11using ResoniteModLoader ;
22using HarmonyLib ;
33using FrooxEngine ;
4+ using Elements . Core ;
5+ using LZ4 ;
46
57namespace FastSync ;
68
79public partial class FastSync : ResoniteMod
810{
11+ [ AutoRegisterConfigKey ]
12+ public static readonly ModConfigurationKey < bool > enable =
13+ new ( "enable" , "Enable FastSync" , ( ) => true ) ;
14+
915 public override string Name => "FastSync" ;
1016 public override string Author => "Raidriar796" ;
1117 public override string Version => "1.0.0" ;
@@ -14,9 +20,58 @@ public partial class FastSync : ResoniteMod
1420
1521 public override void OnEngineInit ( )
1622 {
17- Harmony harmony = new Harmony ( "net.raidriar796.FastSync" ) ;
23+ Harmony harmony = new ( "net.raidriar796.FastSync" ) ;
1824 Config = GetConfiguration ( ) ;
1925 Config ? . Save ( true ) ;
2026 harmony . PatchAll ( ) ;
2127 }
28+
29+ [ HarmonyPatch ( typeof ( SyncMessage ) , "Encode" ) ]
30+ private class EncodePatch
31+ {
32+ private static bool Prefix ( ref RawOutMessage __result , SyncMessage __instance )
33+ {
34+ // Run the original method if the mod is not enabled
35+ if ( ! Config ! . GetValue ( enable ) ) return true ;
36+
37+ // Reconstruction of the original method
38+ RawOutMessage raw = new ( ) ;
39+ raw . UseReliable = __instance . Reliable ;
40+ raw . Background = __instance . Background ;
41+ MemoryStream stream = SyncMessage . StreamManager . GetStream ( ) ;
42+ BinaryWriterX writer = Pool . BorrowBinaryWriter ( stream ) ;
43+ byte header = ( byte ) __instance . SyncMessageType ;
44+ if ( __instance . ShouldCompress )
45+ {
46+ header |= 128 ;
47+ }
48+ writer . Write ( header ) ;
49+ writer . Write7BitEncoded ( __instance . SenderStateVersion ) ;
50+ writer . Write7BitEncoded ( __instance . SenderSyncTick ) ;
51+ LZ4Stream lz4stream = null ! ;
52+ if ( __instance . ShouldCompress )
53+ {
54+ // This is where the magic happens
55+ lz4stream = new LZ4Stream ( stream , LZ4StreamMode . Compress , LZ4StreamFlags . IsolateInnerStream , 1048576 , SyncMessage . _lz4BufferAllocator ) ;
56+ writer . TargetStream = lz4stream ;
57+ }
58+ __instance . EncodeData ( writer ) ;
59+ Pool . Return ( ref writer ) ;
60+ if ( lz4stream != null )
61+ {
62+ lz4stream . Dispose ( ) ;
63+ }
64+ raw . Data = stream ;
65+ __instance . EncodedSize = ( int ) stream . Length ;
66+ foreach ( IConnection t in __instance . Targets )
67+ {
68+ raw . Targets . Add ( t ) ;
69+ }
70+ // Change result of the original method
71+ __result = raw ;
72+
73+ // Skip original method
74+ return false ;
75+ }
76+ }
2277}
0 commit comments