* feature: perf: Global Interest Management. NetworkVisibility components per-NetworkIdentity obsoleted and replaced by one global InterestManagement component on NetworkManager instead. Significantly easier to understand, allows for spatial hashing (~30x faster) and reduces amount of components in the worlds (for 1k objects, we avoid 1k NetworkVisibility components now).
* Benchmark scene uses new Spatial Hashing
* improve message
* Update Assets/Mirror/Components/InterestManagement/SpatialHashing/Grid2D.cs
Co-authored-by: MrGadget <9826063+MrGadget1024@users.noreply.github.com>
* NetworkIdentity.forceHidden changed to enum to prepare for forceShown
* NetworkIdentity.Visibility: added ForceShown option
Co-authored-by: MrGadget <9826063+MrGadget1024@users.noreply.github.com>
* perf: Batching. Batches message into Transport.GetMaxPacketSize sized chunks and sends them every batchInterval
* don't log time
* Transport.GetMaxBatchSize and kcp override it to always use MTU
* remove comment
* NetworkConnectionToClient tests
* Test: Send_BatchesUntilUpdate
* Test: Send_BatchesUntilInterval
* fix: initialize last send time with NetworkTime.time
* better comment
* fixing reset after sending batch
Need to reset both position and length
* revert the transportreceive change for localconnections.
before it didn't work because of the length bug that is fixed now.
* added test to avoid length bug in the future
* optional
* enable batching in benchmark demo for max scale
Co-authored-by: James Frowen <jamesfrowendev@gmail.com>
- fix: unreliable messages reset timeout now too
- perf: KcpConnection OnCheckEnabled callback changed to a simple 'paused' boolean.
This is faster than invoking a Func<bool> every time and allows us to fix#8 more
easily later by calling .Pause/.Unpause from OnEnable/OnDisable in MirrorTransport.
- fix#8: Unpause now resets timeout to fix a bug where Mirror would pause kcp,
change the scene which took >10s, then unpause and kcp would detect the lack of
any messages for >10s as timeout. Added test to make sure it never happens again.
- MirrorTransport: statistics logging for headless servers
- Mirror Transport: Send/Receive window size increased once more from 2048 to 4096.
this avoids the first line of the stacktrace being on the same line as the Exception. this is better because the Exception line could be line and it is easy to miss the first stack trace line.
* moving FindPath to editor scripts
this allows this function to be used by other scripts
* Update Assets/Mirror/Editor/EditorHelper.cs
* removing extra using
* fix: prevent allocation of massive array
A poison message could contain an invalid length causing us to allocate massive arrays
* throw exception instead
* Update Assets/Mirror/Runtime/NetworkReader.cs
Co-authored-by: James Frowen <jamesfrowendev@gmail.com>
* test for ReadArray
* swapping order of equation so that length doesnt overflow
* adding test case
* adding more tests for array length
* swapping order
* fixing expected message
Co-authored-by: James Frowen <jamesfrowendev@gmail.com>
Unity has added new private LogWarning methods in 2020.2 which causes weaver to find the wrong method. Checking the parameters as we as the name will find the correct method.
fixes: https://github.com/vis2k/Mirror/issues/2366
* adding MakeGeneric method
* adding tests for NB syncvar+hook
* adding functions to NetworkBehaviour
* getting references to new functions
* fixing NB read so it always reads same number of bytes as write
* adding backing field and serialize for Nb Syncvar
* extra test
* adding ignore to transform test
* fixing test
Seems like this has come up a few times so here is a commit to sort this out.
We shouldn't have to worry about the order of the using, we should just let plugins automatically sort them. They are sorted into alphabetical order expect for system becase we have `dotnet_sort_system_directives_first = true` enabled in `.editorconfig`
* fix: stopping values being reset before OnDestory is called
* matches server side logic
* if an object is being fully destroyed it doesn't need its values to be reset
* adding read/write functions
* adding method to get WriteNetworkBehaviour
* adding methods to weavertypes
* adding method to get ReadNetworkBehaviour
* weaver test for NetworkBehaviour in RPC
* renaming var
* writing tests to make sure read/write works
* registering functions
* changing function and adding comment
* checking any writer is set
* adding Description to test
* collection test
* fixing call
* removing errors, networkbehaviour as read/write
* adding test to use the reader that weaver generates
* fixing import
* simplifying test
* removing null from spawned
* improving throw
* adding code coverage
* applying code suggestions
* Using TypeReference with IEqualityComparer instead of string to keep reference to type
* using targetType to initialize write/read functions
* test to make sure write function is set
```
UnityException: ToString is not allowed to be called from a MonoBehaviour constructor (or instance field initializer), call it in Awake or Start instead. Called from MonoBehaviour 'GamePlay' on game object 'GamePlay'.
See "Script Serialization" page in the Unity Manual for further details.
UnityEngine.Object.ToString () (at <a979f18d51af41179d12b797e8c5be14>:0)
UnityEngine.Logger.GetString (System.Object message) (at <a979f18d51af41179d12b797e8c5be14>:0)
UnityEngine.Logger.LogError (System.String tag, System.Object message) (at <a979f18d51af41179d12b797e8c5be14>:0)
Mirror.NetworkBehaviour.InitSyncObject (Mirror.SyncObject syncObject) (at Assets/System/3rdParty/Mirror/Runtime/NetworkBehaviour.cs:168)
myGame.GamePlay..ctor () (at Assets/System/GamePlay.cs:18)
```
- consolidate nested if
- set kinematic by default on scene objects
- set kinematic false on server in AddForce::Start
- added field for Rigidbody component reference via inspector
- eliminated calling GetComponent every frame
- set SyncInverval to zero on both NetworkTransforms and NetworkRigidbody
* Changed oldColor to underscore in hook in RandomColor
* WIP
* feat: Updated Basic Example
- PlayerUI is now separated from player object
- PlayerUI is event driven from the Player object
- PlayerUI is locally instantiated, instead of networked
- added border to players panel
* fixed code smells
* moved playersList to BasicNetManager
* fixed compile error and improved layout
* fixed tooltips
Co-authored-by: MrGadget1024 <chris@clevertech.net>
Having near identical lines in these functions is confusing at first glace. Having RegisterWriteFunc call Register makes it more clear exactly what is going on
* formatting
* moving comment about buffer next to buffer
* moving comment to doc comment
* doc comment position
* doc comments for Length
* doc comments for ReadBlittable
* doc comments for ReadBytes
* doc comments for ReadBytesSegment
* doc comments for ToString
* doc comments for NetworkReaderExtensions
* comments for ReadString
* exception comments for read bytes/segement
* fixing comment
* fix(weaver): Warning for multiple write/read functions for the same type
Adding warning message when trying to register a write or read function for a type that is already in dictionary. Previously weaver would be silent about this making it hard to know when an extension method overrides another one.
* test for warnings
* checking buffer length is atleast 2
disconnect if invalid message
* using const instead of magic number
Adding test to make sure that writing id is the same size as IdSize
* adding comment
* renaming to HeaderSize
* delegate and callbacks instead of unityevent
* using callbacks in Mirror
* Using new callbacks instead of events
* moving methods next to each other in NetworkClient
* moving add/remove to methods in NetworkServer
* replacing uses of events within transports and tests
* fixing tests
* fixing more tests
* replacing delegates with actions
* adding comments to show what action variable's are
* removing extra function created in rebase
* renaming callbacks
* adding reset methods so that actions arn't null
* fixing rename
* breaking defines
* Update Assets/Mirror/Runtime/Transport/KCP/MirrorTransport/KcpTransport.cs
* Update KcpTransport.cs
* Update Transport.cs
* removing ResetHandlers methods
transports can now call events after stop is called
Co-authored-by: vis2k <info@noobtuts.com>
* adding try/catch to hanlder
user code can throw errors.
* Update Assets/Mirror/Runtime/MessagePacker.cs
* Update Assets/Mirror/Runtime/MessagePacker.cs
* test for command that throws
* disconnecting client after Exception in message handler
Co-authored-by: vis2k <info@noobtuts.com>
Generating readers and writers for structs in other assemblies
could sometimes cause a
```
System.ArgumentException: Member 'xxx' is declared in another module and needs to be imported
```
This in particular affected unity mathematics.
fixes#2406
* Round trip time bool and tooltip.
I've added this RTT boolean and a tooltip, might clear up some confusion for future users.
Many believe ping is time to server, and rtt is ping pong.
* Round trip time bool and tooltip.
I've added this RTT boolean and a tooltip, might clear up some confusion for future users.
Many believe ping is time to server, and rtt is ping pong.
* Round trip time bool and tooltip.
I've added this RTT boolean and a tooltip, might clear up some confusion for future users.
Many believe ping is time to server, and rtt is ping pong.
* Round trip time bool and tooltip.
I've added this RTT boolean and a tooltip, might clear up some confusion for future users.
Many believe ping is time to server, and rtt is ping pong.
Changed the default 100ms to 10ms
Double checked with Vis in Discord "tooltip is meant to say 10ms."
Already seen one screenshot of a Discord user that set this from 10 to 100, due to the typo, believing 100 was meant to be default and not 10.
* NetworkWriter consistency: Write(U)Ints moved to static extension methods for consistency with all the other writer functions like WriteUInt16.
This makes life easier because weaver looks for all Write(U)Int functions in the same place. Otherwise packed writes can't be removed in a later PR without breaking weaver (which is also evidence for being bad design before)
* NetworkReader consistency: removed redundant Read(U)Ints
* breaking: Obsolete Read/WritePacked functions and use the regular ones everywhere. We are not bandwidth limited but CPU limited, so this is good. Those were overly complex and worst of all they cause non deterministic packet sizes. a player packet might spawn fine in editor, but 1 month into production it might very well hit the 1200 MTU limit if health is suddenly >241 or the Vector2Int position is somewhere else. This was insanity.
* NetworkWriter consistency: Write(U)Ints moved to static extension methods for consistency with all the other writer functions like WriteUInt16.
This makes life easier because weaver looks for all Write(U)Int functions in the same place. Otherwise packed writes can't be removed in a later PR without breaking weaver (which is also evidence for being bad design before)
* NetworkReader consistency: removed redundant Read(U)Ints
* Return and log warning on start already started client or server
* Apply suggestions from code review, Always check for client and server active state
Co-authored-by: MrGadget <9826063+MrGadget1024@users.noreply.github.com>
* Update Assets/Mirror/Runtime/NetworkManager.cs
* Update Assets/Mirror/Runtime/NetworkManager.cs
* Update Assets/Mirror/Runtime/NetworkManager.cs
* Update Assets/Mirror/Runtime/NetworkManager.cs
* Update Assets/Mirror/Runtime/NetworkManager.cs
* Update Assets/Mirror/Runtime/NetworkManager.cs
Co-authored-by: MrGadget <9826063+MrGadget1024@users.noreply.github.com>
Co-authored-by: vis2k <info@noobtuts.com>
* adding kcp2k asmdef
marked with allowUnsafeCode
* adding reference to new kcp2k asmdef, and unmarking allowUnsafeCode
* adding public gettings for list/queue count
* Update Assets/Mirror/Runtime/Transport/KCP/MirrorTransport/KcpTransport.cs
Co-authored-by: vis2k <info@noobtuts.com>
Adding compression methods for Quaternion and floats. These methods can be used to decrease size of Quaternions before sending the value over the network.
ScaleToUInt method can be used to compress float from 32 bits to the range given to the method. This can be used to compress Vector3 if the bounds of the world are known and fixed before runtime.
* fix: fixing sceneId when using BuildPipeline.BuildPlayer with incorrect case in path
BuildPipeline.BuildPlayer takes an array of strings for scene paths. Unity will find the scene with the path case insensitive but path case is case sensitive.
This change would make it so that these 2 paths have the same hash
```
Assets/Scenes/Forest.unity
Assets/Scenes/forest.unity
```
* Adding full comment for ToLower
* Update NetworkIdentity.cs
Co-authored-by: vis2k <info@noobtuts.com>
* Making ReaderWriterProcessor return if it found custom functions (not counting ones in mirror.dll)
* Always writing generateContainerClass if modified
* processing PropertySiteProcessor if either ReaderWriterProcessor or WeaveModule are successful
* creating generateContainerClass in WeaverList constructor
* Moving new WeaverList to after WeaverTypes.SetupTargetTypes
* feat: adding MiddlewareTransport
* Allows Middleware to be created at the transport layer
* Middleware can choice which methods they want to override and which to let inner handle
* using expression bodies
* fix: improving errors in SendTargetRPCInternal
* now give error when connection is null
* updating error message to accurately explain what went wrong
* clientOwnedObjects is a hash set which doesn't need to be disposed
* DestroyOwnedObjects already clears list which is called by networkmanager when connection disconnects
Co-authored-by: vis2k <info@noobtuts.com>
* moving check to base connection because it could be used for either
* renaming to IsAlive
* passing in timeout so it doesn't need to check NetworkServer
* updating doc comment
The code to serialize lists, arrays, and array segments is now in the runtime instead of generated in the weaver.
removes about 300 LOC of weaver witchcraft
* perf: use built in == instead of unity one
should be the same performance as #2325 without the complexity
* more readable version
* more readable version
* Intial commit
see https://github.com/MirrorNetworking/SimpleWebTransport for full git histroy
* Update main.yml
Adding SimpleWebTransport to coverage exclusions
* fully ignoring SimpleWebTransport from sonarcloud
SimpleWebTransport has sonarcloud running on its own repo
* using Buffer.BlockCopy
* SimpleWebTransport v0.4.1
* making error messages use LogError (MirrorNetworking/SimpleWebTransport@5f0096c)
* messages with length of 1 can be recieved by the client (MirrorNetworking/SimpleWebTransport@4237fc4)
* stopping un-needed error logs after disconnect (MirrorNetworking/SimpleWebTransport@25ff190)
* updating readme
* SimpleWebTransport v0.5.0
* adding missing warn level to Log.Levels (MirrorNetworking/SimpleWebTransport@0f68498)
* Allowing multiple instances of javascript client (MirrorNetworking/SimpleWebTransport#14) (MirrorNetworking/SimpleWebTransport@cc6e513)
* SimpleWebTransport v0.5.8
* Stopping send error when client disconnects
* Adding buffer pool
* Using ArrayBuffer for receive
* Removing info and verbose logging by default so performance isnt effected in editor or development builds.
* Making WebSocketClientStandAlone use timeouts from inspector
* Removing incorrect header from inspector
* Removing readonly from logger so that it can be set
* Fixing use of Interlocked in buffer pools
* using ManualResetEventSlim
* making Log.Exception always be logged
* SimpleWebTransport v0.6.0
* Trying to fix error when connection is closed
* Increase arraybuffer speed
* Removing shared buffers from server handshake
* Improving debug logging
* fixing code smells
* SimpleWebTransport v0.6.1
* making sure pending connection work when stop serve is called
* removing exception that isnt directly thrown by this method
this breaks docfx for some reason
* Adding new websocket transport soon that doesn't depend on library
* Code for old transport can now be found here https://github.com/MirrorNetworking/NinjaWebSocketsTransport
* We shouldn't need to replace with empty files from store as having this in project should not break things
* perf: NetworkIdentity DirtyComponentsMask code removed entirely. OnSerialize now includes the component index as byte before serializing each component. Faster because we avoid GetDirtyComponentsMask() and GetSyncModeObserversMask() calculations. Increases allowed NetworkBehaviour components from 64 to 255. Bandwidth is now smaller if <8 components, and larger if >8 components. Code is significantly more simple.
* Update Assets/Mirror/Runtime/NetworkIdentity.cs
Co-authored-by: James Frowen <jamesfrowendev@gmail.com>
Co-authored-by: James Frowen <jamesfrowendev@gmail.com>
* Users must initialize syncobjects (#391)
Previously we initialized syncobjects, so this is valid:
```cs
public class Pepe : NetworkBehavior {
public SyncList<int> mylist;
}
```
With this change, users must initialize their own fields:
```cs
public class Pepe : NetworkBehavior {
public SyncList<int> mylist = new SyncList<int>();
}
```
BREAKING CHANGE: You must initialize all your SyncLists
* Add null check
* This is no longer a weaver error
* Update Assets/Mirror/Runtime/NetworkBehaviour.cs
Co-authored-by: James Frowen <jamesfrowendev@gmail.com>
* Remove unnecesary using
Co-authored-by: James Frowen <jamesfrowendev@gmail.com>
* Server Teleport Enchancement for NetworkTransform
Related to this issue: https://github.com/vis2k/Mirror/issues/2200
* Improvements on NetworkTransformBase
We disable clientAuthority until teleportation is finished and acknowledged. We set the goal and start data points to null before teleportation.
We set the clientAuthority back to it's initial value registered on server, both on the server and client side; it seems like we don't need to change it to anything on Client side because to my understanding clientAuthortiy is not affecting anything on client side. I may be wrong but still it is a great practice to set it back to it's initial value just in case...
* Added teleportation with rotation
I forgot to add a rotation functionality on my previous commit. It wouldn't be a teleportation without also changing the rotation. If provided a rotation input it will teleport with a rotation, if not it will simply protect the original rotation before the teleportation.
* Removed my debug statement
I forgot to remove the debug log statement lol silly me
* fixing up code
* resetting goal and last pos on server and client
* renaming variables
* making sure TeleportFinished can't request authority at any time
* moving teleport block
* removing duplicate lines
Co-authored-by: Emre Bugday <47198270+EmreB99@users.noreply.github.com>
* breaking: no need to override Serialize/Deserialize in messages
Messages no longer serilize themselves. This has been decoupled. Serializing a message is now done
via readers and writers, which can be either generated or user provided.
This lifts some restrictions,
* you no longer need to have a default constructor in messages
* Messages types can be recursive
* struct Messages don't need to provide an empty Serialize and Deserialize method
Before:
```cs
public struct ReadyMessage : IMessageBase
{
public void Deserialize(NetworkReader reader) { }
public void Serialize(NetworkWriter writer) { }
}
```
After:
```cs
public struct ReadyMessage : IMessageBase
{
}
```
BREAKING CHANGE: Messages must be public
BREAKING CHANGE: Use custom reader and writer instead of Serialize/Deserialize methods
* Remove unused method
* remove unused methods
* remove unused methods
* make all messages struct
* Fix test code generator
* Get rid of MessageBase
* Rename IMessageBase -> NetworkMessage
* add MessageBase as obsolete
* Use a default request
* Empty file to make asset store happy
* Apply suggestions from code review
Co-authored-by: James Frowen <jamesfrowendev@gmail.com>
Co-authored-by: James Frowen <jamesfrowendev@gmail.com>
* Fixed OnStopClient not being called on Client Side
* Moved identity.OnStopClient() two scopes above
Co-authored-by: Emre Bugday <47198270+EmreB99@users.noreply.github.com>
* feat: Use SyncLists directly
Previously, you had to write an intermediary class to use synclists, syncsets and syncdictionaries.
The weaver would populate that intermediary class with a serialization and deserialization method
This PR gets rid of 90% of the weaver code for synclists.
There is no need to generate these methods anymore.
Instead the lists use `writer.Write<T>` and `read.read<T>` to serialize their Data.
Since there is no code generate in synclists, you can now use the synclists directly instead
of subclassing them.
BEFORE:
```cs
public class MyComponent : NetworkBehaviour {
// nonsense class to make the weaver happy
class SyncListData : Synclist<Data> {}
SyncListData mySyncList;
}
```
AFTER:
```cs
public class MyComponent : NetworkBehaviour {
Synclist<Data> mySyncList;
}
```
* linting
* feat: Use SyncLists directly (no overrides)
Previously, you had to write an intermediary class to use synclists and syncdictionaries.
The weaver would populate that intermediary class with a serialization and deserialization method
This PR gets rid of 90% of the weaver code for synclists.
There is no need to generate these methods anymore.
Instead the lists use `writer.Write<T>` and `read.read<T>` to serialize their Data.
Since there is no code generate in synclists, you can now use the synclists directly instead
of subclassing them.
Same as #2305 ,but it removes the deprecated Serialize and Deserialize methods from syncobjects,
This way you get a nice compiler error for the code that no longer works, instead of a warning you might accidentally ignore.
BEFORE:
```cs
public class MyComponent : NetworkBehaviour {
// nonsense class to make the weaver happy
class SyncListData : Synclist<Data> {}
SyncListData mySyncList;
}
```
AFTER:
```cs
public class MyComponent : NetworkBehaviour {
Synclist<Data> mySyncList;
}
```
BREAKING CHANGE: Serialize and Deserialize methods in synclists don't do anything anymore
* Remove old comment
* Fix compilatio error
Currently in mirror, there is no way for Mirror itself to invoke
readers and writers for types it does not know about.
This causes us to have to generate code for lists, dictionaries and messages.
This PR makes it so that if there is a reader and writer anywhere in the
code for type X, then the writer can be invoked like this:
```cs
X x = ...;
writer.Write<X>(x);
```
and the reader can be invoked like this:
```cs
X x = reader.Read<X>();
```
* fix: generic arguments lookup
The weaver was not able to figure out the synclist type in code like this:
```cs
public class SomeList<G, T> : SyncList<T> { }
public class SomeListInt : SomeList<string, int> { }
```
This code fixes that problem, and greatly reduces the complexity
of argument lookup.
* linting
Remove all the recursionCount nonsense.
This was added to prevent infinite recursion with types that reference themselves.
No need to check anymore, the weaver can generate readers and writers for types that reference themselves such as:
```cs
class Tree {
Tree child1;
Tree child2;
}
```
This works by the weaver doing it the way the compiler does: Create a function first, memoize it, then write the body. If the body needs the function, it will get itself and issue a call to itself.
Currently, whenever we want to serialize an enum,
we simply serialize the underlying type (byte, short, int)
This works fine, but in order to get the reader and writer
at runtime I need a function for each type.
With this PR, we generate a reader and writer function for enums too,
the function body simply calls the underlying reader and writer.
* throwing Exception instead of returning null
* re-adding null check until later PR
* removing error from test
* removing extra error
* adding comment
* replacing error with throw for abstact
The plan is to remove WeaverLists at some point so moving the functions
out of weaver to here for now and then move them closer to where they
are actaully used when we start to remove WeaverLists.
# Before
This is hard to read:
```
if (ca.AttributeType.FullName == typeof(Mirror.CommandAttribute).FullName) {
...
}
```
# After
```
if (ca.AttributeType.Is<Mirror.CommandAttribute>()) {
...
}
```
# Before
WeaverTypes declared a static variable like this:
```cs
public static TypeReference int32Type;
```
Weavertypes then loaded the variable in SetupTargetTypes like this:
```cs
int32Type = ImportSystemModuleType(currentAssembly, systemModule, "System.Int32");
```
Note we lookup the type with a string, any typo there won't be detected until the code is executed. It will also not be found by the IDE when you click "find references", or when you refactor.
Then we use it like this:
```cs
var intType = WeaverTypes.int32Type;
```
This is a DRY violation: I have to modify 3 different code sections just to say that I want the int32 type.
# After
Get rid of all the duplication, and use the type instead of a string:
```cs
var intType = WeaverTypes.Import<int>();
```
No need for static variable, or to add it in SetupTargetTypes.