├── .gitignore
├── ProjectSettings
├── ProjectVersion.txt
├── ClusterInputManager.asset
├── NetworkManager.asset
├── TimeManager.asset
├── EditorBuildSettings.asset
├── UnityAdsSettings.asset
├── AudioManager.asset
├── EditorSettings.asset
├── TagManager.asset
├── UnityConnectSettings.asset
├── DynamicsManager.asset
├── NavMeshAreas.asset
├── Physics2DSettings.asset
├── GraphicsSettings.asset
├── QualitySettings.asset
├── InputManager.asset
└── ProjectSettings.asset
├── Assets
├── Plugins
│ ├── protobuf
│ │ ├── Google.Protobuf.dll
│ │ ├── Google.Protobuf.xml.meta
│ │ └── Google.Protobuf.dll.meta
│ ├── kcpForUnity.meta
│ ├── protobuf.meta
│ └── kcpForUnity
│ │ ├── common.meta
│ │ ├── TcpSocket.cs.meta
│ │ ├── UdpSocket.cs.meta
│ │ ├── common
│ │ ├── kcp.cs.meta
│ │ ├── ByteBuf.cs.meta
│ │ ├── kcpUtil.cs.meta
│ │ ├── testUtil.cs.meta
│ │ ├── ByteBufSync.cs.meta
│ │ ├── BytePacker.cs.meta
│ │ ├── ObjectPool.cs.meta
│ │ ├── QueueSync.cs.meta
│ │ ├── ObjectPoolSync2.cs.meta
│ │ ├── ByteBufSync.cs
│ │ ├── testUtil.cs
│ │ ├── ObjectPoolSync2.cs
│ │ ├── ObjectPool.cs
│ │ ├── kcpUtil.cs
│ │ ├── BytePacker.cs
│ │ ├── QueueSync.cs
│ │ ├── ByteBuf.cs
│ │ └── kcp.cs
│ │ ├── TcpSocket.cs
│ │ └── UdpSocket.cs
├── Scene
│ └── Test.unity.meta
├── Plugins.meta
├── Scene.meta
├── Scripts.meta
└── Scripts
│ ├── Test.meta
│ ├── libs.meta
│ └── Test
│ ├── TestKcp.cs.meta
│ ├── TestTcp.cs.meta
│ ├── TestConfig.cs.meta
│ ├── TestConfig.cs
│ ├── TestTcp.cs
│ └── TestKcp.cs
├── README.md
├── kcpforunity.sln
├── kcpforunity.csproj
├── kcpforunity.Plugins.csproj
└── LICENSE
/.gitignore:
--------------------------------------------------------------------------------
1 | /.vs
2 | /Library
3 | /Android
4 | /Temp
5 |
--------------------------------------------------------------------------------
/ProjectSettings/ProjectVersion.txt:
--------------------------------------------------------------------------------
1 | m_EditorVersion: 5.4.5f1
2 | m_StandardAssetsVersion: 0
3 |
--------------------------------------------------------------------------------
/Assets/Plugins/protobuf/Google.Protobuf.dll:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/advancer68/kcp-csharp-unity3d/HEAD/Assets/Plugins/protobuf/Google.Protobuf.dll
--------------------------------------------------------------------------------
/ProjectSettings/ClusterInputManager.asset:
--------------------------------------------------------------------------------
1 | %YAML 1.1
2 | %TAG !u! tag:unity3d.com,2011:
3 | --- !u!236 &1
4 | ClusterInputManager:
5 | m_ObjectHideFlags: 0
6 | m_Inputs: []
7 |
--------------------------------------------------------------------------------
/ProjectSettings/NetworkManager.asset:
--------------------------------------------------------------------------------
1 | %YAML 1.1
2 | %TAG !u! tag:unity3d.com,2011:
3 | --- !u!149 &1
4 | NetworkManager:
5 | m_ObjectHideFlags: 0
6 | m_DebugLevel: 0
7 | m_Sendrate: 15
8 | m_AssetToPrefab: {}
9 |
--------------------------------------------------------------------------------
/README.md:
--------------------------------------------------------------------------------
1 | #kcpForUnity
2 | KCP - A Fast and Reliable ARQ Protocol
3 |
4 | ref:
5 | c: skywind3000 [KCP](https://github.com/skywind3000/kcp)
6 | c#: limpo1989 [kcp-csharp](https://github.com/limpo1989/kcp-csharp)
--------------------------------------------------------------------------------
/ProjectSettings/TimeManager.asset:
--------------------------------------------------------------------------------
1 | %YAML 1.1
2 | %TAG !u! tag:unity3d.com,2011:
3 | --- !u!5 &1
4 | TimeManager:
5 | m_ObjectHideFlags: 0
6 | Fixed Timestep: 0.02
7 | Maximum Allowed Timestep: 0.33333334
8 | m_TimeScale: 1
9 |
--------------------------------------------------------------------------------
/Assets/Scene/Test.unity.meta:
--------------------------------------------------------------------------------
1 | fileFormatVersion: 2
2 | guid: bee3e1d92a0d1b740b9e6a1ac3e9b2c9
3 | timeCreated: 1495179511
4 | licenseType: Pro
5 | DefaultImporter:
6 | userData:
7 | assetBundleName:
8 | assetBundleVariant:
9 |
--------------------------------------------------------------------------------
/Assets/Plugins.meta:
--------------------------------------------------------------------------------
1 | fileFormatVersion: 2
2 | guid: 93cb4801b04e2954da1cd8f06f196161
3 | folderAsset: yes
4 | timeCreated: 1495440186
5 | licenseType: Pro
6 | DefaultImporter:
7 | userData:
8 | assetBundleName:
9 | assetBundleVariant:
10 |
--------------------------------------------------------------------------------
/Assets/Plugins/protobuf/Google.Protobuf.xml.meta:
--------------------------------------------------------------------------------
1 | fileFormatVersion: 2
2 | guid: 73a5cdafe88b4da418f48d6b5324ca1a
3 | timeCreated: 1495440524
4 | licenseType: Pro
5 | TextScriptImporter:
6 | userData:
7 | assetBundleName:
8 | assetBundleVariant:
9 |
--------------------------------------------------------------------------------
/Assets/Scene.meta:
--------------------------------------------------------------------------------
1 | fileFormatVersion: 2
2 | guid: fd4e156182778f649a7273d2cbf1548b
3 | folderAsset: yes
4 | timeCreated: 1495179517
5 | licenseType: Pro
6 | DefaultImporter:
7 | userData:
8 | assetBundleName:
9 | assetBundleVariant:
10 |
--------------------------------------------------------------------------------
/Assets/Scripts.meta:
--------------------------------------------------------------------------------
1 | fileFormatVersion: 2
2 | guid: 7949ed2b9a9374a478d424f370ba29c5
3 | folderAsset: yes
4 | timeCreated: 1495180449
5 | licenseType: Pro
6 | DefaultImporter:
7 | userData:
8 | assetBundleName:
9 | assetBundleVariant:
10 |
--------------------------------------------------------------------------------
/Assets/Scripts/Test.meta:
--------------------------------------------------------------------------------
1 | fileFormatVersion: 2
2 | guid: b7ecf4a56283c13488d56a0220af3048
3 | folderAsset: yes
4 | timeCreated: 1495180712
5 | licenseType: Pro
6 | DefaultImporter:
7 | userData:
8 | assetBundleName:
9 | assetBundleVariant:
10 |
--------------------------------------------------------------------------------
/Assets/Scripts/libs.meta:
--------------------------------------------------------------------------------
1 | fileFormatVersion: 2
2 | guid: f79dc91e1efb5f843a136dd27171242b
3 | folderAsset: yes
4 | timeCreated: 1495440110
5 | licenseType: Pro
6 | DefaultImporter:
7 | userData:
8 | assetBundleName:
9 | assetBundleVariant:
10 |
--------------------------------------------------------------------------------
/Assets/Plugins/kcpForUnity.meta:
--------------------------------------------------------------------------------
1 | fileFormatVersion: 2
2 | guid: c834babc55162e641a82859014a1bc0e
3 | folderAsset: yes
4 | timeCreated: 1495877280
5 | licenseType: Pro
6 | DefaultImporter:
7 | userData:
8 | assetBundleName:
9 | assetBundleVariant:
10 |
--------------------------------------------------------------------------------
/Assets/Plugins/protobuf.meta:
--------------------------------------------------------------------------------
1 | fileFormatVersion: 2
2 | guid: 9625fdbca3527334f9f0e285644f68e2
3 | folderAsset: yes
4 | timeCreated: 1495440203
5 | licenseType: Pro
6 | DefaultImporter:
7 | userData:
8 | assetBundleName:
9 | assetBundleVariant:
10 |
--------------------------------------------------------------------------------
/ProjectSettings/EditorBuildSettings.asset:
--------------------------------------------------------------------------------
1 | %YAML 1.1
2 | %TAG !u! tag:unity3d.com,2011:
3 | --- !u!1045 &1
4 | EditorBuildSettings:
5 | m_ObjectHideFlags: 0
6 | serializedVersion: 2
7 | m_Scenes:
8 | - enabled: 0
9 | path: Assets/Scene/Main.unity
10 |
--------------------------------------------------------------------------------
/Assets/Plugins/kcpForUnity/common.meta:
--------------------------------------------------------------------------------
1 | fileFormatVersion: 2
2 | guid: 552b7ec5d4dcd8441b3acdeab0258f74
3 | folderAsset: yes
4 | timeCreated: 1495180427
5 | licenseType: Pro
6 | DefaultImporter:
7 | userData:
8 | assetBundleName:
9 | assetBundleVariant:
10 |
--------------------------------------------------------------------------------
/ProjectSettings/UnityAdsSettings.asset:
--------------------------------------------------------------------------------
1 | %YAML 1.1
2 | %TAG !u! tag:unity3d.com,2011:
3 | --- !u!292 &1
4 | UnityAdsSettings:
5 | m_ObjectHideFlags: 0
6 | m_Enabled: 0
7 | m_InitializeOnStartup: 1
8 | m_TestMode: 0
9 | m_EnabledPlatforms: 4294967295
10 | m_IosGameId:
11 | m_AndroidGameId:
12 |
--------------------------------------------------------------------------------
/Assets/Scripts/Test/TestKcp.cs.meta:
--------------------------------------------------------------------------------
1 | fileFormatVersion: 2
2 | guid: c5e70c48cb8e2d54dbceee29a41d6b06
3 | timeCreated: 1495096350
4 | licenseType: Pro
5 | MonoImporter:
6 | serializedVersion: 2
7 | defaultReferences: []
8 | executionOrder: 0
9 | icon: {instanceID: 0}
10 | userData:
11 | assetBundleName:
12 | assetBundleVariant:
13 |
--------------------------------------------------------------------------------
/Assets/Scripts/Test/TestTcp.cs.meta:
--------------------------------------------------------------------------------
1 | fileFormatVersion: 2
2 | guid: ef2d66e672f08e9489e4ac46ed3e5d72
3 | timeCreated: 1495419299
4 | licenseType: Pro
5 | MonoImporter:
6 | serializedVersion: 2
7 | defaultReferences: []
8 | executionOrder: 0
9 | icon: {instanceID: 0}
10 | userData:
11 | assetBundleName:
12 | assetBundleVariant:
13 |
--------------------------------------------------------------------------------
/Assets/Scripts/Test/TestConfig.cs.meta:
--------------------------------------------------------------------------------
1 | fileFormatVersion: 2
2 | guid: 015b46a5e6d82d34f81c807f32fc54a0
3 | timeCreated: 1495419370
4 | licenseType: Pro
5 | MonoImporter:
6 | serializedVersion: 2
7 | defaultReferences: []
8 | executionOrder: 0
9 | icon: {instanceID: 0}
10 | userData:
11 | assetBundleName:
12 | assetBundleVariant:
13 |
--------------------------------------------------------------------------------
/Assets/Plugins/kcpForUnity/TcpSocket.cs.meta:
--------------------------------------------------------------------------------
1 | fileFormatVersion: 2
2 | guid: 10cf2dcbf58c12c42853e47219203ea6
3 | timeCreated: 1495622016
4 | licenseType: Pro
5 | MonoImporter:
6 | serializedVersion: 2
7 | defaultReferences: []
8 | executionOrder: 0
9 | icon: {instanceID: 0}
10 | userData:
11 | assetBundleName:
12 | assetBundleVariant:
13 |
--------------------------------------------------------------------------------
/Assets/Plugins/kcpForUnity/UdpSocket.cs.meta:
--------------------------------------------------------------------------------
1 | fileFormatVersion: 2
2 | guid: db5eabc704831cf4eac6bf017623d17b
3 | timeCreated: 1495180428
4 | licenseType: Pro
5 | MonoImporter:
6 | serializedVersion: 2
7 | defaultReferences: []
8 | executionOrder: 0
9 | icon: {instanceID: 0}
10 | userData:
11 | assetBundleName:
12 | assetBundleVariant:
13 |
--------------------------------------------------------------------------------
/Assets/Plugins/kcpForUnity/common/kcp.cs.meta:
--------------------------------------------------------------------------------
1 | fileFormatVersion: 2
2 | guid: 872d68c2afbd3ff4582bb99ee6844bd4
3 | timeCreated: 1495180428
4 | licenseType: Pro
5 | MonoImporter:
6 | serializedVersion: 2
7 | defaultReferences: []
8 | executionOrder: 0
9 | icon: {instanceID: 0}
10 | userData:
11 | assetBundleName:
12 | assetBundleVariant:
13 |
--------------------------------------------------------------------------------
/Assets/Plugins/kcpForUnity/common/ByteBuf.cs.meta:
--------------------------------------------------------------------------------
1 | fileFormatVersion: 2
2 | guid: 3ed78911739e07547826c4d1f1925ff6
3 | timeCreated: 1495962139
4 | licenseType: Pro
5 | MonoImporter:
6 | serializedVersion: 2
7 | defaultReferences: []
8 | executionOrder: 0
9 | icon: {instanceID: 0}
10 | userData:
11 | assetBundleName:
12 | assetBundleVariant:
13 |
--------------------------------------------------------------------------------
/Assets/Plugins/kcpForUnity/common/kcpUtil.cs.meta:
--------------------------------------------------------------------------------
1 | fileFormatVersion: 2
2 | guid: a1111be059b0cef41bbc7b77a14d9c81
3 | timeCreated: 1495274463
4 | licenseType: Pro
5 | MonoImporter:
6 | serializedVersion: 2
7 | defaultReferences: []
8 | executionOrder: 0
9 | icon: {instanceID: 0}
10 | userData:
11 | assetBundleName:
12 | assetBundleVariant:
13 |
--------------------------------------------------------------------------------
/Assets/Plugins/kcpForUnity/common/testUtil.cs.meta:
--------------------------------------------------------------------------------
1 | fileFormatVersion: 2
2 | guid: 6f7d8b4bed6b32042a55f432969cd999
3 | timeCreated: 1495877701
4 | licenseType: Pro
5 | MonoImporter:
6 | serializedVersion: 2
7 | defaultReferences: []
8 | executionOrder: 0
9 | icon: {instanceID: 0}
10 | userData:
11 | assetBundleName:
12 | assetBundleVariant:
13 |
--------------------------------------------------------------------------------
/Assets/Plugins/kcpForUnity/common/ByteBufSync.cs.meta:
--------------------------------------------------------------------------------
1 | fileFormatVersion: 2
2 | guid: 000c83d39fc478a448f8bb5b49c73b07
3 | timeCreated: 1495962139
4 | licenseType: Pro
5 | MonoImporter:
6 | serializedVersion: 2
7 | defaultReferences: []
8 | executionOrder: 0
9 | icon: {instanceID: 0}
10 | userData:
11 | assetBundleName:
12 | assetBundleVariant:
13 |
--------------------------------------------------------------------------------
/Assets/Plugins/kcpForUnity/common/BytePacker.cs.meta:
--------------------------------------------------------------------------------
1 | fileFormatVersion: 2
2 | guid: 3a3d0368909c09b4cb51fa3d7640ae39
3 | timeCreated: 1495615050
4 | licenseType: Pro
5 | MonoImporter:
6 | serializedVersion: 2
7 | defaultReferences: []
8 | executionOrder: 0
9 | icon: {instanceID: 0}
10 | userData:
11 | assetBundleName:
12 | assetBundleVariant:
13 |
--------------------------------------------------------------------------------
/Assets/Plugins/kcpForUnity/common/ObjectPool.cs.meta:
--------------------------------------------------------------------------------
1 | fileFormatVersion: 2
2 | guid: 6055d393324318e488a05711cc5cc69c
3 | timeCreated: 1495962139
4 | licenseType: Pro
5 | MonoImporter:
6 | serializedVersion: 2
7 | defaultReferences: []
8 | executionOrder: 0
9 | icon: {instanceID: 0}
10 | userData:
11 | assetBundleName:
12 | assetBundleVariant:
13 |
--------------------------------------------------------------------------------
/Assets/Plugins/kcpForUnity/common/QueueSync.cs.meta:
--------------------------------------------------------------------------------
1 | fileFormatVersion: 2
2 | guid: f371177888ea0dd4dacd7ae812c7b417
3 | timeCreated: 1495615403
4 | licenseType: Pro
5 | MonoImporter:
6 | serializedVersion: 2
7 | defaultReferences: []
8 | executionOrder: 0
9 | icon: {instanceID: 0}
10 | userData:
11 | assetBundleName:
12 | assetBundleVariant:
13 |
--------------------------------------------------------------------------------
/Assets/Plugins/kcpForUnity/common/ObjectPoolSync2.cs.meta:
--------------------------------------------------------------------------------
1 | fileFormatVersion: 2
2 | guid: e8298caa14d7fed458eac28830fb1ce8
3 | timeCreated: 1495962139
4 | licenseType: Pro
5 | MonoImporter:
6 | serializedVersion: 2
7 | defaultReferences: []
8 | executionOrder: 0
9 | icon: {instanceID: 0}
10 | userData:
11 | assetBundleName:
12 | assetBundleVariant:
13 |
--------------------------------------------------------------------------------
/Assets/Scripts/Test/TestConfig.cs:
--------------------------------------------------------------------------------
1 | using UnityEngine;
2 | using System.Collections;
3 |
4 | public class TestConfig : MonoBehaviour {
5 | public string host;
6 | public int port;
7 | public string precontent;
8 | // Use this for initialization
9 | void Start () {
10 |
11 | }
12 |
13 | // Update is called once per frame
14 | void Update () {
15 |
16 | }
17 | }
18 |
--------------------------------------------------------------------------------
/ProjectSettings/AudioManager.asset:
--------------------------------------------------------------------------------
1 | %YAML 1.1
2 | %TAG !u! tag:unity3d.com,2011:
3 | --- !u!11 &1
4 | AudioManager:
5 | m_ObjectHideFlags: 0
6 | m_Volume: 1
7 | Rolloff Scale: 1
8 | Doppler Factor: 1
9 | Default Speaker Mode: 2
10 | m_SampleRate: 0
11 | m_DSPBufferSize: 0
12 | m_VirtualVoiceCount: 512
13 | m_RealVoiceCount: 32
14 | m_SpatializerPlugin:
15 | m_DisableAudio: 0
16 | m_VirtualizeEffects: 1
17 |
--------------------------------------------------------------------------------
/Assets/Scripts/Test/TestTcp.cs:
--------------------------------------------------------------------------------
1 | using UnityEngine;
2 | using System.Collections;
3 | using System.Threading;
4 | using System.Collections.Generic;
5 |
6 | public class TestTcp : MonoBehaviour {
7 | // Use this for initialization
8 |
9 | void Start () {
10 | //wthandle = new EventWaitHandle();
11 | //ThreadPool.QueueUserWorkItem()
12 | }
13 |
14 | // Update is called once per frame
15 | void Update () {
16 |
17 | }
18 | }
19 |
--------------------------------------------------------------------------------
/ProjectSettings/EditorSettings.asset:
--------------------------------------------------------------------------------
1 | %YAML 1.1
2 | %TAG !u! tag:unity3d.com,2011:
3 | --- !u!159 &1
4 | EditorSettings:
5 | m_ObjectHideFlags: 0
6 | serializedVersion: 3
7 | m_ExternalVersionControlSupport: Visible Meta Files
8 | m_SerializationMode: 2
9 | m_WebSecurityEmulationEnabled: 0
10 | m_WebSecurityEmulationHostUrl: http://www.mydomain.com/mygame.unity3d
11 | m_DefaultBehaviorMode: 0
12 | m_SpritePackerMode: 2
13 | m_SpritePackerPaddingPower: 1
14 | m_ProjectGenerationIncludedExtensions: txt;xml;fnt;cd
15 | m_ProjectGenerationRootNamespace:
16 |
--------------------------------------------------------------------------------
/ProjectSettings/TagManager.asset:
--------------------------------------------------------------------------------
1 | %YAML 1.1
2 | %TAG !u! tag:unity3d.com,2011:
3 | --- !u!78 &1
4 | TagManager:
5 | serializedVersion: 2
6 | tags: []
7 | layers:
8 | - Default
9 | - TransparentFX
10 | - Ignore Raycast
11 | -
12 | - Water
13 | - UI
14 | -
15 | -
16 | -
17 | -
18 | -
19 | -
20 | -
21 | -
22 | -
23 | -
24 | -
25 | -
26 | -
27 | -
28 | -
29 | -
30 | -
31 | -
32 | -
33 | -
34 | -
35 | -
36 | -
37 | -
38 | -
39 | -
40 | m_SortingLayers:
41 | - name: Default
42 | uniqueID: 0
43 | locked: 0
44 |
--------------------------------------------------------------------------------
/ProjectSettings/UnityConnectSettings.asset:
--------------------------------------------------------------------------------
1 | %YAML 1.1
2 | %TAG !u! tag:unity3d.com,2011:
3 | --- !u!310 &1
4 | UnityConnectSettings:
5 | m_ObjectHideFlags: 0
6 | m_Enabled: 0
7 | m_TestMode: 0
8 | m_TestEventUrl:
9 | m_TestConfigUrl:
10 | CrashReportingSettings:
11 | m_EventUrl: https://perf-events.cloud.unity3d.com/api/events/crashes
12 | m_Enabled: 0
13 | UnityPurchasingSettings:
14 | m_Enabled: 0
15 | m_TestMode: 0
16 | UnityAnalyticsSettings:
17 | m_Enabled: 0
18 | m_InitializeOnStartup: 1
19 | m_TestMode: 0
20 | m_TestEventUrl:
21 | m_TestConfigUrl:
22 |
--------------------------------------------------------------------------------
/Assets/Plugins/protobuf/Google.Protobuf.dll.meta:
--------------------------------------------------------------------------------
1 | fileFormatVersion: 2
2 | guid: aec7b1d31ee2b924f8812039e6a54e6a
3 | timeCreated: 1495440524
4 | licenseType: Pro
5 | PluginImporter:
6 | serializedVersion: 1
7 | iconMap: {}
8 | executionOrder: {}
9 | isPreloaded: 0
10 | platformData:
11 | Any:
12 | enabled: 1
13 | settings: {}
14 | Editor:
15 | enabled: 0
16 | settings:
17 | DefaultValueInitialized: true
18 | WindowsStoreApps:
19 | enabled: 0
20 | settings:
21 | CPU: AnyCPU
22 | userData:
23 | assetBundleName:
24 | assetBundleVariant:
25 |
--------------------------------------------------------------------------------
/ProjectSettings/DynamicsManager.asset:
--------------------------------------------------------------------------------
1 | %YAML 1.1
2 | %TAG !u! tag:unity3d.com,2011:
3 | --- !u!55 &1
4 | PhysicsManager:
5 | m_ObjectHideFlags: 0
6 | serializedVersion: 2
7 | m_Gravity: {x: 0, y: -9.81, z: 0}
8 | m_DefaultMaterial: {fileID: 0}
9 | m_BounceThreshold: 2
10 | m_SleepThreshold: 0.005
11 | m_DefaultContactOffset: 0.01
12 | m_SolverIterationCount: 6
13 | m_SolverVelocityIterations: 1
14 | m_QueriesHitTriggers: 1
15 | m_EnableAdaptiveForce: 0
16 | m_LayerCollisionMatrix: ffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff
17 |
--------------------------------------------------------------------------------
/ProjectSettings/NavMeshAreas.asset:
--------------------------------------------------------------------------------
1 | %YAML 1.1
2 | %TAG !u! tag:unity3d.com,2011:
3 | --- !u!126 &1
4 | NavMeshAreas:
5 | m_ObjectHideFlags: 0
6 | serializedVersion: 2
7 | areas:
8 | - name: Walkable
9 | cost: 1
10 | - name: Not Walkable
11 | cost: 1
12 | - name: Jump
13 | cost: 2
14 | - name:
15 | cost: 1
16 | - name:
17 | cost: 1
18 | - name:
19 | cost: 1
20 | - name:
21 | cost: 1
22 | - name:
23 | cost: 1
24 | - name:
25 | cost: 1
26 | - name:
27 | cost: 1
28 | - name:
29 | cost: 1
30 | - name:
31 | cost: 1
32 | - name:
33 | cost: 1
34 | - name:
35 | cost: 1
36 | - name:
37 | cost: 1
38 | - name:
39 | cost: 1
40 | - name:
41 | cost: 1
42 | - name:
43 | cost: 1
44 | - name:
45 | cost: 1
46 | - name:
47 | cost: 1
48 | - name:
49 | cost: 1
50 | - name:
51 | cost: 1
52 | - name:
53 | cost: 1
54 | - name:
55 | cost: 1
56 | - name:
57 | cost: 1
58 | - name:
59 | cost: 1
60 | - name:
61 | cost: 1
62 | - name:
63 | cost: 1
64 | - name:
65 | cost: 1
66 | - name:
67 | cost: 1
68 | - name:
69 | cost: 1
70 | - name:
71 | cost: 1
72 |
--------------------------------------------------------------------------------
/Assets/Plugins/kcpForUnity/common/ByteBufSync.cs:
--------------------------------------------------------------------------------
1 | ///
2 | ///同步版ByteBuf 用于 两个线程的通讯,一个线程写入的同时 另一个线程读取,仅用于两个线程,请不要用于大于一个线程读 或者大于线程写
3 | ///
4 | namespace System.Collections
5 | {
6 | using System;
7 | using System.Collections.Generic;
8 | using System.Linq;
9 | using System.Text;
10 | public class ByteBufSync
11 | {
12 | private const int defaultSize = 4;
13 | private ByteBuf m_readQue = new ByteBuf(defaultSize);
14 | private ByteBuf m_writeQue = new ByteBuf(defaultSize);
15 | private object locker = new object();
16 | public ByteBufSync()
17 | {
18 |
19 | }
20 | public void WriteFrom(ByteBuf buf)
21 | {
22 | lock (locker)
23 | {
24 | m_writeQue.WriteBytesFrom(buf);
25 | }
26 | }
27 | public void Swap()
28 | {
29 | lock (locker)
30 | {
31 | kcpUtil.Swap(ref m_readQue, ref m_writeQue);
32 | }
33 | }
34 | public ByteBuf writeQue
35 | {
36 | get { return m_writeQue; }
37 | }
38 | public ByteBuf readQue
39 | {
40 | get { return m_readQue; }
41 | }
42 | }
43 | }
44 |
--------------------------------------------------------------------------------
/ProjectSettings/Physics2DSettings.asset:
--------------------------------------------------------------------------------
1 | %YAML 1.1
2 | %TAG !u! tag:unity3d.com,2011:
3 | --- !u!19 &1
4 | Physics2DSettings:
5 | m_ObjectHideFlags: 0
6 | serializedVersion: 2
7 | m_Gravity: {x: 0, y: -9.81}
8 | m_DefaultMaterial: {fileID: 0}
9 | m_VelocityIterations: 8
10 | m_PositionIterations: 3
11 | m_VelocityThreshold: 1
12 | m_MaxLinearCorrection: 0.2
13 | m_MaxAngularCorrection: 8
14 | m_MaxTranslationSpeed: 100
15 | m_MaxRotationSpeed: 360
16 | m_MinPenetrationForPenalty: 0.01
17 | m_BaumgarteScale: 0.2
18 | m_BaumgarteTimeOfImpactScale: 0.75
19 | m_TimeToSleep: 0.5
20 | m_LinearSleepTolerance: 0.01
21 | m_AngularSleepTolerance: 2
22 | m_QueriesHitTriggers: 1
23 | m_QueriesStartInColliders: 1
24 | m_ChangeStopsCallbacks: 0
25 | m_AlwaysShowColliders: 0
26 | m_ShowColliderSleep: 1
27 | m_ShowColliderContacts: 0
28 | m_ContactArrowScale: 0.2
29 | m_ColliderAwakeColor: {r: 0.5686275, g: 0.95686275, b: 0.54509807, a: 0.7529412}
30 | m_ColliderAsleepColor: {r: 0.5686275, g: 0.95686275, b: 0.54509807, a: 0.36078432}
31 | m_ColliderContactColor: {r: 1, g: 0, b: 1, a: 0.6862745}
32 | m_LayerCollisionMatrix: ffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff
33 |
--------------------------------------------------------------------------------
/kcpforunity.sln:
--------------------------------------------------------------------------------
1 |
2 | Microsoft Visual Studio Solution File, Format Version 12.00
3 | # Visual Studio 2015
4 | Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "kcpforunity.Plugins", "kcpforunity.Plugins.csproj", "{0EB4FC5E-89E0-A1AB-14A6-58A6E5C41B23}"
5 | EndProject
6 | Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "kcpforunity", "kcpforunity.csproj", "{6EEBB32C-F259-4A35-7134-E198984C8870}"
7 | EndProject
8 | Global
9 | GlobalSection(SolutionConfigurationPlatforms) = preSolution
10 | Debug|Any CPU = Debug|Any CPU
11 | Release|Any CPU = Release|Any CPU
12 | EndGlobalSection
13 | GlobalSection(ProjectConfigurationPlatforms) = postSolution
14 | {0EB4FC5E-89E0-A1AB-14A6-58A6E5C41B23}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
15 | {0EB4FC5E-89E0-A1AB-14A6-58A6E5C41B23}.Debug|Any CPU.Build.0 = Debug|Any CPU
16 | {0EB4FC5E-89E0-A1AB-14A6-58A6E5C41B23}.Release|Any CPU.ActiveCfg = Release|Any CPU
17 | {0EB4FC5E-89E0-A1AB-14A6-58A6E5C41B23}.Release|Any CPU.Build.0 = Release|Any CPU
18 | {6EEBB32C-F259-4A35-7134-E198984C8870}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
19 | {6EEBB32C-F259-4A35-7134-E198984C8870}.Debug|Any CPU.Build.0 = Debug|Any CPU
20 | {6EEBB32C-F259-4A35-7134-E198984C8870}.Release|Any CPU.ActiveCfg = Release|Any CPU
21 | {6EEBB32C-F259-4A35-7134-E198984C8870}.Release|Any CPU.Build.0 = Release|Any CPU
22 | EndGlobalSection
23 | GlobalSection(SolutionProperties) = preSolution
24 | HideSolutionNode = FALSE
25 | EndGlobalSection
26 | EndGlobal
27 |
--------------------------------------------------------------------------------
/Assets/Plugins/kcpForUnity/common/testUtil.cs:
--------------------------------------------------------------------------------
1 | using System;
2 | using UnityEngine;
3 | using System.Collections.Generic;
4 |
5 | public static class testUtil{
6 |
7 | private static System.Random random = new System.Random();
8 | private static int count = 0;
9 |
10 | public static bool RandInclude(int min, int max, int rate)
11 | {
12 | var value = random.Next(min, max);
13 | return value < rate;
14 | }
15 | public static bool RandIncludePercent(int rate)
16 | {
17 | return RandInclude(0, 100, rate);
18 | }
19 | public static bool CountIncludePercent(int rate)
20 | {
21 | if (count < rate)
22 | {
23 | count = 0;
24 | return true;
25 | }
26 | count++;
27 | return false;
28 | }
29 | public static void PackInSendTime(this byte[] self)
30 | {
31 | self.PackInInt((int)kcpUtil.nowTotalMilliseconds, 0);
32 | }
33 | public static void PackInInt(this byte[] self, int value, int index)
34 | {
35 | var bytes = BitConverter.GetBytes(value);
36 | Array.Copy(bytes, 0, self, index, bytes.Length);
37 | }
38 | public static int Unpack2Int(this byte[] self, int indx)
39 | {
40 | return BitConverter.ToInt32(self, indx);
41 | }
42 | public static int GetRTT(this byte[] self)
43 | {
44 | var sndTime = self.Unpack2Int(0);
45 | return (int)kcpUtil.nowTotalMilliseconds - sndTime;
46 | }
47 | }
48 |
--------------------------------------------------------------------------------
/Assets/Plugins/kcpForUnity/common/ObjectPoolSync2.cs:
--------------------------------------------------------------------------------
1 | using System;
2 | using System.Collections.Generic;
3 | using System.Linq;
4 | using System.Text;
5 |
6 | namespace CxExtension
7 | {
8 | ///
9 | /// 用于两个线程间的通信,一个只线程get 一个线程里面只return,切记 只用于两个线程的对象池,单线程请使用单线程版
10 | ///
11 | ///
12 | public class ObjectPoolSync2 : ObjectPool where T : class, new()
13 | {
14 | private object locker = new object();
15 | public ObjectPoolSync2(Func creatNew, Action resetFunc) : base(creatNew, resetFunc)
16 | {
17 | returnQue = new Queue();
18 | }
19 | public override T Get()
20 | {
21 | T t = null;
22 | if (getQue.Count > 0)
23 | {
24 | t = getQue.Dequeue();
25 | }
26 | else
27 | {
28 | Swap();
29 | if (getQue.Count > 0)
30 | {
31 | t = getQue.Dequeue();
32 | }
33 | else
34 | {
35 | t = m_createNew();
36 | }
37 | }
38 | return t;
39 | }
40 | public void Swap()
41 | {
42 | kcpUtil.Swap(ref getQue, ref returnQue);
43 | }
44 | public override void Return(T item)
45 | {
46 | lock (locker)
47 | {
48 | base.Return(item);
49 | }
50 | }
51 | }
52 | }
53 |
--------------------------------------------------------------------------------
/Assets/Plugins/kcpForUnity/TcpSocket.cs:
--------------------------------------------------------------------------------
1 | using UnityEngine;
2 | using System.Collections;
3 | using System.Net.Sockets;
4 | using System;
5 |
6 | public class TcpSocket
7 | {
8 | TcpClient client;
9 | private BytePacker packer;
10 | private NetworkStream tcpStream;
11 | private byte[] readCache = new byte[1000];
12 | public int rtt;
13 | public TcpSocket()
14 | {
15 | packer = new BytePacker(OnPacked);
16 | }
17 | public void OnPacked(byte[] buff)
18 | {
19 | rtt = buff.GetRTT();
20 | }
21 | public void Connect(string host, int port)
22 | {
23 | client = new TcpClient();
24 | client.Connect(host, port);
25 | tcpStream = client.GetStream();
26 | BeginRead();
27 | }
28 | public void BeginRead()
29 | {
30 | tcpStream.BeginRead(readCache, 0, readCache.Length, RecvCall, tcpStream);
31 | }
32 | public void Send(byte[] buff)
33 | {
34 | buff.PackInSendTime();
35 | buff.PackInInt(rtt, 4);
36 | //buff.PackInInt()
37 | buff = packer.Pack(buff);
38 | tcpStream.Write(buff, 0, buff.Length);
39 | }
40 | public void RecvCall(IAsyncResult ar)
41 | {
42 | int rcvSize = tcpStream.EndRead(ar);
43 | var rcvBuff = new byte[rcvSize];
44 | Array.Copy(readCache, 0, rcvBuff, 0, rcvSize);
45 | packer.Recv(rcvBuff);
46 | if (tcpStream.CanRead)
47 | {
48 | }
49 |
50 | BeginRead();
51 | }
52 | public void Close()
53 | {
54 | client.Close();
55 | }
56 | }
57 |
--------------------------------------------------------------------------------
/Assets/Plugins/kcpForUnity/common/ObjectPool.cs:
--------------------------------------------------------------------------------
1 |
2 |
3 | namespace CxExtension
4 | {
5 | using System;
6 | using System.Collections.Generic;
7 | using System.Linq;
8 | using System.Text;
9 | ///
10 | /// a sample pool and your self ensure multile tiems return.used to single thread
11 | ///
12 | ///
13 | public class ObjectPool where T : class, new()
14 | {
15 | protected Queue getQue = new Queue();
16 | protected Queue returnQue;
17 | protected Func m_createNew;
18 | protected Action m_resetFunc;
19 | public ObjectPool(Func createNew, Action resetFunc)
20 | {
21 | m_createNew = createNew;
22 | m_resetFunc = resetFunc;
23 | returnQue = getQue;
24 | }
25 | public ObjectPool()
26 | {
27 | returnQue = getQue;
28 | }
29 | public virtual T Get()
30 | {
31 | var it = getQue.Dequeue();
32 | if (it == null)
33 | {
34 | if (m_createNew == null)
35 | {
36 | it = new T();
37 | }
38 | else
39 | {
40 | it = m_createNew();
41 | }
42 | }
43 | return it;
44 | }
45 | public virtual void Return(T item)
46 | {
47 | if (m_resetFunc != null)
48 | {
49 | m_resetFunc(item);
50 | }
51 | getQue.Enqueue(item);
52 | }
53 | }
54 | }
55 |
--------------------------------------------------------------------------------
/Assets/Plugins/kcpForUnity/common/kcpUtil.cs:
--------------------------------------------------------------------------------
1 | using System;
2 | using System.Collections.Generic;
3 | using System.Linq;
4 | using System.Linq.Expressions;
5 | using System.Text;
6 |
7 | public static class kcpUtil
8 | {
9 | private static DateTime offTime = new DateTime(2017, 1, 1);
10 | static kcpUtil()
11 | {
12 | offTime = DateTime.Now;
13 | }
14 | ///
15 | /// DateTime.Now.Subtract(offTime).TotalMilliseconds
16 | ///
17 | public static ulong nowTotalMilliseconds
18 | {
19 | get
20 | {
21 | #if true
22 | return (ulong)(DateTime.Now.Subtract(offTime).TotalMilliseconds);
23 | #else
24 | return (ulong)(DateTime.Now.Ticks / 10000);
25 | #endif
26 | }
27 | }
28 | public static T[] copyAll(this T[] self)
29 | {
30 | var it = new T[self.Length];
31 | Array.Copy(self, it, self.Length);
32 | return it;
33 | }
34 | public static UInt32 ReadUint32(this byte[] self, int startIndx)
35 | {
36 | return BitConverter.ToUInt32(self, startIndx);
37 | }
38 | public static byte[] Recapacity(this byte[] self, int length, bool copyData = false)
39 | {
40 | byte[] newBytes = self;
41 | if (self.Length < length)
42 | {
43 | newBytes = new byte[length];
44 | if (copyData)
45 | {
46 | self.CopyTo(0, newBytes, 0, self.Length);
47 | }
48 | }
49 | return newBytes;
50 | }
51 |
52 |
53 | public static void CopyTo(this T[] self, int sourceIndex, T[] dest, int destIndex, int count)
54 | {
55 | Array.Copy(self, sourceIndex, dest, destIndex, count);
56 | }
57 | public static void Swap(ref T left, ref T right)
58 | {
59 | T temp = left;
60 | left = right;
61 | right = temp;
62 | }
63 | }
64 |
--------------------------------------------------------------------------------
/Assets/Plugins/kcpForUnity/common/BytePacker.cs:
--------------------------------------------------------------------------------
1 | using System;
2 | using System.Collections;
3 | using System.Collections.Generic;
4 | public class BytePacker
5 | {
6 | private List cache = new List(1024);
7 | private int pkgLengthByteSize = 4;//
8 | private byte[] pkgLengthBytes;
9 | private int curPkgSize = -1;
10 | private Action func;
11 | public byte[] Pack(byte[] content)
12 | {
13 | pkgLengthBytes = BitConverter.GetBytes(content.Length);
14 | pkgLengthByteSize = pkgLengthBytes.Length;
15 | var buf = new byte[content.Length + pkgLengthByteSize];
16 | int offset = 0;
17 | Array.Copy(pkgLengthBytes, buf, pkgLengthBytes.Length);
18 | offset += pkgLengthBytes.Length;
19 | Array.Copy(content, 0, buf, offset, content.Length);
20 | return buf;
21 | }
22 | public BytePacker(Action call)
23 | {
24 | func = call;
25 | }
26 | public void Recv(byte[] buff)
27 | {
28 | cache.AddRange(buff);
29 | while (true)
30 | {
31 | if (curPkgSize < 0)// if not pkg size
32 | {
33 | if (cache.Count > pkgLengthByteSize)
34 | {
35 | //get pkg size
36 | cache.CopyTo(0, pkgLengthBytes, 0, pkgLengthByteSize);
37 | cache.RemoveRange(0, pkgLengthByteSize);
38 | curPkgSize = BitConverter.ToInt32(pkgLengthBytes, 0);
39 | }
40 | else
41 | {
42 | break;
43 | }
44 | }
45 |
46 | if (cache.Count >= curPkgSize)
47 | {//get pkg data
48 | var pkgData = new byte[curPkgSize];
49 | cache.CopyTo(0, pkgData, 0, pkgData.Length);
50 | cache.RemoveRange(0, curPkgSize);
51 | func.Invoke(pkgData);
52 | //reset pkg size
53 | curPkgSize = -1;
54 | }
55 | else
56 | {
57 | break;
58 | }
59 | }
60 | }
61 | }
--------------------------------------------------------------------------------
/Assets/Plugins/kcpForUnity/common/QueueSync.cs:
--------------------------------------------------------------------------------
1 | using System;
2 | using System.Collections.Generic;
3 | ///
4 | /// this Queue use to multiple thread Enqueue and one thread dequeue;
5 | /// not use to multiple thread dequeue
6 | ///
7 | ///
8 |
9 | public class QueueSync
10 | {
11 | private Queue inQue;
12 | private Queue outQue;
13 | //private int queueNum = 2;
14 | private object locker = new object();
15 | public QueueSync()
16 | {
17 | inQue = new Queue();
18 | outQue = new Queue();
19 | }
20 | public QueueSync(int size)
21 | {
22 | inQue = new Queue(size);
23 | outQue = new Queue(size);
24 | }
25 | public int Count
26 | {
27 | get
28 | {
29 | int count;
30 | lock (locker)
31 | {
32 | count = inQue.Count + outQue.Count;
33 | }
34 | return count;
35 | }
36 | }
37 |
38 | private T DequeueUnsafe()
39 | {
40 | return outQue.Dequeue();
41 | }
42 | public T Dequeue()
43 | {
44 | T t;
45 | if (outQue.Count == 0)
46 | {
47 | Switch();
48 | }
49 | t = DequeueUnsafe();
50 | return t;
51 | }
52 | ///
53 | /// Switch The InQue outQue used to foreach
54 | ///
55 | private void Switch()
56 | {
57 | lock (locker)
58 | {
59 | kcpUtil.Swap(ref inQue, ref outQue);
60 | }
61 | }
62 | public void Enqueue(T item)
63 | {
64 | lock (locker)
65 | {
66 | inQue.Enqueue(item);
67 | }
68 | }
69 | ///
70 | /// dequeue All in outQue items only used one thread
71 | ///
72 | ///
73 | public void DequeueAll(Action func)
74 | {
75 | if (func == null)
76 | {
77 | return;
78 | }
79 | Switch();
80 | while (outQue.Count > 0)
81 | {
82 | T it = outQue.Dequeue();
83 | func(it);
84 | }
85 | }
86 | ///
87 | /// peek on item
88 | ///
89 | ///
90 | public T Peek()
91 | {
92 | T item;
93 | if (outQue.Count == 0)
94 | {
95 | Switch();
96 | }
97 | //lock (locker)
98 | {
99 | item = outQue.Peek();
100 | }
101 | return item;
102 | }
103 | }
--------------------------------------------------------------------------------
/ProjectSettings/GraphicsSettings.asset:
--------------------------------------------------------------------------------
1 | %YAML 1.1
2 | %TAG !u! tag:unity3d.com,2011:
3 | --- !u!30 &1
4 | GraphicsSettings:
5 | m_ObjectHideFlags: 0
6 | serializedVersion: 7
7 | m_Deferred:
8 | m_Mode: 1
9 | m_Shader: {fileID: 69, guid: 0000000000000000f000000000000000, type: 0}
10 | m_DeferredReflections:
11 | m_Mode: 1
12 | m_Shader: {fileID: 74, guid: 0000000000000000f000000000000000, type: 0}
13 | m_ScreenSpaceShadows:
14 | m_Mode: 1
15 | m_Shader: {fileID: 64, guid: 0000000000000000f000000000000000, type: 0}
16 | m_LegacyDeferred:
17 | m_Mode: 1
18 | m_Shader: {fileID: 63, guid: 0000000000000000f000000000000000, type: 0}
19 | m_DepthNormals:
20 | m_Mode: 1
21 | m_Shader: {fileID: 62, guid: 0000000000000000f000000000000000, type: 0}
22 | m_MotionVectors:
23 | m_Mode: 1
24 | m_Shader: {fileID: 75, guid: 0000000000000000f000000000000000, type: 0}
25 | m_LightHalo:
26 | m_Mode: 1
27 | m_Shader: {fileID: 105, guid: 0000000000000000f000000000000000, type: 0}
28 | m_LensFlare:
29 | m_Mode: 1
30 | m_Shader: {fileID: 102, guid: 0000000000000000f000000000000000, type: 0}
31 | m_AlwaysIncludedShaders:
32 | - {fileID: 7, guid: 0000000000000000f000000000000000, type: 0}
33 | - {fileID: 15104, guid: 0000000000000000f000000000000000, type: 0}
34 | - {fileID: 15105, guid: 0000000000000000f000000000000000, type: 0}
35 | - {fileID: 15106, guid: 0000000000000000f000000000000000, type: 0}
36 | - {fileID: 10753, guid: 0000000000000000f000000000000000, type: 0}
37 | - {fileID: 10770, guid: 0000000000000000f000000000000000, type: 0}
38 | - {fileID: 10782, guid: 0000000000000000f000000000000000, type: 0}
39 | m_PreloadedShaders: []
40 | m_SpritesDefaultMaterial: {fileID: 10754, guid: 0000000000000000f000000000000000,
41 | type: 0}
42 | m_ShaderSettings_Tier1:
43 | useCascadedShadowMaps: 0
44 | standardShaderQuality: 0
45 | useReflectionProbeBoxProjection: 0
46 | useReflectionProbeBlending: 0
47 | m_ShaderSettings_Tier2:
48 | useCascadedShadowMaps: 0
49 | standardShaderQuality: 1
50 | useReflectionProbeBoxProjection: 0
51 | useReflectionProbeBlending: 0
52 | m_ShaderSettings_Tier3:
53 | useCascadedShadowMaps: 0
54 | standardShaderQuality: 1
55 | useReflectionProbeBoxProjection: 0
56 | useReflectionProbeBlending: 0
57 | m_BuildTargetShaderSettings: []
58 | m_LightmapStripping: 0
59 | m_FogStripping: 0
60 | m_LightmapKeepPlain: 1
61 | m_LightmapKeepDirCombined: 1
62 | m_LightmapKeepDirSeparate: 1
63 | m_LightmapKeepDynamicPlain: 1
64 | m_LightmapKeepDynamicDirCombined: 1
65 | m_LightmapKeepDynamicDirSeparate: 1
66 | m_FogKeepLinear: 1
67 | m_FogKeepExp: 1
68 | m_FogKeepExp2: 1
69 |
--------------------------------------------------------------------------------
/ProjectSettings/QualitySettings.asset:
--------------------------------------------------------------------------------
1 | %YAML 1.1
2 | %TAG !u! tag:unity3d.com,2011:
3 | --- !u!47 &1
4 | QualitySettings:
5 | m_ObjectHideFlags: 0
6 | serializedVersion: 5
7 | m_CurrentQuality: 5
8 | m_QualitySettings:
9 | - serializedVersion: 2
10 | name: Fastest
11 | pixelLightCount: 0
12 | shadows: 0
13 | shadowResolution: 0
14 | shadowProjection: 1
15 | shadowCascades: 1
16 | shadowDistance: 15
17 | shadowNearPlaneOffset: 2
18 | shadowCascade2Split: 0.33333334
19 | shadowCascade4Split: {x: 0.06666667, y: 0.2, z: 0.46666667}
20 | blendWeights: 1
21 | textureQuality: 1
22 | anisotropicTextures: 0
23 | antiAliasing: 0
24 | softParticles: 0
25 | softVegetation: 0
26 | realtimeReflectionProbes: 0
27 | billboardsFaceCameraPosition: 0
28 | vSyncCount: 0
29 | lodBias: 0.3
30 | maximumLODLevel: 0
31 | particleRaycastBudget: 4
32 | asyncUploadTimeSlice: 2
33 | asyncUploadBufferSize: 4
34 | excludedTargetPlatforms: []
35 | - serializedVersion: 2
36 | name: Fast
37 | pixelLightCount: 0
38 | shadows: 0
39 | shadowResolution: 0
40 | shadowProjection: 1
41 | shadowCascades: 1
42 | shadowDistance: 20
43 | shadowNearPlaneOffset: 2
44 | shadowCascade2Split: 0.33333334
45 | shadowCascade4Split: {x: 0.06666667, y: 0.2, z: 0.46666667}
46 | blendWeights: 2
47 | textureQuality: 0
48 | anisotropicTextures: 0
49 | antiAliasing: 0
50 | softParticles: 0
51 | softVegetation: 0
52 | realtimeReflectionProbes: 0
53 | billboardsFaceCameraPosition: 0
54 | vSyncCount: 0
55 | lodBias: 0.4
56 | maximumLODLevel: 0
57 | particleRaycastBudget: 16
58 | asyncUploadTimeSlice: 2
59 | asyncUploadBufferSize: 4
60 | excludedTargetPlatforms: []
61 | - serializedVersion: 2
62 | name: Simple
63 | pixelLightCount: 1
64 | shadows: 1
65 | shadowResolution: 0
66 | shadowProjection: 1
67 | shadowCascades: 1
68 | shadowDistance: 20
69 | shadowNearPlaneOffset: 2
70 | shadowCascade2Split: 0.33333334
71 | shadowCascade4Split: {x: 0.06666667, y: 0.2, z: 0.46666667}
72 | blendWeights: 2
73 | textureQuality: 0
74 | anisotropicTextures: 1
75 | antiAliasing: 0
76 | softParticles: 0
77 | softVegetation: 0
78 | realtimeReflectionProbes: 0
79 | billboardsFaceCameraPosition: 0
80 | vSyncCount: 1
81 | lodBias: 0.7
82 | maximumLODLevel: 0
83 | particleRaycastBudget: 64
84 | asyncUploadTimeSlice: 2
85 | asyncUploadBufferSize: 4
86 | excludedTargetPlatforms: []
87 | - serializedVersion: 2
88 | name: Good
89 | pixelLightCount: 2
90 | shadows: 2
91 | shadowResolution: 1
92 | shadowProjection: 1
93 | shadowCascades: 2
94 | shadowDistance: 40
95 | shadowNearPlaneOffset: 2
96 | shadowCascade2Split: 0.33333334
97 | shadowCascade4Split: {x: 0.06666667, y: 0.2, z: 0.46666667}
98 | blendWeights: 2
99 | textureQuality: 0
100 | anisotropicTextures: 1
101 | antiAliasing: 0
102 | softParticles: 0
103 | softVegetation: 1
104 | realtimeReflectionProbes: 1
105 | billboardsFaceCameraPosition: 1
106 | vSyncCount: 1
107 | lodBias: 1
108 | maximumLODLevel: 0
109 | particleRaycastBudget: 256
110 | asyncUploadTimeSlice: 2
111 | asyncUploadBufferSize: 4
112 | excludedTargetPlatforms: []
113 | - serializedVersion: 2
114 | name: Beautiful
115 | pixelLightCount: 3
116 | shadows: 2
117 | shadowResolution: 2
118 | shadowProjection: 1
119 | shadowCascades: 2
120 | shadowDistance: 70
121 | shadowNearPlaneOffset: 2
122 | shadowCascade2Split: 0.33333334
123 | shadowCascade4Split: {x: 0.06666667, y: 0.2, z: 0.46666667}
124 | blendWeights: 4
125 | textureQuality: 0
126 | anisotropicTextures: 2
127 | antiAliasing: 2
128 | softParticles: 1
129 | softVegetation: 1
130 | realtimeReflectionProbes: 1
131 | billboardsFaceCameraPosition: 1
132 | vSyncCount: 1
133 | lodBias: 1.5
134 | maximumLODLevel: 0
135 | particleRaycastBudget: 1024
136 | asyncUploadTimeSlice: 2
137 | asyncUploadBufferSize: 4
138 | excludedTargetPlatforms: []
139 | - serializedVersion: 2
140 | name: Fantastic
141 | pixelLightCount: 4
142 | shadows: 2
143 | shadowResolution: 2
144 | shadowProjection: 1
145 | shadowCascades: 4
146 | shadowDistance: 150
147 | shadowNearPlaneOffset: 2
148 | shadowCascade2Split: 0.33333334
149 | shadowCascade4Split: {x: 0.06666667, y: 0.2, z: 0.46666667}
150 | blendWeights: 4
151 | textureQuality: 0
152 | anisotropicTextures: 2
153 | antiAliasing: 2
154 | softParticles: 1
155 | softVegetation: 1
156 | realtimeReflectionProbes: 1
157 | billboardsFaceCameraPosition: 1
158 | vSyncCount: 1
159 | lodBias: 2
160 | maximumLODLevel: 0
161 | particleRaycastBudget: 4096
162 | asyncUploadTimeSlice: 2
163 | asyncUploadBufferSize: 4
164 | excludedTargetPlatforms: []
165 | m_PerPlatformDefaultQuality:
166 | Android: 2
167 | Nintendo 3DS: 5
168 | PS3: 5
169 | PS4: 5
170 | PSM: 5
171 | PSP2: 2
172 | Samsung TV: 2
173 | Standalone: 5
174 | Tizen: 2
175 | Web: 5
176 | WebGL: 3
177 | WiiU: 5
178 | Windows Store Apps: 5
179 | XBOX360: 5
180 | XboxOne: 5
181 | iPhone: 2
182 | tvOS: 5
183 |
--------------------------------------------------------------------------------
/Assets/Scripts/Test/TestKcp.cs:
--------------------------------------------------------------------------------
1 | using UnityEngine;
2 | //using System.;
3 | using System.Collections;
4 | using KcpProject.v2;
5 | using System;
6 | using System.Net.Sockets;
7 | using UnityEngine.UI;
8 |
9 | public class TestKcp : MonoBehaviour
10 | {
11 | [Serializable]
12 | public struct HostAdress
13 | {
14 | public string name;
15 | public string host;
16 | public int portKcp;
17 | public int portTcp;
18 | }
19 | public HostAdress[] hostss;
20 | public int hostIndx = 0;
21 | public UdpSocket kcpClient;
22 | public TcpSocket tcpClient;
23 | public bool autoSend = true;
24 | public uint pkgCountTotal = 0;
25 | public float interval = 0.1f;
26 | public float used = 0;
27 | public int msgSize = 10000;
28 | public int mLosePackRate = 10;
29 | public int rttKcpMax = 0;
30 | public int rttTcpMax = 0;
31 | public int rttKcp = 10;
32 | public uint pckCntFrm = 100;
33 | public double pckCntFrmTime = 0;
34 | public int pckCalcSize = 100;
35 | public int pckCalcCur = 0;
36 | public bool runOnStart = true;
37 | public bool tcpRuning = false;
38 | public bool kcpRuning = false;
39 |
40 | public bool rcvSync = false;
41 | public UnityEngine.UI.Text kcpRttText;
42 | public UnityEngine.UI.Text tcpRttText;
43 | public UnityEngine.UI.Text msgSizeText;
44 | public UnityEngine.UI.Text freNumText;
45 | public UnityEngine.UI.Text losePackRateText;
46 | public HostAdress curHost { get { return hostss[hostIndx]; } }
47 | public void OnSenSizeChange(float value)
48 | {
49 | msgSize = (int)value;
50 | msgSizeText.text = string.Format("msgSize:{0}", msgSize);
51 | //Debug.LogFormat("set SendBuff:{0}", value);
52 | }
53 | public void OnFreQuencyChange(float value)
54 | {
55 | interval = 1.0f / value;
56 | freNumText.text = string.Format("fps:{0}", value);
57 | }
58 | public void OnLosePackRateChange(float value)
59 | {
60 | mLosePackRate = (int)value;
61 | UdpSocket.lostPackRate = mLosePackRate;
62 | losePackRateText.text = string.Format("LosePackRate:{0}", (int)value);
63 | }
64 | // Use this for initialization
65 | void Start()
66 | {
67 | Debug.LogFormat("now time:{0}", kcpUtil.nowTotalMilliseconds);
68 | //enabled = false;
69 | if (runOnStart)
70 | {
71 | TestStart();
72 | }
73 | }
74 | #region KcpTest
75 | public void KcpStart()
76 | {
77 | //enabled = true;
78 | kcpClient = new UdpSocket((buff,length) =>
79 | {
80 | var rcvtime = kcpUtil.nowTotalMilliseconds;
81 | var sndtime = BitConverter.ToUInt32(buff, 0);
82 | var usetime = rcvtime - sndtime;
83 | pckCntFrmTime += usetime;
84 | pckCalcCur++;
85 | });
86 | kcpClient.Connect(curHost.host, curHost.portKcp);
87 | }
88 | public void KcpSend(byte[] buff)
89 | {
90 | if (kcpClient != null)
91 | {
92 | if (kcpClient.Connected)
93 | {
94 | kcpClient.Send(buff);
95 | }
96 | }
97 | }
98 | public void KcpStop()
99 | {
100 | //enabled = false;
101 | kcpClient.Close();
102 | }
103 | public void KcpRestart()
104 | {
105 | KcpStop();
106 | KcpStart();
107 | }
108 | #endregion
109 | #region TcpTest
110 | public void TcpStart()
111 | {
112 | //enabled = true;
113 | tcpClient = new TcpSocket();
114 | tcpClient.Connect(curHost.host, curHost.portTcp);
115 | tcpRuning = true;
116 | }
117 | public void TcpSend(byte[] buff)
118 | {
119 | if (tcpRuning)
120 | {
121 | tcpClient.Send(buff);
122 | }
123 | }
124 | public void TcpStop()
125 | {
126 | //enabled = false;
127 | tcpClient.Close();
128 | tcpRuning = false;
129 | }
130 | #endregion
131 | public void TestSend()
132 | {
133 | var buff = new byte[msgSize];
134 | buff.PackInSendTime();//send time
135 | //buff.PackInInt(rttKcp, 4);//pre rtt
136 | buff.PackInInt(mLosePackRate, 8);
137 |
138 | KcpSend(buff);
139 | TcpSend(buff);
140 | }
141 | public void TestStart()
142 | {
143 | TcpStart();
144 | KcpStart();
145 | }
146 | public void TestStop()
147 | {
148 | TcpStop();
149 | KcpStop();
150 | }
151 | public void SendTestBuff()
152 | {
153 | var buff = new byte[msgSize];
154 | buff.PackInSendTime();
155 | buff.PackInInt(rttKcp, 4);
156 | buff.PackInInt(mLosePackRate, 8);
157 | if (kcpClient != null)
158 | {
159 | if (kcpClient.Connected)
160 | {
161 | kcpClient.Send(buff);
162 | }
163 | }
164 | if (tcpRuning)
165 | {
166 | TcpSend(buff);
167 | }
168 | //Debug.LogFormat("send sessage:{0}", content);
169 | }
170 | // Update is called once per frame
171 | void Update()
172 | {
173 | if (autoSend)
174 | {
175 | used += Time.deltaTime;
176 | if (used > interval)
177 | {
178 | used -= interval;
179 | TestSend();
180 | }
181 | }
182 | if (tcpClient != null)
183 | {
184 | rttTcpMax = Math.Max(tcpClient.rtt, rttTcpMax);
185 | tcpRttText.text = string.Format("tcp rtt:{0} max:{1}", tcpClient.rtt, rttTcpMax);
186 | }
187 | if (pckCalcCur >= pckCalcSize)
188 | {
189 | var meanTime = pckCntFrmTime / pckCalcCur;
190 | rttKcp = (int)meanTime;
191 | rttKcpMax = Math.Max((int)meanTime, rttKcpMax);
192 |
193 | kcpRttText.text = string.Format("kcp rtt:{0} max:{1}", (int)meanTime, rttKcpMax);
194 | pckCalcCur = 0;
195 | pckCntFrmTime = 0;
196 | }
197 | }
198 | }
199 |
--------------------------------------------------------------------------------
/Assets/Plugins/kcpForUnity/common/ByteBuf.cs:
--------------------------------------------------------------------------------
1 | /**
2 | * 缓冲区
3 | **/
4 | using System;
5 | using System.Text;
6 |
7 | public class ByteBuf
8 | {
9 | private byte[] data;
10 | private int mReadPos;
11 | private int mWritePos;
12 | private static byte[] emptyArray = new byte[0];
13 | #region Constroct
14 | public ByteBuf()
15 | {
16 | Init();
17 | data = emptyArray;
18 | }
19 | public ByteBuf(int capacity) : this()
20 | {
21 | data = new byte[capacity];
22 | }
23 | public ByteBuf(byte[] content) : this()
24 | {
25 | data = content;
26 | mWritePos = content.Length;
27 | }
28 | public ByteBuf(ByteBuf oldbuf) : this()
29 | {
30 | mReadPos = oldbuf.mReadPos;
31 | mWritePos = oldbuf.mWritePos;
32 | data = new byte[oldbuf.data.Length];
33 | if (data.Length > 0)
34 | {
35 | Array.Copy(oldbuf.data, data, data.Length);
36 | }
37 | }
38 | #endregion
39 | #region Private Mothed
40 |
41 | private void Init()
42 | {
43 | mReadPos = 0;
44 | mWritePos = 0;
45 | }
46 | public int RawReadIndex(int offset)
47 | {
48 | return mReadPos + offset;
49 | }
50 | private void MoveReadPos(int offset)
51 | {
52 | var newpos = mReadPos + offset;
53 | if (newpos <= mWritePos)
54 | {
55 | mReadPos = newpos;
56 | }
57 | }
58 | public int RawWriteIndex(int offset)
59 | {
60 | return mWritePos + offset;
61 | }
62 | private void MoveWritePos(int offset)
63 | {
64 | var newpos = mWritePos + offset;
65 | if (newpos <= data.Length)
66 | {
67 | mWritePos = newpos;
68 | }
69 | }
70 | #endregion
71 | public void Recapacity(int newCapacity)
72 | {
73 | byte[] old = data;
74 | data = new byte[newCapacity];
75 | Array.Copy(old, data, old.Length);
76 | }
77 |
78 | public void EnsureCapacity(int newCapacity)
79 | {
80 | if (newCapacity > data.Length)
81 | {
82 | Recapacity(newCapacity);
83 | }
84 | }
85 | public void EnsureCapacityChange(int changevalue)
86 | {
87 | int newCapacity = mWritePos + changevalue;
88 | EnsureCapacity(newCapacity);
89 | }
90 |
91 | public void Clear()
92 | {
93 | Init();
94 | }
95 | public byte GetByte(int index)
96 | {
97 | if (CanRead(1))
98 | {
99 | return data[RawReadIndex(index)];
100 | }
101 | return 0;
102 | }
103 | public short GetInt16(int index)
104 | {
105 | if (CanRead(2))
106 | {
107 | return BitConverter.ToInt16(data, RawReadIndex(index));
108 | }
109 | return 0;
110 | }
111 | public int GetInt32(int index)
112 | {
113 | if (CanRead(4))
114 | {
115 | return BitConverter.ToInt32(data, RawReadIndex(index));
116 | }
117 | return 0;
118 | }
119 | public bool CanRead(int index, int length)
120 | {
121 | return mReadPos + index + length <= mWritePos;
122 | }
123 | public bool CanRead(int length)
124 | {
125 | return CanRead(0, length);
126 | }
127 | public byte ReadByte()
128 | {
129 | var bt = GetByte(0);
130 | MoveReadPos(1);
131 | return bt;
132 | }
133 | public short ReadInt16()
134 | {
135 | var v = GetInt16(0);
136 | MoveReadPos(2);
137 | return v;
138 | }
139 | public short ReadShort()
140 | {
141 | return ReadInt16();
142 | }
143 | public int ReadInt32()
144 | {
145 | var v = GetInt32(0);
146 | MoveReadPos(4);
147 | return v;
148 | }
149 | public int GetBytes(int offset, byte[] destArray, int destIndx, int length)
150 | {
151 | if (!CanRead(offset, length))
152 | {
153 | return -1;
154 | }
155 | if (destIndx + length > destArray.Length)
156 | {
157 | return -2;
158 | }
159 | Array.Copy(data, RawReadIndex(offset), destArray, destIndx, length);
160 | return length;
161 | }
162 | public int ReadToBytes(int srcIndx, byte[] destArray, int destIndx, int length)
163 | {
164 | int ret = GetBytes(srcIndx, destArray, destIndx, length);
165 | MoveReadPos(length);
166 | return ret;
167 | }
168 | public int PeekSize()
169 | {
170 | return mWritePos - mReadPos;
171 | }
172 | public int Size { get { return mWritePos - mReadPos; } }
173 | public int Capacity { get { return data.Length; } }
174 | public int WritePos { get { return mWritePos; } }
175 | public int ReadPos { get { return mReadPos; } }
176 | public byte[] RawData { get { return data; } }
177 | public bool CanWrite(int index, int length)
178 | {
179 | return mWritePos + index + length <= data.Length;
180 | }
181 | public bool CanWrite(int length)
182 | {
183 | return CanWrite(0, length);
184 | }
185 | public ByteBuf SetByte(int offset, byte value)
186 | {
187 | if (CanWrite(offset, 1))
188 | {
189 | data[RawWriteIndex(offset)] = value;
190 | }
191 | return this;
192 | }
193 | public void SetBytes(int offset, byte[] src, int srcStartIndex, int len)
194 | {
195 | if (CanWrite(offset, len))
196 | {
197 | Array.Copy(src, srcStartIndex, data, RawWriteIndex(offset), len);
198 | }
199 | }
200 | public void SkipBytes(int length)
201 | {
202 | if (length > 0)
203 | {
204 | MoveReadPos(length);
205 | }
206 | }
207 | public void WriteByte(byte value)
208 | {
209 | EnsureCapacityChange(1);
210 | SetByte(0, value);
211 | MoveWritePos(1);
212 | }
213 | public void WriteInt16(short value)
214 | {
215 | var bytes = BitConverter.GetBytes(value);
216 | WriteBytesFrom(bytes);
217 | }
218 | public void WriteShort(short value)
219 | {
220 | WriteInt16(value);
221 | }
222 | public void WriteInt32(int value)
223 | {
224 | var bytes = BitConverter.GetBytes(value);
225 | WriteBytesFrom(bytes);
226 | }
227 | public void WriteBytesFrom(ByteBuf src)
228 | {
229 | WriteBytesFrom(src, src.Size);
230 | }
231 | public void WriteBytesFrom(ByteBuf src, int len)
232 | {
233 | WriteBytesFrom(0, src.data, src.ReadPos, len);
234 | }
235 | public void WriteBytesFrom(byte[] src)
236 | {
237 | WriteBytesFrom(0, src, 0, src.Length);
238 | }
239 | public void WriteBytesFrom(int offset, byte[] src, int srcStartIndex, int len)
240 | {
241 | if (len > 0)
242 | {
243 | EnsureCapacityChange(len);
244 | Array.Copy(src, srcStartIndex, data, RawWriteIndex(offset), len);
245 | MoveWritePos(len);
246 | }
247 | }
248 | }
249 |
250 |
--------------------------------------------------------------------------------
/ProjectSettings/InputManager.asset:
--------------------------------------------------------------------------------
1 | %YAML 1.1
2 | %TAG !u! tag:unity3d.com,2011:
3 | --- !u!13 &1
4 | InputManager:
5 | m_ObjectHideFlags: 0
6 | serializedVersion: 2
7 | m_Axes:
8 | - serializedVersion: 3
9 | m_Name: Horizontal
10 | descriptiveName:
11 | descriptiveNegativeName:
12 | negativeButton: left
13 | positiveButton: right
14 | altNegativeButton: a
15 | altPositiveButton: d
16 | gravity: 3
17 | dead: 0.001
18 | sensitivity: 3
19 | snap: 1
20 | invert: 0
21 | type: 0
22 | axis: 0
23 | joyNum: 0
24 | - serializedVersion: 3
25 | m_Name: Vertical
26 | descriptiveName:
27 | descriptiveNegativeName:
28 | negativeButton: down
29 | positiveButton: up
30 | altNegativeButton: s
31 | altPositiveButton: w
32 | gravity: 3
33 | dead: 0.001
34 | sensitivity: 3
35 | snap: 1
36 | invert: 0
37 | type: 0
38 | axis: 0
39 | joyNum: 0
40 | - serializedVersion: 3
41 | m_Name: Fire1
42 | descriptiveName:
43 | descriptiveNegativeName:
44 | negativeButton:
45 | positiveButton: left ctrl
46 | altNegativeButton:
47 | altPositiveButton: mouse 0
48 | gravity: 1000
49 | dead: 0.001
50 | sensitivity: 1000
51 | snap: 0
52 | invert: 0
53 | type: 0
54 | axis: 0
55 | joyNum: 0
56 | - serializedVersion: 3
57 | m_Name: Fire2
58 | descriptiveName:
59 | descriptiveNegativeName:
60 | negativeButton:
61 | positiveButton: left alt
62 | altNegativeButton:
63 | altPositiveButton: mouse 1
64 | gravity: 1000
65 | dead: 0.001
66 | sensitivity: 1000
67 | snap: 0
68 | invert: 0
69 | type: 0
70 | axis: 0
71 | joyNum: 0
72 | - serializedVersion: 3
73 | m_Name: Fire3
74 | descriptiveName:
75 | descriptiveNegativeName:
76 | negativeButton:
77 | positiveButton: left shift
78 | altNegativeButton:
79 | altPositiveButton: mouse 2
80 | gravity: 1000
81 | dead: 0.001
82 | sensitivity: 1000
83 | snap: 0
84 | invert: 0
85 | type: 0
86 | axis: 0
87 | joyNum: 0
88 | - serializedVersion: 3
89 | m_Name: Jump
90 | descriptiveName:
91 | descriptiveNegativeName:
92 | negativeButton:
93 | positiveButton: space
94 | altNegativeButton:
95 | altPositiveButton:
96 | gravity: 1000
97 | dead: 0.001
98 | sensitivity: 1000
99 | snap: 0
100 | invert: 0
101 | type: 0
102 | axis: 0
103 | joyNum: 0
104 | - serializedVersion: 3
105 | m_Name: Mouse X
106 | descriptiveName:
107 | descriptiveNegativeName:
108 | negativeButton:
109 | positiveButton:
110 | altNegativeButton:
111 | altPositiveButton:
112 | gravity: 0
113 | dead: 0
114 | sensitivity: 0.1
115 | snap: 0
116 | invert: 0
117 | type: 1
118 | axis: 0
119 | joyNum: 0
120 | - serializedVersion: 3
121 | m_Name: Mouse Y
122 | descriptiveName:
123 | descriptiveNegativeName:
124 | negativeButton:
125 | positiveButton:
126 | altNegativeButton:
127 | altPositiveButton:
128 | gravity: 0
129 | dead: 0
130 | sensitivity: 0.1
131 | snap: 0
132 | invert: 0
133 | type: 1
134 | axis: 1
135 | joyNum: 0
136 | - serializedVersion: 3
137 | m_Name: Mouse ScrollWheel
138 | descriptiveName:
139 | descriptiveNegativeName:
140 | negativeButton:
141 | positiveButton:
142 | altNegativeButton:
143 | altPositiveButton:
144 | gravity: 0
145 | dead: 0
146 | sensitivity: 0.1
147 | snap: 0
148 | invert: 0
149 | type: 1
150 | axis: 2
151 | joyNum: 0
152 | - serializedVersion: 3
153 | m_Name: Horizontal
154 | descriptiveName:
155 | descriptiveNegativeName:
156 | negativeButton:
157 | positiveButton:
158 | altNegativeButton:
159 | altPositiveButton:
160 | gravity: 0
161 | dead: 0.19
162 | sensitivity: 1
163 | snap: 0
164 | invert: 0
165 | type: 2
166 | axis: 0
167 | joyNum: 0
168 | - serializedVersion: 3
169 | m_Name: Vertical
170 | descriptiveName:
171 | descriptiveNegativeName:
172 | negativeButton:
173 | positiveButton:
174 | altNegativeButton:
175 | altPositiveButton:
176 | gravity: 0
177 | dead: 0.19
178 | sensitivity: 1
179 | snap: 0
180 | invert: 1
181 | type: 2
182 | axis: 1
183 | joyNum: 0
184 | - serializedVersion: 3
185 | m_Name: Fire1
186 | descriptiveName:
187 | descriptiveNegativeName:
188 | negativeButton:
189 | positiveButton: joystick button 0
190 | altNegativeButton:
191 | altPositiveButton:
192 | gravity: 1000
193 | dead: 0.001
194 | sensitivity: 1000
195 | snap: 0
196 | invert: 0
197 | type: 0
198 | axis: 0
199 | joyNum: 0
200 | - serializedVersion: 3
201 | m_Name: Fire2
202 | descriptiveName:
203 | descriptiveNegativeName:
204 | negativeButton:
205 | positiveButton: joystick button 1
206 | altNegativeButton:
207 | altPositiveButton:
208 | gravity: 1000
209 | dead: 0.001
210 | sensitivity: 1000
211 | snap: 0
212 | invert: 0
213 | type: 0
214 | axis: 0
215 | joyNum: 0
216 | - serializedVersion: 3
217 | m_Name: Fire3
218 | descriptiveName:
219 | descriptiveNegativeName:
220 | negativeButton:
221 | positiveButton: joystick button 2
222 | altNegativeButton:
223 | altPositiveButton:
224 | gravity: 1000
225 | dead: 0.001
226 | sensitivity: 1000
227 | snap: 0
228 | invert: 0
229 | type: 0
230 | axis: 0
231 | joyNum: 0
232 | - serializedVersion: 3
233 | m_Name: Jump
234 | descriptiveName:
235 | descriptiveNegativeName:
236 | negativeButton:
237 | positiveButton: joystick button 3
238 | altNegativeButton:
239 | altPositiveButton:
240 | gravity: 1000
241 | dead: 0.001
242 | sensitivity: 1000
243 | snap: 0
244 | invert: 0
245 | type: 0
246 | axis: 0
247 | joyNum: 0
248 | - serializedVersion: 3
249 | m_Name: Submit
250 | descriptiveName:
251 | descriptiveNegativeName:
252 | negativeButton:
253 | positiveButton: return
254 | altNegativeButton:
255 | altPositiveButton: joystick button 0
256 | gravity: 1000
257 | dead: 0.001
258 | sensitivity: 1000
259 | snap: 0
260 | invert: 0
261 | type: 0
262 | axis: 0
263 | joyNum: 0
264 | - serializedVersion: 3
265 | m_Name: Submit
266 | descriptiveName:
267 | descriptiveNegativeName:
268 | negativeButton:
269 | positiveButton: enter
270 | altNegativeButton:
271 | altPositiveButton: space
272 | gravity: 1000
273 | dead: 0.001
274 | sensitivity: 1000
275 | snap: 0
276 | invert: 0
277 | type: 0
278 | axis: 0
279 | joyNum: 0
280 | - serializedVersion: 3
281 | m_Name: Cancel
282 | descriptiveName:
283 | descriptiveNegativeName:
284 | negativeButton:
285 | positiveButton: escape
286 | altNegativeButton:
287 | altPositiveButton: joystick button 1
288 | gravity: 1000
289 | dead: 0.001
290 | sensitivity: 1000
291 | snap: 0
292 | invert: 0
293 | type: 0
294 | axis: 0
295 | joyNum: 0
296 |
--------------------------------------------------------------------------------
/kcpforunity.csproj:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 | Debug
5 | AnyCPU
6 | 10.0.20506
7 | 2.0
8 | {6EEBB32C-F259-4A35-7134-E198984C8870}
9 | Library
10 | Assembly-CSharp
11 | 512
12 | {E097FAD1-6243-4DAD-9C02-E9B9EFC3FFC1};{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}
13 | .NETFramework
14 | v3.5
15 | Unity Full v3.5
16 |
17 | Game:1
18 | Android:13
19 | 5.4.5f1
20 |
21 | 4
22 |
23 |
24 | pdbonly
25 | false
26 | Temp\UnityVS_bin\Debug\
27 | Temp\UnityVS_obj\Debug\
28 | prompt
29 | 4
30 | DEBUG;TRACE;UNITY_5_3_OR_NEWER;UNITY_5_4_OR_NEWER;UNITY_5_4_5;UNITY_5_4;UNITY_5;ENABLE_NEW_BUGREPORTER;ENABLE_AUDIO;ENABLE_CACHING;ENABLE_CLOTH;ENABLE_EDITOR_RETINA;ENABLE_RETINA_GUISTYLES;ENABLE_FRAME_DEBUGGER;ENABLE_GENERICS;ENABLE_HOME_SCREEN;ENABLE_IMAGEEFFECTS;ENABLE_LIGHT_PROBES_LEGACY;ENABLE_MICROPHONE;ENABLE_MULTIPLE_DISPLAYS;ENABLE_PHYSICS;ENABLE_PLUGIN_INSPECTOR;ENABLE_SHADOWS;ENABLE_SPRITERENDERER_FLIPPING;ENABLE_SPRITES;ENABLE_SPRITE_POLYGON;ENABLE_TERRAIN;ENABLE_RAKNET;ENABLE_UNET;ENABLE_UNITYEVENTS;ENABLE_VR;ENABLE_WEBCAM;ENABLE_WWW;ENABLE_CLOUD_SERVICES;ENABLE_CLOUD_SERVICES_COLLAB;ENABLE_CLOUD_SERVICES_ADS;ENABLE_CLOUD_HUB;ENABLE_CLOUD_PROJECT_ID;ENABLE_CLOUD_SERVICES_CRASH_REPORTING;ENABLE_CLOUD_SERVICES_PURCHASING;ENABLE_CLOUD_SERVICES_ANALYTICS;ENABLE_CLOUD_SERVICES_UNET;ENABLE_CLOUD_SERVICES_BUILD;ENABLE_CLOUD_LICENSE;ENABLE_EDITOR_METRICS;ENABLE_EDITOR_METRICS_CACHING;INCLUDE_DYNAMIC_GI;INCLUDE_GI;INCLUDE_IL2CPP;INCLUDE_DIRECTX12;PLATFORM_SUPPORTS_MONO;INCLUDE_PUBNUB;ENABLE_LOCALIZATION;ENABLE_ANDROID_ATLAS_ETC1_COMPRESSION;ENABLE_EDITOR_TESTS_RUNNER;UNITY_ANDROID;UNITY_ANDROID_API;ENABLE_SUBSTANCE;UNITY_ANDROID_API;ENABLE_TEXTUREID_MAP;ENABLE_EGL;ENABLE_NETWORK;ENABLE_RUNTIME_GI;ENABLE_CRUNCH_TEXTURE_COMPRESSION;ENABLE_UNITYWEBREQUEST;PLATFORM_SUPPORTS_ADS_ID;UNITY_CAN_SHOW_SPLASH_SCREEN;ENABLE_UNITYADS_RUNTIME;UNITY_UNITYADS_API;ENABLE_MONO;DEVELOPMENT_BUILD;ENABLE_PROFILER;DEBUG;TRACE;UNITY_ASSERTIONS;UNITY_EDITOR;UNITY_EDITOR_64;UNITY_EDITOR_WIN;UNITY_TEAM_LICENSE;ENABLE_VSTU;UNITY_PRO_LICENSE
31 | false
32 |
33 |
34 | pdbonly
35 | false
36 | Temp\UnityVS_bin\Release\
37 | Temp\UnityVS_obj\Release\
38 | prompt
39 | 4
40 | TRACE;UNITY_5_3_OR_NEWER;UNITY_5_4_OR_NEWER;UNITY_5_4_5;UNITY_5_4;UNITY_5;ENABLE_NEW_BUGREPORTER;ENABLE_AUDIO;ENABLE_CACHING;ENABLE_CLOTH;ENABLE_EDITOR_RETINA;ENABLE_RETINA_GUISTYLES;ENABLE_FRAME_DEBUGGER;ENABLE_GENERICS;ENABLE_HOME_SCREEN;ENABLE_IMAGEEFFECTS;ENABLE_LIGHT_PROBES_LEGACY;ENABLE_MICROPHONE;ENABLE_MULTIPLE_DISPLAYS;ENABLE_PHYSICS;ENABLE_PLUGIN_INSPECTOR;ENABLE_SHADOWS;ENABLE_SPRITERENDERER_FLIPPING;ENABLE_SPRITES;ENABLE_SPRITE_POLYGON;ENABLE_TERRAIN;ENABLE_RAKNET;ENABLE_UNET;ENABLE_UNITYEVENTS;ENABLE_VR;ENABLE_WEBCAM;ENABLE_WWW;ENABLE_CLOUD_SERVICES;ENABLE_CLOUD_SERVICES_COLLAB;ENABLE_CLOUD_SERVICES_ADS;ENABLE_CLOUD_HUB;ENABLE_CLOUD_PROJECT_ID;ENABLE_CLOUD_SERVICES_CRASH_REPORTING;ENABLE_CLOUD_SERVICES_PURCHASING;ENABLE_CLOUD_SERVICES_ANALYTICS;ENABLE_CLOUD_SERVICES_UNET;ENABLE_CLOUD_SERVICES_BUILD;ENABLE_CLOUD_LICENSE;ENABLE_EDITOR_METRICS;ENABLE_EDITOR_METRICS_CACHING;INCLUDE_DYNAMIC_GI;INCLUDE_GI;INCLUDE_IL2CPP;INCLUDE_DIRECTX12;PLATFORM_SUPPORTS_MONO;INCLUDE_PUBNUB;ENABLE_LOCALIZATION;ENABLE_ANDROID_ATLAS_ETC1_COMPRESSION;ENABLE_EDITOR_TESTS_RUNNER;UNITY_ANDROID;UNITY_ANDROID_API;ENABLE_SUBSTANCE;UNITY_ANDROID_API;ENABLE_TEXTUREID_MAP;ENABLE_EGL;ENABLE_NETWORK;ENABLE_RUNTIME_GI;ENABLE_CRUNCH_TEXTURE_COMPRESSION;ENABLE_UNITYWEBREQUEST;PLATFORM_SUPPORTS_ADS_ID;UNITY_CAN_SHOW_SPLASH_SCREEN;ENABLE_UNITYADS_RUNTIME;UNITY_UNITYADS_API;ENABLE_MONO;DEVELOPMENT_BUILD;ENABLE_PROFILER;DEBUG;TRACE;UNITY_ASSERTIONS;UNITY_EDITOR;UNITY_EDITOR_64;UNITY_EDITOR_WIN;UNITY_TEAM_LICENSE;ENABLE_VSTU;UNITY_PRO_LICENSE
41 | false
42 |
43 |
44 |
45 |
46 |
47 |
48 |
49 |
50 |
51 |
52 |
53 | Library\UnityAssemblies\UnityEngine.dll
54 |
55 |
56 | Library\UnityAssemblies\UnityEngine.UI.dll
57 |
58 |
59 | Library\UnityAssemblies\UnityEngine.Networking.dll
60 |
61 |
62 | Library\UnityAssemblies\UnityEditor.dll
63 |
64 |
65 | Library\UnityAssemblies\UnityEditor.iOS.Extensions.Xcode.dll
66 |
67 |
68 | Library\UnityAssemblies\UnityEditor.iOS.Extensions.Common.dll
69 |
70 |
71 | Assets\Plugins\protobuf\Google.Protobuf.dll
72 |
73 |
74 |
75 |
76 | {0EB4FC5E-89E0-A1AB-14A6-58A6E5C41B23}
77 | kcpforunity.Plugins
78 |
79 |
80 |
81 |
82 |
83 |
84 |
85 |
86 |
87 |
88 |
89 |
90 |
91 |
--------------------------------------------------------------------------------
/kcpforunity.Plugins.csproj:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 | Debug
5 | AnyCPU
6 | 10.0.20506
7 | 2.0
8 | {0EB4FC5E-89E0-A1AB-14A6-58A6E5C41B23}
9 | Library
10 | Assembly-CSharp-firstpass
11 | 512
12 | {E097FAD1-6243-4DAD-9C02-E9B9EFC3FFC1};{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}
13 | .NETFramework
14 | v3.5
15 | Unity Full v3.5
16 |
17 | GamePlugins:3
18 | Android:13
19 | 5.4.5f1
20 |
21 | 4
22 |
23 |
24 | pdbonly
25 | false
26 | Temp\UnityVS_bin\Debug\
27 | Temp\UnityVS_obj\Debug\
28 | prompt
29 | 4
30 | DEBUG;TRACE;UNITY_5_3_OR_NEWER;UNITY_5_4_OR_NEWER;UNITY_5_4_5;UNITY_5_4;UNITY_5;ENABLE_NEW_BUGREPORTER;ENABLE_AUDIO;ENABLE_CACHING;ENABLE_CLOTH;ENABLE_EDITOR_RETINA;ENABLE_RETINA_GUISTYLES;ENABLE_FRAME_DEBUGGER;ENABLE_GENERICS;ENABLE_HOME_SCREEN;ENABLE_IMAGEEFFECTS;ENABLE_LIGHT_PROBES_LEGACY;ENABLE_MICROPHONE;ENABLE_MULTIPLE_DISPLAYS;ENABLE_PHYSICS;ENABLE_PLUGIN_INSPECTOR;ENABLE_SHADOWS;ENABLE_SPRITERENDERER_FLIPPING;ENABLE_SPRITES;ENABLE_SPRITE_POLYGON;ENABLE_TERRAIN;ENABLE_RAKNET;ENABLE_UNET;ENABLE_UNITYEVENTS;ENABLE_VR;ENABLE_WEBCAM;ENABLE_WWW;ENABLE_CLOUD_SERVICES;ENABLE_CLOUD_SERVICES_COLLAB;ENABLE_CLOUD_SERVICES_ADS;ENABLE_CLOUD_HUB;ENABLE_CLOUD_PROJECT_ID;ENABLE_CLOUD_SERVICES_CRASH_REPORTING;ENABLE_CLOUD_SERVICES_PURCHASING;ENABLE_CLOUD_SERVICES_ANALYTICS;ENABLE_CLOUD_SERVICES_UNET;ENABLE_CLOUD_SERVICES_BUILD;ENABLE_CLOUD_LICENSE;ENABLE_EDITOR_METRICS;ENABLE_EDITOR_METRICS_CACHING;INCLUDE_DYNAMIC_GI;INCLUDE_GI;INCLUDE_IL2CPP;INCLUDE_DIRECTX12;PLATFORM_SUPPORTS_MONO;INCLUDE_PUBNUB;ENABLE_LOCALIZATION;ENABLE_ANDROID_ATLAS_ETC1_COMPRESSION;ENABLE_EDITOR_TESTS_RUNNER;UNITY_ANDROID;UNITY_ANDROID_API;ENABLE_SUBSTANCE;UNITY_ANDROID_API;ENABLE_TEXTUREID_MAP;ENABLE_EGL;ENABLE_NETWORK;ENABLE_RUNTIME_GI;ENABLE_CRUNCH_TEXTURE_COMPRESSION;ENABLE_UNITYWEBREQUEST;PLATFORM_SUPPORTS_ADS_ID;UNITY_CAN_SHOW_SPLASH_SCREEN;ENABLE_UNITYADS_RUNTIME;UNITY_UNITYADS_API;ENABLE_MONO;DEVELOPMENT_BUILD;ENABLE_PROFILER;DEBUG;TRACE;UNITY_ASSERTIONS;UNITY_EDITOR;UNITY_EDITOR_64;UNITY_EDITOR_WIN;UNITY_TEAM_LICENSE;ENABLE_VSTU;UNITY_PRO_LICENSE
31 | false
32 |
33 |
34 | pdbonly
35 | false
36 | Temp\UnityVS_bin\Release\
37 | Temp\UnityVS_obj\Release\
38 | prompt
39 | 4
40 | TRACE;UNITY_5_3_OR_NEWER;UNITY_5_4_OR_NEWER;UNITY_5_4_5;UNITY_5_4;UNITY_5;ENABLE_NEW_BUGREPORTER;ENABLE_AUDIO;ENABLE_CACHING;ENABLE_CLOTH;ENABLE_EDITOR_RETINA;ENABLE_RETINA_GUISTYLES;ENABLE_FRAME_DEBUGGER;ENABLE_GENERICS;ENABLE_HOME_SCREEN;ENABLE_IMAGEEFFECTS;ENABLE_LIGHT_PROBES_LEGACY;ENABLE_MICROPHONE;ENABLE_MULTIPLE_DISPLAYS;ENABLE_PHYSICS;ENABLE_PLUGIN_INSPECTOR;ENABLE_SHADOWS;ENABLE_SPRITERENDERER_FLIPPING;ENABLE_SPRITES;ENABLE_SPRITE_POLYGON;ENABLE_TERRAIN;ENABLE_RAKNET;ENABLE_UNET;ENABLE_UNITYEVENTS;ENABLE_VR;ENABLE_WEBCAM;ENABLE_WWW;ENABLE_CLOUD_SERVICES;ENABLE_CLOUD_SERVICES_COLLAB;ENABLE_CLOUD_SERVICES_ADS;ENABLE_CLOUD_HUB;ENABLE_CLOUD_PROJECT_ID;ENABLE_CLOUD_SERVICES_CRASH_REPORTING;ENABLE_CLOUD_SERVICES_PURCHASING;ENABLE_CLOUD_SERVICES_ANALYTICS;ENABLE_CLOUD_SERVICES_UNET;ENABLE_CLOUD_SERVICES_BUILD;ENABLE_CLOUD_LICENSE;ENABLE_EDITOR_METRICS;ENABLE_EDITOR_METRICS_CACHING;INCLUDE_DYNAMIC_GI;INCLUDE_GI;INCLUDE_IL2CPP;INCLUDE_DIRECTX12;PLATFORM_SUPPORTS_MONO;INCLUDE_PUBNUB;ENABLE_LOCALIZATION;ENABLE_ANDROID_ATLAS_ETC1_COMPRESSION;ENABLE_EDITOR_TESTS_RUNNER;UNITY_ANDROID;UNITY_ANDROID_API;ENABLE_SUBSTANCE;UNITY_ANDROID_API;ENABLE_TEXTUREID_MAP;ENABLE_EGL;ENABLE_NETWORK;ENABLE_RUNTIME_GI;ENABLE_CRUNCH_TEXTURE_COMPRESSION;ENABLE_UNITYWEBREQUEST;PLATFORM_SUPPORTS_ADS_ID;UNITY_CAN_SHOW_SPLASH_SCREEN;ENABLE_UNITYADS_RUNTIME;UNITY_UNITYADS_API;ENABLE_MONO;DEVELOPMENT_BUILD;ENABLE_PROFILER;DEBUG;TRACE;UNITY_ASSERTIONS;UNITY_EDITOR;UNITY_EDITOR_64;UNITY_EDITOR_WIN;UNITY_TEAM_LICENSE;ENABLE_VSTU;UNITY_PRO_LICENSE
41 | false
42 |
43 |
44 |
45 |
46 |
47 |
48 |
49 |
50 |
51 |
52 |
53 | Library\UnityAssemblies\UnityEngine.dll
54 |
55 |
56 | Library\UnityAssemblies\UnityEngine.UI.dll
57 |
58 |
59 | Library\UnityAssemblies\UnityEngine.Networking.dll
60 |
61 |
62 | Library\UnityAssemblies\UnityEditor.dll
63 |
64 |
65 | Library\UnityAssemblies\UnityEditor.iOS.Extensions.Xcode.dll
66 |
67 |
68 | Library\UnityAssemblies\UnityEditor.iOS.Extensions.Common.dll
69 |
70 |
71 | Assets\Plugins\protobuf\Google.Protobuf.dll
72 |
73 |
74 |
75 |
76 |
77 |
78 |
79 |
80 |
81 |
82 |
83 |
84 |
85 |
86 |
87 |
88 |
89 |
90 |
91 |
92 |
93 |
--------------------------------------------------------------------------------
/Assets/Plugins/kcpForUnity/UdpSocket.cs:
--------------------------------------------------------------------------------
1 | using System;
2 | using System.Collections.Generic;
3 | using System.Linq;
4 | using System.Text;
5 | using System.Net.Sockets;
6 | using System.Net;
7 | using System.Threading;
8 | using System.Diagnostics;
9 |
10 | namespace KcpProject.v2
11 | {
12 | // 客户端随机生成conv并作为后续与服务器通信
13 | public class UdpSocket
14 | {
15 | public enum State
16 | {
17 | Connect,
18 | Disconnect
19 | }
20 | public static int lostPackRate = 10;
21 | private ByteBuf rcvCache = new ByteBuf(1500);
22 | private byte[] msgBuffCache = new byte[0];
23 | private State state = State.Disconnect;
24 | public bool rcvSync = true;
25 |
26 | private UdpClient mUdpClient;
27 | private IPEndPoint mIPEndPoint;
28 | private IPEndPoint mSvrEndPoint;
29 | private int nxtPacketSize = -1;
30 | private Kcp mKcp;
31 | private Action onProcessMessage;
32 | public int rtt = 0;
33 | private AutoResetEvent kcpThreadNotify;
34 | private QueueSync rcv_queue = new QueueSync(128);
35 | private QueueSync snd_queue = new QueueSync(128);
36 | private CxExtension.ObjectPool mSegpool;
37 | public UdpSocket(Action handler)
38 | {
39 | onProcessMessage = handler;
40 | kcpThreadNotify = new AutoResetEvent(false);
41 | }
42 |
43 | public void Connect(string host, int port)
44 | {
45 | mSvrEndPoint = new IPEndPoint(IPAddress.Parse(host), port);
46 | mUdpClient = new UdpClient(host, port);
47 | UnityEngine.Debug.LogFormat("snd buff size:{0},rcv buff size:{1}", mUdpClient.Client.SendBufferSize, mUdpClient.Client.ReceiveBufferSize);
48 | mUdpClient.Connect(mSvrEndPoint);
49 | state = State.Connect;
50 | //init_kcp((UInt32)new Random((int)DateTime.Now.Ticks).Next(1, Int32.MaxValue));
51 | init_kcp(0);
52 | if (rcvSync)
53 | {
54 | mUdpClient.BeginReceive(ReceiveCallback, this);
55 | }
56 | else
57 | {
58 | //ThreadPool.QueueUserWorkItem(new WaitCallback(process_rcv_queue));
59 | }
60 | ThreadPool.QueueUserWorkItem(new WaitCallback(process_kcpio_queue));
61 | }
62 |
63 | public bool Connected { get { return state == State.Connect; } }
64 | void init_kcp(UInt32 conv)
65 | {
66 | mKcp = new Kcp((int)conv, (ByteBuf buf) =>
67 | {
68 | //if (kcpUtil.CountIncludePercent(lostPackRate))
69 | //if (testUtil.RandIncludePercent(100 - lostPackRate))
70 | {
71 | mUdpClient.Send(buf.RawData,buf.Size );
72 | }
73 | });
74 | mSegpool = new CxExtension.ObjectPool();
75 | mKcp.SetSegmentHook(mSegpool.Get, mSegpool.Return);
76 | // fast mode.
77 | mKcp.NoDelay(1, 1, 2, 1);
78 | mKcp.WndSize(255, 255);
79 | }
80 |
81 | void ReceiveCallback(IAsyncResult ar)
82 | {
83 | Byte[] data = (mIPEndPoint == null) ?
84 | mUdpClient.Receive(ref mIPEndPoint) :
85 | mUdpClient.EndReceive(ar, ref mIPEndPoint);
86 |
87 | if (null != data)
88 | {
89 | var dt = new ByteBuf(data);
90 | rcv_queue.Enqueue(dt);
91 | kcpThreadNotify.Set();
92 | }
93 |
94 | if (mUdpClient != null)
95 | {
96 | // try to receive again.
97 | mUdpClient.BeginReceive(ReceiveCallback, this);
98 | }
99 | }
100 |
101 | public void Send(byte[] data)
102 | {
103 | var btBuf = Pack(data);
104 | snd_queue.Enqueue(btBuf);
105 | kcpThreadNotify.Set();
106 | }
107 | private void SendPacket(ByteBuf content)
108 | {
109 | mKcp.Send(content);
110 | }
111 | public void Close()
112 | {
113 | state = State.Disconnect;
114 | mUdpClient.Close();
115 | }
116 | public void ProcessMessage(byte[] buff, int length)
117 | {
118 | if (onProcessMessage != null)
119 | {
120 | onProcessMessage(buff, length);
121 | }
122 | }
123 | ///
124 | /// pack data to:data length to data pre
125 | ///
126 | ///
127 | ///
128 | public ByteBuf Pack(byte[] data)
129 | {
130 | var btBuf = new ByteBuf(data.Length + 4);
131 | btBuf.WriteInt32(data.Length);
132 | btBuf.WriteBytesFrom(data);
133 | return btBuf;
134 | }
135 | public void Unpack(ByteBuf buf)
136 | {
137 | while (true)
138 | {
139 | if (nxtPacketSize < 0)
140 | {
141 | if (buf.PeekSize() >= 4)
142 | {
143 | nxtPacketSize = buf.ReadInt32();
144 | }
145 | else
146 | {
147 | break;
148 | }
149 | }
150 | if (buf.PeekSize() >= nxtPacketSize)
151 | {
152 | //var data = buf.read
153 | msgBuffCache = msgBuffCache.Recapacity(nxtPacketSize);
154 | int length = buf.ReadToBytes(0, msgBuffCache, 0, nxtPacketSize);
155 | ProcessMessage(msgBuffCache, nxtPacketSize);
156 |
157 | nxtPacketSize = -1;
158 | }
159 | else
160 | {
161 | break;
162 | }
163 | }
164 | }
165 | void process_kcpio_queue(object state)
166 | {
167 | while (Connected)
168 | {
169 | try
170 | {
171 | //send process
172 | snd_queue.DequeueAll(it =>
173 | {
174 | SendPacket(it);
175 | //mKcp.Send(it);
176 | });
177 | Stopwatch t = new Stopwatch();
178 | t.Start();
179 | mKcp.Flush((int)kcpUtil.nowTotalMilliseconds);
180 | rcv_queue.DequeueAll(it =>
181 | {
182 | mKcp.Input(it);
183 | });
184 | rcvCache.Clear();
185 | //rcvCache.Capacity(peekSize);
186 | while (true)
187 | {
188 | int peekSize = mKcp.PeekSize();
189 | if (peekSize > 0)
190 | {
191 | int rcvSize = mKcp.Receive(rcvCache);
192 | if (rcvSize > 0)
193 | {
194 | //packer.Recv(rcvCache);
195 | Unpack(rcvCache);
196 | }
197 | else { break; }
198 | }
199 | else { break; }
200 | }
201 | t.Stop();
202 | if (t.ElapsedMilliseconds > 5)
203 | {
204 | Console.WriteLine(string.Format("used time:{0}", t.ElapsedMilliseconds));
205 | }
206 | }
207 | catch (Exception e)
208 | {
209 | Console.WriteLine(e.ToString());
210 | }
211 | finally
212 | {
213 | //Console.WriteLine("thread run error");
214 | }
215 | if (kcpThreadNotify.WaitOne(5))
216 | {
217 | Thread.Sleep(2);
218 | }
219 | }
220 | }
221 | }
222 | }
223 |
--------------------------------------------------------------------------------
/LICENSE:
--------------------------------------------------------------------------------
1 | Apache License
2 | Version 2.0, January 2004
3 | http://www.apache.org/licenses/
4 |
5 | TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
6 |
7 | 1. Definitions.
8 |
9 | "License" shall mean the terms and conditions for use, reproduction, and
10 | distribution as defined by Sections 1 through 9 of this document.
11 |
12 | "Licensor" shall mean the copyright owner or entity authorized by the copyright
13 | owner that is granting the License.
14 |
15 | "Legal Entity" shall mean the union of the acting entity and all other entities
16 | that control, are controlled by, or are under common control with that entity.
17 | For the purposes of this definition, "control" means (i) the power, direct or
18 | indirect, to cause the direction or management of such entity, whether by
19 | contract or otherwise, or (ii) ownership of fifty percent (50%) or more of the
20 | outstanding shares, or (iii) beneficial ownership of such entity.
21 |
22 | "You" (or "Your") shall mean an individual or Legal Entity exercising
23 | permissions granted by this License.
24 |
25 | "Source" form shall mean the preferred form for making modifications, including
26 | but not limited to software source code, documentation source, and configuration
27 | files.
28 |
29 | "Object" form shall mean any form resulting from mechanical transformation or
30 | translation of a Source form, including but not limited to compiled object code,
31 | generated documentation, and conversions to other media types.
32 |
33 | "Work" shall mean the work of authorship, whether in Source or Object form, made
34 | available under the License, as indicated by a copyright notice that is included
35 | in or attached to the work (an example is provided in the Appendix below).
36 |
37 | "Derivative Works" shall mean any work, whether in Source or Object form, that
38 | is based on (or derived from) the Work and for which the editorial revisions,
39 | annotations, elaborations, or other modifications represent, as a whole, an
40 | original work of authorship. For the purposes of this License, Derivative Works
41 | shall not include works that remain separable from, or merely link (or bind by
42 | name) to the interfaces of, the Work and Derivative Works thereof.
43 |
44 | "Contribution" shall mean any work of authorship, including the original version
45 | of the Work and any modifications or additions to that Work or Derivative Works
46 | thereof, that is intentionally submitted to Licensor for inclusion in the Work
47 | by the copyright owner or by an individual or Legal Entity authorized to submit
48 | on behalf of the copyright owner. For the purposes of this definition,
49 | "submitted" means any form of electronic, verbal, or written communication sent
50 | to the Licensor or its representatives, including but not limited to
51 | communication on electronic mailing lists, source code control systems, and
52 | issue tracking systems that are managed by, or on behalf of, the Licensor for
53 | the purpose of discussing and improving the Work, but excluding communication
54 | that is conspicuously marked or otherwise designated in writing by the copyright
55 | owner as "Not a Contribution."
56 |
57 | "Contributor" shall mean Licensor and any individual or Legal Entity on behalf
58 | of whom a Contribution has been received by Licensor and subsequently
59 | incorporated within the Work.
60 |
61 | 2. Grant of Copyright License.
62 |
63 | Subject to the terms and conditions of this License, each Contributor hereby
64 | grants to You a perpetual, worldwide, non-exclusive, no-charge, royalty-free,
65 | irrevocable copyright license to reproduce, prepare Derivative Works of,
66 | publicly display, publicly perform, sublicense, and distribute the Work and such
67 | Derivative Works in Source or Object form.
68 |
69 | 3. Grant of Patent License.
70 |
71 | Subject to the terms and conditions of this License, each Contributor hereby
72 | grants to You a perpetual, worldwide, non-exclusive, no-charge, royalty-free,
73 | irrevocable (except as stated in this section) patent license to make, have
74 | made, use, offer to sell, sell, import, and otherwise transfer the Work, where
75 | such license applies only to those patent claims licensable by such Contributor
76 | that are necessarily infringed by their Contribution(s) alone or by combination
77 | of their Contribution(s) with the Work to which such Contribution(s) was
78 | submitted. If You institute patent litigation against any entity (including a
79 | cross-claim or counterclaim in a lawsuit) alleging that the Work or a
80 | Contribution incorporated within the Work constitutes direct or contributory
81 | patent infringement, then any patent licenses granted to You under this License
82 | for that Work shall terminate as of the date such litigation is filed.
83 |
84 | 4. Redistribution.
85 |
86 | You may reproduce and distribute copies of the Work or Derivative Works thereof
87 | in any medium, with or without modifications, and in Source or Object form,
88 | provided that You meet the following conditions:
89 |
90 | You must give any other recipients of the Work or Derivative Works a copy of
91 | this License; and
92 | You must cause any modified files to carry prominent notices stating that You
93 | changed the files; and
94 | You must retain, in the Source form of any Derivative Works that You distribute,
95 | all copyright, patent, trademark, and attribution notices from the Source form
96 | of the Work, excluding those notices that do not pertain to any part of the
97 | Derivative Works; and
98 | If the Work includes a "NOTICE" text file as part of its distribution, then any
99 | Derivative Works that You distribute must include a readable copy of the
100 | attribution notices contained within such NOTICE file, excluding those notices
101 | that do not pertain to any part of the Derivative Works, in at least one of the
102 | following places: within a NOTICE text file distributed as part of the
103 | Derivative Works; within the Source form or documentation, if provided along
104 | with the Derivative Works; or, within a display generated by the Derivative
105 | Works, if and wherever such third-party notices normally appear. The contents of
106 | the NOTICE file are for informational purposes only and do not modify the
107 | License. You may add Your own attribution notices within Derivative Works that
108 | You distribute, alongside or as an addendum to the NOTICE text from the Work,
109 | provided that such additional attribution notices cannot be construed as
110 | modifying the License.
111 | You may add Your own copyright statement to Your modifications and may provide
112 | additional or different license terms and conditions for use, reproduction, or
113 | distribution of Your modifications, or for any such Derivative Works as a whole,
114 | provided Your use, reproduction, and distribution of the Work otherwise complies
115 | with the conditions stated in this License.
116 |
117 | 5. Submission of Contributions.
118 |
119 | Unless You explicitly state otherwise, any Contribution intentionally submitted
120 | for inclusion in the Work by You to the Licensor shall be under the terms and
121 | conditions of this License, without any additional terms or conditions.
122 | Notwithstanding the above, nothing herein shall supersede or modify the terms of
123 | any separate license agreement you may have executed with Licensor regarding
124 | such Contributions.
125 |
126 | 6. Trademarks.
127 |
128 | This License does not grant permission to use the trade names, trademarks,
129 | service marks, or product names of the Licensor, except as required for
130 | reasonable and customary use in describing the origin of the Work and
131 | reproducing the content of the NOTICE file.
132 |
133 | 7. Disclaimer of Warranty.
134 |
135 | Unless required by applicable law or agreed to in writing, Licensor provides the
136 | Work (and each Contributor provides its Contributions) on an "AS IS" BASIS,
137 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied,
138 | including, without limitation, any warranties or conditions of TITLE,
139 | NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A PARTICULAR PURPOSE. You are
140 | solely responsible for determining the appropriateness of using or
141 | redistributing the Work and assume any risks associated with Your exercise of
142 | permissions under this License.
143 |
144 | 8. Limitation of Liability.
145 |
146 | In no event and under no legal theory, whether in tort (including negligence),
147 | contract, or otherwise, unless required by applicable law (such as deliberate
148 | and grossly negligent acts) or agreed to in writing, shall any Contributor be
149 | liable to You for damages, including any direct, indirect, special, incidental,
150 | or consequential damages of any character arising as a result of this License or
151 | out of the use or inability to use the Work (including but not limited to
152 | damages for loss of goodwill, work stoppage, computer failure or malfunction, or
153 | any and all other commercial damages or losses), even if such Contributor has
154 | been advised of the possibility of such damages.
155 |
156 | 9. Accepting Warranty or Additional Liability.
157 |
158 | While redistributing the Work or Derivative Works thereof, You may choose to
159 | offer, and charge a fee for, acceptance of support, warranty, indemnity, or
160 | other liability obligations and/or rights consistent with this License. However,
161 | in accepting such obligations, You may act only on Your own behalf and on Your
162 | sole responsibility, not on behalf of any other Contributor, and only if You
163 | agree to indemnify, defend, and hold each Contributor harmless for any liability
164 | incurred by, or claims asserted against, such Contributor by reason of your
165 | accepting any such warranty or additional liability.
166 |
167 | END OF TERMS AND CONDITIONS
168 |
169 | APPENDIX: How to apply the Apache License to your work
170 |
171 | To apply the Apache License to your work, attach the following boilerplate
172 | notice, with the fields enclosed by brackets "{}" replaced with your own
173 | identifying information. (Don't include the brackets!) The text should be
174 | enclosed in the appropriate comment syntax for the file format. We also
175 | recommend that a file or class name and description of purpose be included on
176 | the same "printed page" as the copyright notice for easier identification within
177 | third-party archives.
178 |
179 | Copyright 2017 Advancer68
180 |
181 | Licensed under the Apache License, Version 2.0 (the "License");
182 | you may not use this file except in compliance with the License.
183 | You may obtain a copy of the License at
184 |
185 | http://www.apache.org/licenses/LICENSE-2.0
186 |
187 | Unless required by applicable law or agreed to in writing, software
188 | distributed under the License is distributed on an "AS IS" BASIS,
189 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
190 | See the License for the specific language governing permissions and
191 | limitations under the License.
--------------------------------------------------------------------------------
/ProjectSettings/ProjectSettings.asset:
--------------------------------------------------------------------------------
1 | %YAML 1.1
2 | %TAG !u! tag:unity3d.com,2011:
3 | --- !u!129 &1
4 | PlayerSettings:
5 | m_ObjectHideFlags: 0
6 | serializedVersion: 8
7 | productGUID: e8e448bce0bbcc642bd58e3bd4f340b9
8 | AndroidProfiler: 0
9 | defaultScreenOrientation: 4
10 | targetDevice: 2
11 | useOnDemandResources: 0
12 | accelerometerFrequency: 60
13 | companyName: lmd
14 | productName: TestKcp
15 | defaultCursor: {fileID: 0}
16 | cursorHotspot: {x: 0, y: 0}
17 | m_SplashScreenStyle: 0
18 | m_ShowUnitySplashScreen: 1
19 | m_VirtualRealitySplashScreen: {fileID: 0}
20 | defaultScreenWidth: 1024
21 | defaultScreenHeight: 768
22 | defaultScreenWidthWeb: 960
23 | defaultScreenHeightWeb: 600
24 | m_RenderingPath: 1
25 | m_MobileRenderingPath: 1
26 | m_ActiveColorSpace: 0
27 | m_MTRendering: 1
28 | m_MobileMTRendering: 0
29 | m_StackTraceTypes: 010000000100000001000000010000000100000001000000
30 | iosShowActivityIndicatorOnLoading: -1
31 | androidShowActivityIndicatorOnLoading: -1
32 | tizenShowActivityIndicatorOnLoading: -1
33 | iosAppInBackgroundBehavior: 0
34 | displayResolutionDialog: 1
35 | iosAllowHTTPDownload: 1
36 | allowedAutorotateToPortrait: 0
37 | allowedAutorotateToPortraitUpsideDown: 0
38 | allowedAutorotateToLandscapeRight: 1
39 | allowedAutorotateToLandscapeLeft: 1
40 | useOSAutorotation: 1
41 | use32BitDisplayBuffer: 0
42 | disableDepthAndStencilBuffers: 0
43 | defaultIsFullScreen: 1
44 | defaultIsNativeResolution: 1
45 | runInBackground: 0
46 | captureSingleScreen: 0
47 | Override IPod Music: 0
48 | muteOtherAudioSources: 0
49 | Prepare IOS For Recording: 0
50 | submitAnalytics: 1
51 | usePlayerLog: 1
52 | bakeCollisionMeshes: 0
53 | forceSingleInstance: 0
54 | resizableWindow: 0
55 | useMacAppStoreValidation: 0
56 | gpuSkinning: 0
57 | graphicsJobs: 0
58 | xboxPIXTextureCapture: 0
59 | xboxEnableAvatar: 0
60 | xboxEnableKinect: 0
61 | xboxEnableKinectAutoTracking: 0
62 | xboxEnableFitness: 0
63 | visibleInBackground: 0
64 | allowFullscreenSwitch: 1
65 | macFullscreenMode: 2
66 | d3d9FullscreenMode: 1
67 | d3d11FullscreenMode: 1
68 | xboxSpeechDB: 0
69 | xboxEnableHeadOrientation: 0
70 | xboxEnableGuest: 0
71 | xboxEnablePIXSampling: 0
72 | n3dsDisableStereoscopicView: 0
73 | n3dsEnableSharedListOpt: 1
74 | n3dsEnableVSync: 0
75 | uiUse16BitDepthBuffer: 0
76 | ignoreAlphaClear: 0
77 | xboxOneResolution: 0
78 | xboxOneMonoLoggingLevel: 0
79 | xboxOneLoggingLevel: 1
80 | ps3SplashScreen: {fileID: 0}
81 | videoMemoryForVertexBuffers: 0
82 | psp2PowerMode: 0
83 | psp2AcquireBGM: 1
84 | wiiUTVResolution: 0
85 | wiiUGamePadMSAA: 1
86 | wiiUSupportsNunchuk: 0
87 | wiiUSupportsClassicController: 0
88 | wiiUSupportsBalanceBoard: 0
89 | wiiUSupportsMotionPlus: 0
90 | wiiUSupportsProController: 0
91 | wiiUAllowScreenCapture: 1
92 | wiiUControllerCount: 0
93 | m_SupportedAspectRatios:
94 | 4:3: 1
95 | 5:4: 1
96 | 16:10: 1
97 | 16:9: 1
98 | Others: 1
99 | bundleIdentifier: com.lmd.TestKcp
100 | bundleVersion: 1.0
101 | preloadedAssets: []
102 | metroEnableIndependentInputSource: 0
103 | xboxOneDisableKinectGpuReservation: 0
104 | singlePassStereoRendering: 0
105 | protectGraphicsMemory: 0
106 | AndroidBundleVersionCode: 1
107 | AndroidMinSdkVersion: 15
108 | AndroidPreferredInstallLocation: 1
109 | aotOptions:
110 | apiCompatibilityLevel: 1
111 | stripEngineCode: 1
112 | iPhoneStrippingLevel: 0
113 | iPhoneScriptCallOptimization: 0
114 | iPhoneBuildNumber: 0
115 | ForceInternetPermission: 0
116 | ForceSDCardPermission: 0
117 | CreateWallpaper: 0
118 | APKExpansionFiles: 0
119 | preloadShaders: 0
120 | StripUnusedMeshComponents: 0
121 | VertexChannelCompressionMask:
122 | serializedVersion: 2
123 | m_Bits: 238
124 | iPhoneSdkVersion: 988
125 | iPhoneTargetOSVersion: 24
126 | tvOSSdkVersion: 0
127 | tvOSTargetOSVersion: 900
128 | tvOSRequireExtendedGameController: 0
129 | uIPrerenderedIcon: 0
130 | uIRequiresPersistentWiFi: 0
131 | uIRequiresFullScreen: 1
132 | uIStatusBarHidden: 1
133 | uIExitOnSuspend: 0
134 | uIStatusBarStyle: 0
135 | iPhoneSplashScreen: {fileID: 0}
136 | iPhoneHighResSplashScreen: {fileID: 0}
137 | iPhoneTallHighResSplashScreen: {fileID: 0}
138 | iPhone47inSplashScreen: {fileID: 0}
139 | iPhone55inPortraitSplashScreen: {fileID: 0}
140 | iPhone55inLandscapeSplashScreen: {fileID: 0}
141 | iPadPortraitSplashScreen: {fileID: 0}
142 | iPadHighResPortraitSplashScreen: {fileID: 0}
143 | iPadLandscapeSplashScreen: {fileID: 0}
144 | iPadHighResLandscapeSplashScreen: {fileID: 0}
145 | appleTVSplashScreen: {fileID: 0}
146 | tvOSSmallIconLayers: []
147 | tvOSLargeIconLayers: []
148 | tvOSTopShelfImageLayers: []
149 | tvOSTopShelfImageWideLayers: []
150 | iOSLaunchScreenType: 0
151 | iOSLaunchScreenPortrait: {fileID: 0}
152 | iOSLaunchScreenLandscape: {fileID: 0}
153 | iOSLaunchScreenBackgroundColor:
154 | serializedVersion: 2
155 | rgba: 0
156 | iOSLaunchScreenFillPct: 100
157 | iOSLaunchScreenSize: 100
158 | iOSLaunchScreenCustomXibPath:
159 | iOSLaunchScreeniPadType: 0
160 | iOSLaunchScreeniPadImage: {fileID: 0}
161 | iOSLaunchScreeniPadBackgroundColor:
162 | serializedVersion: 2
163 | rgba: 0
164 | iOSLaunchScreeniPadFillPct: 100
165 | iOSLaunchScreeniPadSize: 100
166 | iOSLaunchScreeniPadCustomXibPath:
167 | iOSDeviceRequirements: []
168 | iOSURLSchemes: []
169 | appleDeveloperTeamID:
170 | iOSManualSigningProvisioningProfileID:
171 | tvOSManualSigningProvisioningProfileID:
172 | appleEnableAutomaticSigning: 0
173 | AndroidTargetDevice: 0
174 | AndroidSplashScreenScale: 0
175 | androidSplashScreen: {fileID: 0}
176 | AndroidKeystoreName:
177 | AndroidKeyaliasName:
178 | AndroidTVCompatibility: 1
179 | AndroidIsGame: 1
180 | androidEnableBanner: 1
181 | m_AndroidBanners:
182 | - width: 320
183 | height: 180
184 | banner: {fileID: 0}
185 | androidGamepadSupportLevel: 0
186 | resolutionDialogBanner: {fileID: 0}
187 | m_BuildTargetIcons:
188 | - m_BuildTarget:
189 | m_Icons:
190 | - serializedVersion: 2
191 | m_Icon: {fileID: 0}
192 | m_Width: 128
193 | m_Height: 128
194 | m_BuildTargetBatching: []
195 | m_BuildTargetGraphicsAPIs: []
196 | webPlayerTemplate: APPLICATION:Default
197 | m_TemplateCustomTags: {}
198 | wiiUTitleID: 0005000011000000
199 | wiiUGroupID: 00010000
200 | wiiUCommonSaveSize: 4096
201 | wiiUAccountSaveSize: 2048
202 | wiiUOlvAccessKey: 0
203 | wiiUTinCode: 0
204 | wiiUJoinGameId: 0
205 | wiiUJoinGameModeMask: 0000000000000000
206 | wiiUCommonBossSize: 0
207 | wiiUAccountBossSize: 0
208 | wiiUAddOnUniqueIDs: []
209 | wiiUMainThreadStackSize: 3072
210 | wiiULoaderThreadStackSize: 1024
211 | wiiUSystemHeapSize: 128
212 | wiiUTVStartupScreen: {fileID: 0}
213 | wiiUGamePadStartupScreen: {fileID: 0}
214 | wiiUDrcBufferDisabled: 0
215 | wiiUProfilerLibPath:
216 | actionOnDotNetUnhandledException: 1
217 | enableInternalProfiler: 0
218 | logObjCUncaughtExceptions: 1
219 | enableCrashReportAPI: 0
220 | cameraUsageDescription:
221 | locationUsageDescription:
222 | microphoneUsageDescription:
223 | XboxTitleId:
224 | XboxImageXexPath:
225 | XboxSpaPath:
226 | XboxGenerateSpa: 0
227 | XboxDeployKinectResources: 0
228 | XboxSplashScreen: {fileID: 0}
229 | xboxEnableSpeech: 0
230 | xboxAdditionalTitleMemorySize: 0
231 | xboxDeployKinectHeadOrientation: 0
232 | xboxDeployKinectHeadPosition: 0
233 | ps3TitleConfigPath:
234 | ps3DLCConfigPath:
235 | ps3ThumbnailPath:
236 | ps3BackgroundPath:
237 | ps3SoundPath:
238 | ps3NPAgeRating: 12
239 | ps3TrophyCommId:
240 | ps3NpCommunicationPassphrase:
241 | ps3TrophyPackagePath:
242 | ps3BootCheckMaxSaveGameSizeKB: 128
243 | ps3TrophyCommSig:
244 | ps3SaveGameSlots: 1
245 | ps3TrialMode: 0
246 | ps3VideoMemoryForAudio: 0
247 | ps3EnableVerboseMemoryStats: 0
248 | ps3UseSPUForUmbra: 0
249 | ps3EnableMoveSupport: 1
250 | ps3DisableDolbyEncoding: 0
251 | ps4NPAgeRating: 12
252 | ps4NPTitleSecret:
253 | ps4NPTrophyPackPath:
254 | ps4ParentalLevel: 1
255 | ps4ContentID: ED1633-NPXX51362_00-0000000000000000
256 | ps4Category: 0
257 | ps4MasterVersion: 01.00
258 | ps4AppVersion: 01.00
259 | ps4AppType: 0
260 | ps4ParamSfxPath:
261 | ps4VideoOutPixelFormat: 0
262 | ps4VideoOutInitialWidth: 1920
263 | ps4VideoOutReprojectionRate: 120
264 | ps4PronunciationXMLPath:
265 | ps4PronunciationSIGPath:
266 | ps4BackgroundImagePath:
267 | ps4StartupImagePath:
268 | ps4SaveDataImagePath:
269 | ps4SdkOverride:
270 | ps4BGMPath:
271 | ps4ShareFilePath:
272 | ps4ShareOverlayImagePath:
273 | ps4PrivacyGuardImagePath:
274 | ps4NPtitleDatPath:
275 | ps4RemotePlayKeyAssignment: -1
276 | ps4RemotePlayKeyMappingDir:
277 | ps4PlayTogetherPlayerCount: 0
278 | ps4EnterButtonAssignment: 1
279 | ps4ApplicationParam1: 0
280 | ps4ApplicationParam2: 0
281 | ps4ApplicationParam3: 0
282 | ps4ApplicationParam4: 0
283 | ps4DownloadDataSize: 0
284 | ps4GarlicHeapSize: 2048
285 | ps4Passcode: frAQBc8Wsa1xVPfvJcrgRYwTiizs2trQ
286 | ps4UseDebugIl2cppLibs: 0
287 | ps4pnSessions: 1
288 | ps4pnPresence: 1
289 | ps4pnFriends: 1
290 | ps4pnGameCustomData: 1
291 | playerPrefsSupport: 0
292 | ps4UseResolutionFallback: 0
293 | restrictedAudioUsageRights: 0
294 | ps4ReprojectionSupport: 0
295 | ps4UseAudio3dBackend: 0
296 | ps4SocialScreenEnabled: 0
297 | ps4ScriptOptimizationLevel: 3
298 | ps4Audio3dVirtualSpeakerCount: 14
299 | ps4attribCpuUsage: 0
300 | ps4PatchPkgPath:
301 | ps4PatchLatestPkgPath:
302 | ps4PatchChangeinfoPath:
303 | ps4PatchDayOne: 0
304 | ps4attribUserManagement: 0
305 | ps4attribMoveSupport: 0
306 | ps4attrib3DSupport: 0
307 | ps4attribShareSupport: 0
308 | ps4attribExclusiveVR: 0
309 | ps4disableAutoHideSplash: 0
310 | ps4videoRecordingFeaturesUsed: 0
311 | ps4contentSearchFeaturesUsed: 0
312 | ps4attribEyeToEyeDistanceSettingVR: 0
313 | ps4IncludedModules: []
314 | monoEnv:
315 | psp2Splashimage: {fileID: 0}
316 | psp2NPTrophyPackPath:
317 | psp2NPSupportGBMorGJP: 0
318 | psp2NPAgeRating: 12
319 | psp2NPTitleDatPath:
320 | psp2NPCommsID:
321 | psp2NPCommunicationsID:
322 | psp2NPCommsPassphrase:
323 | psp2NPCommsSig:
324 | psp2ParamSfxPath:
325 | psp2ManualPath:
326 | psp2LiveAreaGatePath:
327 | psp2LiveAreaBackroundPath:
328 | psp2LiveAreaPath:
329 | psp2LiveAreaTrialPath:
330 | psp2PatchChangeInfoPath:
331 | psp2PatchOriginalPackage:
332 | psp2PackagePassword: F69AzBlax3CF3EDNhm3soLBPh71Yexui
333 | psp2KeystoneFile:
334 | psp2MemoryExpansionMode: 0
335 | psp2DRMType: 0
336 | psp2StorageType: 0
337 | psp2MediaCapacity: 0
338 | psp2DLCConfigPath:
339 | psp2ThumbnailPath:
340 | psp2BackgroundPath:
341 | psp2SoundPath:
342 | psp2TrophyCommId:
343 | psp2TrophyPackagePath:
344 | psp2PackagedResourcesPath:
345 | psp2SaveDataQuota: 10240
346 | psp2ParentalLevel: 1
347 | psp2ShortTitle: Not Set
348 | psp2ContentID: IV0000-ABCD12345_00-0123456789ABCDEF
349 | psp2Category: 0
350 | psp2MasterVersion: 01.00
351 | psp2AppVersion: 01.00
352 | psp2TVBootMode: 0
353 | psp2EnterButtonAssignment: 2
354 | psp2TVDisableEmu: 0
355 | psp2AllowTwitterDialog: 1
356 | psp2Upgradable: 0
357 | psp2HealthWarning: 0
358 | psp2UseLibLocation: 0
359 | psp2InfoBarOnStartup: 0
360 | psp2InfoBarColor: 0
361 | psp2UseDebugIl2cppLibs: 0
362 | psmSplashimage: {fileID: 0}
363 | spritePackerPolicy:
364 | scriptingDefineSymbols: {}
365 | metroPackageName: TestKcp
366 | metroPackageVersion:
367 | metroCertificatePath:
368 | metroCertificatePassword:
369 | metroCertificateSubject:
370 | metroCertificateIssuer:
371 | metroCertificateNotAfter: 0000000000000000
372 | metroApplicationDescription: TestKcp
373 | wsaImages: {}
374 | metroTileShortName:
375 | metroCommandLineArgsFile:
376 | metroTileShowName: 0
377 | metroMediumTileShowName: 0
378 | metroLargeTileShowName: 0
379 | metroWideTileShowName: 0
380 | metroDefaultTileSize: 1
381 | metroTileForegroundText: 1
382 | metroTileBackgroundColor: {r: 0.13333334, g: 0.17254902, b: 0.21568628, a: 0}
383 | metroSplashScreenBackgroundColor: {r: 0.12941177, g: 0.17254902, b: 0.21568628,
384 | a: 1}
385 | metroSplashScreenUseBackgroundColor: 0
386 | platformCapabilities: {}
387 | metroFTAName:
388 | metroFTAFileTypes: []
389 | metroProtocolName:
390 | metroCompilationOverrides: 1
391 | tizenProductDescription:
392 | tizenProductURL:
393 | tizenSigningProfileName:
394 | tizenGPSPermissions: 0
395 | tizenMicrophonePermissions: 0
396 | tizenMinOSVersion: 0
397 | n3dsUseExtSaveData: 0
398 | n3dsCompressStaticMem: 1
399 | n3dsExtSaveDataNumber: 0x12345
400 | n3dsStackSize: 131072
401 | n3dsTargetPlatform: 2
402 | n3dsRegion: 7
403 | n3dsMediaSize: 0
404 | n3dsLogoStyle: 3
405 | n3dsTitle: GameName
406 | n3dsProductCode:
407 | n3dsApplicationId: 0xFF3FF
408 | stvDeviceAddress:
409 | stvProductDescription:
410 | stvProductAuthor:
411 | stvProductAuthorEmail:
412 | stvProductLink:
413 | stvProductCategory: 0
414 | XboxOneProductId:
415 | XboxOneUpdateKey:
416 | XboxOneSandboxId:
417 | XboxOneContentId:
418 | XboxOneTitleId:
419 | XboxOneSCId:
420 | XboxOneGameOsOverridePath:
421 | XboxOnePackagingOverridePath:
422 | XboxOneAppManifestOverridePath:
423 | XboxOnePackageEncryption: 0
424 | XboxOnePackageUpdateGranularity: 2
425 | XboxOneDescription:
426 | XboxOneIsContentPackage: 0
427 | XboxOneEnableGPUVariability: 0
428 | XboxOneSockets: {}
429 | XboxOneSplashScreen: {fileID: 0}
430 | XboxOneAllowedProductIds: []
431 | XboxOnePersistentLocalStorageSize: 0
432 | intPropertyNames:
433 | - Android::ScriptingBackend
434 | - Standalone::ScriptingBackend
435 | - WebPlayer::ScriptingBackend
436 | - iOS::Architecture
437 | - iOS::ScriptingBackend
438 | Android::ScriptingBackend: 0
439 | Standalone::ScriptingBackend: 0
440 | WebPlayer::ScriptingBackend: 0
441 | iOS::Architecture: 2
442 | iOS::ScriptingBackend: 1
443 | boolPropertyNames:
444 | - Android::VR::enable
445 | - Metro::VR::enable
446 | - N3DS::VR::enable
447 | - PS3::VR::enable
448 | - PS4::VR::enable
449 | - PSM::VR::enable
450 | - PSP2::VR::enable
451 | - SamsungTV::VR::enable
452 | - Standalone::VR::enable
453 | - Tizen::VR::enable
454 | - WebGL::VR::enable
455 | - WebPlayer::VR::enable
456 | - WiiU::VR::enable
457 | - Xbox360::VR::enable
458 | - XboxOne::VR::enable
459 | - XboxOne::enus
460 | - iOS::VR::enable
461 | - tvOS::VR::enable
462 | Android::VR::enable: 0
463 | Metro::VR::enable: 0
464 | N3DS::VR::enable: 0
465 | PS3::VR::enable: 0
466 | PS4::VR::enable: 0
467 | PSM::VR::enable: 0
468 | PSP2::VR::enable: 0
469 | SamsungTV::VR::enable: 0
470 | Standalone::VR::enable: 0
471 | Tizen::VR::enable: 0
472 | WebGL::VR::enable: 0
473 | WebPlayer::VR::enable: 0
474 | WiiU::VR::enable: 0
475 | Xbox360::VR::enable: 0
476 | XboxOne::VR::enable: 0
477 | XboxOne::enus: 1
478 | iOS::VR::enable: 0
479 | tvOS::VR::enable: 0
480 | stringPropertyNames:
481 | - Analytics_ServiceEnabled::Analytics_ServiceEnabled
482 | - Build_ServiceEnabled::Build_ServiceEnabled
483 | - Collab_ServiceEnabled::Collab_ServiceEnabled
484 | - ErrorHub_ServiceEnabled::ErrorHub_ServiceEnabled
485 | - Game_Performance_ServiceEnabled::Game_Performance_ServiceEnabled
486 | - Hub_ServiceEnabled::Hub_ServiceEnabled
487 | - Purchasing_ServiceEnabled::Purchasing_ServiceEnabled
488 | - UNet_ServiceEnabled::UNet_ServiceEnabled
489 | - Unity_Ads_ServiceEnabled::Unity_Ads_ServiceEnabled
490 | Analytics_ServiceEnabled::Analytics_ServiceEnabled: False
491 | Build_ServiceEnabled::Build_ServiceEnabled: False
492 | Collab_ServiceEnabled::Collab_ServiceEnabled: False
493 | ErrorHub_ServiceEnabled::ErrorHub_ServiceEnabled: False
494 | Game_Performance_ServiceEnabled::Game_Performance_ServiceEnabled: False
495 | Hub_ServiceEnabled::Hub_ServiceEnabled: False
496 | Purchasing_ServiceEnabled::Purchasing_ServiceEnabled: False
497 | UNet_ServiceEnabled::UNet_ServiceEnabled: True
498 | Unity_Ads_ServiceEnabled::Unity_Ads_ServiceEnabled: False
499 | vectorPropertyNames:
500 | - Android::VR::enabledDevices
501 | - Metro::VR::enabledDevices
502 | - N3DS::VR::enabledDevices
503 | - PS3::VR::enabledDevices
504 | - PS4::VR::enabledDevices
505 | - PSM::VR::enabledDevices
506 | - PSP2::VR::enabledDevices
507 | - SamsungTV::VR::enabledDevices
508 | - Standalone::VR::enabledDevices
509 | - Tizen::VR::enabledDevices
510 | - WebGL::VR::enabledDevices
511 | - WebPlayer::VR::enabledDevices
512 | - WiiU::VR::enabledDevices
513 | - Xbox360::VR::enabledDevices
514 | - XboxOne::VR::enabledDevices
515 | - iOS::VR::enabledDevices
516 | - tvOS::VR::enabledDevices
517 | Android::VR::enabledDevices:
518 | - Oculus
519 | Metro::VR::enabledDevices: []
520 | N3DS::VR::enabledDevices: []
521 | PS3::VR::enabledDevices: []
522 | PS4::VR::enabledDevices:
523 | - PlayStationVR
524 | PSM::VR::enabledDevices: []
525 | PSP2::VR::enabledDevices: []
526 | SamsungTV::VR::enabledDevices: []
527 | Standalone::VR::enabledDevices:
528 | - Oculus
529 | Tizen::VR::enabledDevices: []
530 | WebGL::VR::enabledDevices: []
531 | WebPlayer::VR::enabledDevices: []
532 | WiiU::VR::enabledDevices: []
533 | Xbox360::VR::enabledDevices: []
534 | XboxOne::VR::enabledDevices: []
535 | iOS::VR::enabledDevices: []
536 | tvOS::VR::enabledDevices: []
537 | cloudProjectId: 36ef6255-0a57-44d5-896e-4e8650c7abf9
538 | projectName: TestKcp
539 | organizationId: lemanduo
540 | cloudEnabled: 0
541 |
--------------------------------------------------------------------------------
/Assets/Plugins/kcpForUnity/common/kcp.cs:
--------------------------------------------------------------------------------
1 | using System;
2 | using System.Collections;
3 | using System.Collections.Generic;
4 | using System.Linq;
5 | using System.Text;
6 |
7 | /**
8 | * KCP - A Better ARQ Protocol Implementation
9 | * skywind3000 (at) gmail.com, 2010-2011
10 | * Features:
11 | * + Average RTT reduce 30% - 40% vs traditional ARQ like tcp.
12 | * + Maximum RTT reduce three times vs tcp.
13 | * + Lightweight, distributed as a single source file.
14 | */
15 | public class Kcp
16 | {
17 |
18 | public const int IKCP_RTO_NDL = 30; // no delay min rto
19 | public const int IKCP_RTO_MIN = 100; // normal min rto
20 | public const int IKCP_RTO_DEF = 200;
21 | public const int IKCP_RTO_MAX = 60000;
22 | public const int IKCP_CMD_PUSH = 81; // cmd: push data
23 | public const int IKCP_CMD_ACK = 82; // cmd: ack
24 | public const int IKCP_CMD_WASK = 83; // cmd: window probe (ask)
25 | public const int IKCP_CMD_WINS = 84; // cmd: window size (tell)
26 | public const int IKCP_ASK_SEND = 1; // need to send IKCP_CMD_WASK
27 | public const int IKCP_ASK_TELL = 2; // need to send IKCP_CMD_WINS
28 | public const int IKCP_WND_SND = 32;
29 | public const int IKCP_WND_RCV = 32;
30 | public const int IKCP_MTU_DEF = 1400;
31 | public const int IKCP_ACK_FAST = 3;
32 | public const int IKCP_INTERVAL = 100;
33 | public const int IKCP_OVERHEAD = 24;
34 | public const int IKCP_DEADLINK = 10;
35 | public const int IKCP_THRESH_INIT = 2;
36 | public const int IKCP_THRESH_MIN = 2;
37 | public const int IKCP_PROBE_INIT = 7000; // 7 secs to probe window size
38 | public const int IKCP_PROBE_LIMIT = 120000; // up to 120 secs to probe window
39 |
40 | private int conv;
41 | private int mtu;
42 | private int mss;
43 | private int state;
44 | private int snd_una;
45 | private int snd_nxt;
46 | private int rcv_nxt;
47 | private int ts_recent;
48 | private int ts_lastack;
49 | private int ssthresh;
50 | private int rx_rttval;
51 | private int rx_srtt;
52 | private int rx_rto;
53 | private int rx_minrto;
54 | private int snd_wnd;
55 | private int rcv_wnd;
56 | private int rmt_wnd;
57 | private int cwnd;
58 | private int probe;
59 | private int current;
60 | private int interval;
61 | private int ts_flush;
62 | private int xmit;
63 | private int nodelay;
64 | private int updated;
65 | private int ts_probe;
66 | private int probe_wait;
67 | private int dead_link;
68 | private int incr;
69 | private List snd_queue = new List();
70 | private List rcv_queue = new List();
71 | private List snd_buf = new List();
72 | private List rcv_buf = new List();
73 | private Func segNewFunc;
74 | private Action segDeleteFunc;
75 | private List acklist = new List();
76 | private ByteBuf buffer;
77 | private int fastresend;
78 | private int nocwnd;
79 | private bool stream;
80 | private int logmask;
81 | private Action outputFunc;
82 | private int nextUpdate;//the next update time.
83 |
84 | private static int _ibound_(int lower, int middle, int upper)
85 | {
86 | return Math.Min(Math.Max(lower, middle), upper);
87 | }
88 |
89 | private static int _itimediff(int later, int earlier)
90 | {
91 | return later - earlier;
92 | }
93 |
94 | /**
95 | * SEGMENT
96 | */
97 | public class Segment
98 | {
99 |
100 | public int conv = 0;
101 | public byte cmd = 0;
102 | public int frg = 0;
103 | public int wnd = 0;
104 | public int ts = 0;
105 | public int sn = 0;
106 | public int una = 0;
107 | public int resendts = 0;
108 | public int rto = 0;
109 | public int fastack = 0;
110 | public int xmit = 0;
111 | public ByteBuf data;
112 | public Segment()
113 | {
114 | data = new ByteBuf();
115 | }
116 | public Segment(int size) : this()
117 | {
118 | if (size > 0)
119 | {
120 | this.data.EnsureCapacity(size);
121 | }
122 | }
123 | public void Reset()
124 | {
125 | conv = 0;
126 | cmd = 0;
127 | frg = 0;
128 | wnd = 0;
129 | ts = 0;
130 | sn = 0;
131 | una = 0;
132 | resendts = 0;
133 | rto = 0;
134 | fastack = 0;
135 | xmit = 0;
136 | data.Clear();
137 | }
138 | /**
139 | * encode a segment into buffer
140 | *
141 | * @param buf
142 | * @param offset
143 | * @return
144 | */
145 | public int Encode(ByteBuf buf)
146 | {
147 | int off = buf.WritePos;
148 | buf.WriteInt32(conv);
149 | buf.WriteByte(cmd);
150 | buf.WriteByte((byte)frg);
151 | buf.WriteInt16((short)wnd);
152 | buf.WriteInt32(ts);
153 | buf.WriteInt32(sn);
154 | buf.WriteInt32(una);
155 | buf.WriteInt32(data == null ? 0 : data.Size);
156 | return buf.WritePos - off;
157 | }
158 | }
159 |
160 | /**
161 | * create a new kcpcb
162 | *
163 | * @param conv
164 | * @param output
165 | * @param user
166 | */
167 | public Kcp(int conv, Action output)
168 | {
169 | this.conv = conv;
170 | snd_wnd = IKCP_WND_SND;
171 | rcv_wnd = IKCP_WND_RCV;
172 | rmt_wnd = IKCP_WND_RCV;
173 | mtu = IKCP_MTU_DEF;
174 | mss = mtu - IKCP_OVERHEAD;
175 | rx_rto = IKCP_RTO_DEF;
176 | rx_minrto = IKCP_RTO_MIN;
177 | interval = IKCP_INTERVAL;
178 | ts_flush = IKCP_INTERVAL;
179 | ssthresh = IKCP_THRESH_INIT;
180 | dead_link = IKCP_DEADLINK;
181 | rcv_nxt = 0;
182 | buffer = new ByteBuf((mtu + IKCP_OVERHEAD) * 3);
183 | this.outputFunc = output;
184 | }
185 |
186 | /**
187 | * check the size of next message in the recv queue
188 | *
189 | * @return
190 | */
191 | public int PeekSize()
192 | {
193 | if (rcv_queue.Count <= 0)
194 | {
195 | return -1;
196 | }
197 | Segment seq = rcv_queue.First();
198 | if (seq.frg == 0)
199 | {
200 | return seq.data.Size;
201 | }
202 | if (rcv_queue.Count < seq.frg + 1)
203 | {
204 | return -1;
205 | }
206 | int length = 0;
207 | for (int i = 0; i < rcv_queue.Count; i++)
208 | {
209 | Segment item = rcv_queue[i];
210 | length += item.data.Size;
211 | if (item.frg == 0)
212 | {
213 | break;
214 | }
215 | }
216 | return length;
217 | }
218 |
219 | /**
220 | * user/upper level recv: returns size, returns below zero for EAGAIN
221 | *
222 | * @param buffer
223 | * @return
224 | */
225 | public int Receive(ByteBuf buffer)
226 | {
227 | if (rcv_queue.Count <= 0)
228 | {
229 | return -1;
230 | }
231 | int peekSize = PeekSize();
232 | if (peekSize < 0)
233 | {
234 | return -2;
235 | }
236 | bool recover = rcv_queue.Count >= rcv_wnd;
237 | // merge fragment.
238 | int c = 0;
239 | int len = 0;
240 | for (int i = 0; i < rcv_queue.Count; i++)
241 | {
242 | Segment seg = rcv_queue[i];
243 | len += seg.data.Size;
244 | buffer.WriteBytesFrom(seg.data);
245 | c++;
246 | if (seg.frg == 0)
247 | {
248 | break;
249 | }
250 | }
251 | if (c > 0)
252 | {
253 | for (int i = 0; i < c; i++)
254 | {
255 | SegmentDelete(rcv_queue[i]);
256 | }
257 | rcv_queue.RemoveRange(0, c);
258 | }
259 | if (len != peekSize)
260 | {
261 | throw new Exception("数据异常.");
262 | }
263 | // move available data from rcv_buf -> rcv_queue
264 | c = 0;
265 | for (int i = 0; i < rcv_buf.Count; i++)
266 | {
267 | Segment seg = rcv_buf[i];
268 | if (seg.sn == rcv_nxt && rcv_queue.Count < rcv_wnd)
269 | {
270 | rcv_queue.Add(seg);
271 | rcv_nxt++;
272 | c++;
273 | }
274 | else
275 | {
276 | break;
277 | }
278 | }
279 | if (c > 0)
280 | rcv_buf.RemoveRange(0, c);
281 | // fast recover
282 | if (rcv_queue.Count < rcv_wnd && recover)
283 | {
284 | // ready to send back IKCP_CMD_WINS in ikcp_flush
285 | // tell remote my window size
286 | probe |= IKCP_ASK_TELL;
287 | }
288 | return len;
289 | }
290 | private Segment SegmentNew(int size)
291 | {
292 | Segment seg = null;
293 | if (segNewFunc == null)
294 | {
295 | seg = new Segment(size);
296 | }
297 | else
298 | {
299 | seg = segNewFunc();
300 | seg.data.EnsureCapacity(size);
301 | }
302 | return seg;
303 | }
304 | private void SegmentDelete(Segment seg)
305 | {
306 | seg.Reset();
307 | if (segDeleteFunc != null)
308 | {
309 | segDeleteFunc(seg);
310 | }
311 | }
312 | public void SetSegmentHook(Func segNew, Action segDel)
313 | {
314 | segNewFunc = segNew;
315 | segDeleteFunc = segDel;
316 | }
317 | public int Send(byte[] buff)
318 | {
319 | return Send(new ByteBuf(buff));
320 | }
321 | /**
322 | * user/upper level send, returns below zero for error
323 | *
324 | * @param buffer
325 | * @return
326 | */
327 | public int Send(ByteBuf buffer)
328 | {
329 | if (buffer.Size == 0)
330 | {
331 | return -1;
332 | }
333 | // append to previous segment in streaming mode (if possible)
334 | if (this.stream && this.snd_queue.Count > 0)
335 | {
336 | Segment seg = snd_queue.Last();
337 | if (seg.data != null && seg.data.Size < mss)
338 | {
339 | int capacity = mss - seg.data.Size;
340 | int extend = (buffer.Size < capacity) ? buffer.Size : capacity;
341 | seg.data.WriteBytesFrom(buffer, extend);
342 | SegmentDelete(seg);
343 | if (buffer.Size == 0)
344 | {
345 | return 0;
346 | }
347 | }
348 | }
349 | int count;
350 | if (buffer.Size <= mss)
351 | {
352 | count = 1;
353 | }
354 | else
355 | {
356 | count = (buffer.Size + mss - 1) / mss;
357 | }
358 | if (count > 255)
359 | {
360 | return -2;
361 | }
362 | if (count == 0)
363 | {
364 | count = 1;
365 | }
366 | //fragment
367 | for (int i = 0; i < count; i++)
368 | {
369 | int size = buffer.Size > mss ? mss : buffer.Size;
370 | Segment seg = SegmentNew(size);
371 | seg.data.WriteBytesFrom(buffer, size);
372 | seg.frg = this.stream ? 0 : count - i - 1;
373 | snd_queue.Add(seg);
374 | }
375 | return 0;
376 | }
377 |
378 | /**
379 | * update ack.
380 | *
381 | * @param rtt
382 | */
383 | private void Update_ack(int rtt)
384 | {
385 | if (rx_srtt == 0)
386 | {
387 | rx_srtt = rtt;
388 | rx_rttval = rtt / 2;
389 | }
390 | else
391 | {
392 | int delta = rtt - rx_srtt;
393 | if (delta < 0)
394 | {
395 | delta = -delta;
396 | }
397 | rx_rttval = (3 * rx_rttval + delta) / 4;
398 | rx_srtt = (7 * rx_srtt + rtt) / 8;
399 | if (rx_srtt < 1)
400 | {
401 | rx_srtt = 1;
402 | }
403 | }
404 | int rto = rx_srtt + Math.Max(interval, 4 * rx_rttval);
405 | rx_rto = _ibound_(rx_minrto, rto, IKCP_RTO_MAX);
406 | }
407 |
408 | private void Shrink_buf()
409 | {
410 | if (snd_buf.Count > 0)
411 | {
412 | snd_una = snd_buf.First().sn;
413 | }
414 | else
415 | {
416 | snd_una = snd_nxt;
417 | }
418 | }
419 |
420 | private void Parse_ack(int sn)
421 | {
422 | if (_itimediff(sn, snd_una) < 0 || _itimediff(sn, snd_nxt) >= 0)
423 | {
424 | return;
425 | }
426 | for (int i = 0; i < snd_buf.Count; i++)
427 | {
428 | Segment seg = snd_buf[i];
429 | if (sn == seg.sn)
430 | {
431 | snd_buf.RemoveAt(i);
432 | SegmentDelete(seg);
433 | break;
434 | }
435 | if (_itimediff(sn, seg.sn) < 0)
436 | {
437 | break;
438 | }
439 | }
440 | }
441 |
442 | private void Parse_una(int una)
443 | {
444 | int c = 0;
445 | for (int i = 0; i < snd_buf.Count; i++)
446 | {
447 | Segment seg = snd_buf[i];
448 | if (_itimediff(una, seg.sn) > 0)
449 | {
450 | c++;
451 | }
452 | else
453 | {
454 | break;
455 | }
456 | }
457 | if (c > 0)
458 | {
459 | for (int i = 0; i < c; i++)
460 | {
461 | SegmentDelete(snd_buf[i]);
462 | }
463 | snd_buf.RemoveRange(0, c);
464 | }
465 | }
466 |
467 | private void Parse_fastack(int sn)
468 | {
469 | if (_itimediff(sn, snd_una) < 0 || _itimediff(sn, snd_nxt) >= 0)
470 | {
471 | return;
472 | }
473 | for (int i = 0; i < snd_buf.Count; i++)
474 | {
475 | Segment seg = snd_buf[i];
476 | if (_itimediff(sn, seg.sn) < 0)
477 | {
478 | break;
479 | }
480 | else if (sn != seg.sn)
481 | {
482 | seg.fastack++;
483 | }
484 | }
485 | }
486 |
487 | /**
488 | * ack append
489 | *
490 | * @param sn
491 | * @param ts
492 | */
493 | private void Ack_push(int sn, int ts)
494 | {
495 | acklist.Add(sn);
496 | acklist.Add(ts);
497 | }
498 |
499 | private void Parse_data(Segment newseg)
500 | {
501 | int sn = newseg.sn;
502 | if (_itimediff(sn, rcv_nxt + rcv_wnd) >= 0 || _itimediff(sn, rcv_nxt) < 0)
503 | {
504 | SegmentDelete(newseg);
505 | return;
506 | }
507 | int n = rcv_buf.Count - 1;
508 | int temp = -1;
509 | bool repeat = false;
510 | for (int i = n; i >= 0; i--)
511 | {
512 | Segment seg = rcv_buf[i];
513 | if (seg.sn == sn)
514 | {
515 | repeat = true;
516 | break;
517 | }
518 | if (_itimediff(sn, seg.sn) > 0)
519 | {
520 | temp = i;
521 | break;
522 | }
523 | }
524 | if (!repeat)
525 | {
526 | if (temp == -1)
527 | {
528 | rcv_buf.Insert(0, newseg);
529 | }
530 | else
531 | {
532 | rcv_buf.Insert(temp + 1, newseg);
533 | }
534 | }
535 | else
536 | {
537 | SegmentDelete(newseg);
538 | }
539 | // move available data from rcv_buf -> rcv_queue
540 | int c = 0;
541 | for (int i = 0; i < rcv_buf.Count; i++)
542 | {
543 | Segment seg = rcv_buf[i];
544 | if (seg.sn == rcv_nxt && rcv_queue.Count < rcv_wnd)
545 | {
546 | rcv_queue.Add(seg);
547 | rcv_nxt++;
548 | c++;
549 | }
550 | else
551 | {
552 | break;
553 | }
554 | }
555 | if (c > 0)
556 | {
557 | rcv_buf.RemoveRange(0, c);
558 | }
559 | }
560 |
561 | /**
562 | *
563 | * when you received a low level packet (eg. UDP packet), call it
564 | *
565 | * @param data
566 | * @return
567 | */
568 | public int Input(ByteBuf data)
569 | {
570 | int una_temp = snd_una;
571 | int flag = 0, maxack = 0;
572 | if (data == null || data.Size < IKCP_OVERHEAD)
573 | {
574 | return -1;
575 | }
576 | while (true)
577 | {
578 | bool readed = false;
579 | int ts;
580 | int sn;
581 | int len;
582 | int una;
583 | int conv_;
584 | int wnd;
585 | byte cmd;
586 | byte frg;
587 | if (data.Size < IKCP_OVERHEAD)
588 | {
589 | break;
590 | }
591 | conv_ = data.ReadInt32();
592 | if (this.conv != conv_)
593 | {
594 | return -1;
595 | }
596 | cmd = data.ReadByte();
597 | frg = data.ReadByte();
598 | wnd = data.ReadInt16();
599 | ts = data.ReadInt32();
600 | sn = data.ReadInt32();
601 | una = data.ReadInt32();
602 | len = data.ReadInt32();
603 | if (data.Size < len)
604 | {
605 | return -2;
606 | }
607 | switch ((int)cmd)
608 | {
609 | case IKCP_CMD_PUSH:
610 | case IKCP_CMD_ACK:
611 | case IKCP_CMD_WASK:
612 | case IKCP_CMD_WINS:
613 | break;
614 | default:
615 | return -3;
616 | }
617 | rmt_wnd = wnd & 0x0000ffff;
618 | Parse_una(una);
619 | Shrink_buf();
620 | switch (cmd)
621 | {
622 | case IKCP_CMD_ACK:
623 | if (_itimediff(current, ts) >= 0)
624 | {
625 | Update_ack(_itimediff(current, ts));
626 | }
627 | Parse_ack(sn);
628 | Shrink_buf();
629 | if (flag == 0)
630 | {
631 | flag = 1;
632 | maxack = sn;
633 | }
634 | else if (_itimediff(sn, maxack) > 0)
635 | {
636 | maxack = sn;
637 | }
638 | break;
639 | case IKCP_CMD_PUSH:
640 | if (_itimediff(sn, rcv_nxt + rcv_wnd) < 0)
641 | {
642 | Ack_push(sn, ts);
643 | if (_itimediff(sn, rcv_nxt) >= 0)
644 | {
645 | Segment seg = SegmentNew(len);
646 | seg.conv = conv_;
647 | seg.cmd = cmd;
648 | seg.frg = frg & 0x000000ff;
649 | seg.wnd = wnd;
650 | seg.ts = ts;
651 | seg.sn = sn;
652 | seg.una = una;
653 | if (len > 0)
654 | {
655 | seg.data.WriteBytesFrom(data, len);
656 | readed = true;
657 | }
658 | Parse_data(seg);
659 | }
660 | }
661 | break;
662 | case IKCP_CMD_WASK:
663 | // ready to send back IKCP_CMD_WINS in Ikcp_flush
664 | // tell remote my window size
665 | probe |= IKCP_ASK_TELL;
666 | break;
667 | case IKCP_CMD_WINS:
668 | // do nothing
669 | break;
670 | default:
671 | return -3;
672 | }
673 | if (!readed)
674 | {
675 | data.SkipBytes(len);
676 | }
677 | }
678 | if (flag != 0)
679 | {
680 | Parse_fastack(maxack);
681 | }
682 | if (_itimediff(snd_una, una_temp) > 0)
683 | {
684 | if (this.cwnd < this.rmt_wnd)
685 | {
686 | if (this.cwnd < this.ssthresh)
687 | {
688 | this.cwnd++;
689 | this.incr += mss;
690 | }
691 | else
692 | {
693 | if (this.incr < mss)
694 | {
695 | this.incr = mss;
696 | }
697 | this.incr += (mss * mss) / this.incr + (mss / 16);
698 | if ((this.cwnd + 1) * mss <= this.incr)
699 | {
700 | this.cwnd++;
701 | }
702 | }
703 | if (this.cwnd > this.rmt_wnd)
704 | {
705 | this.cwnd = this.rmt_wnd;
706 | this.incr = this.rmt_wnd * mss;
707 | }
708 | }
709 | }
710 | return 0;
711 | }
712 |
713 | private int wnd_unused()
714 | {
715 | if (rcv_queue.Count < rcv_wnd)
716 | {
717 | return rcv_wnd - rcv_queue.Count;
718 | }
719 | return 0;
720 | }
721 | public void Flush(int cur)
722 | {
723 | updated = 1;
724 | current = cur;
725 | Flush();
726 | }
727 | private void Output(ByteBuf buf)
728 | {
729 | outputFunc(buf);
730 | buf.Clear();
731 | }
732 | /**
733 | * flush pending data
734 | */
735 | private void Flush()
736 | {
737 | int cur = current;
738 | int change = 0;
739 | int lost = 0;
740 | if (updated == 0)
741 | {
742 | return;
743 | }
744 | Segment seg = new Segment(0);
745 | seg.conv = conv;
746 | seg.cmd = IKCP_CMD_ACK;
747 | seg.wnd = wnd_unused();
748 | seg.una = rcv_nxt;
749 | // flush acknowledges
750 | int c = acklist.Count / 2;
751 | for (int i = 0; i < c; i++)
752 | {
753 | if (buffer.Size + IKCP_OVERHEAD > mtu)
754 | {
755 | this.Output(buffer);
756 | }
757 | seg.sn = acklist[i * 2 + 0];
758 | seg.ts = acklist[i * 2 + 1];
759 | seg.Encode(buffer);
760 | }
761 | acklist.Clear();
762 | // probe window size (if remote window size equals zero)
763 | if (rmt_wnd == 0)
764 | {
765 | if (probe_wait == 0)
766 | {
767 | probe_wait = IKCP_PROBE_INIT;
768 | ts_probe = current + probe_wait;
769 | }
770 | else if (_itimediff(current, ts_probe) >= 0)
771 | {
772 | if (probe_wait < IKCP_PROBE_INIT)
773 | {
774 | probe_wait = IKCP_PROBE_INIT;
775 | }
776 | probe_wait += probe_wait / 2;
777 | if (probe_wait > IKCP_PROBE_LIMIT)
778 | {
779 | probe_wait = IKCP_PROBE_LIMIT;
780 | }
781 | ts_probe = current + probe_wait;
782 | probe |= IKCP_ASK_SEND;
783 | }
784 | }
785 | else
786 | {
787 | ts_probe = 0;
788 | probe_wait = 0;
789 | }
790 | // flush window probing commands
791 | if ((probe & IKCP_ASK_SEND) != 0)
792 | {
793 | seg.cmd = IKCP_CMD_WASK;
794 | if (buffer.Size + IKCP_OVERHEAD > mtu)
795 | {
796 | this.Output(buffer);
797 | }
798 | seg.Encode(buffer);
799 | }
800 | // flush window probing commands
801 | if ((probe & IKCP_ASK_TELL) != 0)
802 | {
803 | seg.cmd = IKCP_CMD_WINS;
804 | if (buffer.Size + IKCP_OVERHEAD > mtu)
805 | {
806 | this.Output(buffer);
807 | }
808 | seg.Encode(buffer);
809 | }
810 | probe = 0;
811 | // calculate window size
812 | int cwnd_temp = Math.Min(snd_wnd, rmt_wnd);
813 | if (nocwnd == 0)
814 | {
815 | cwnd_temp = Math.Min(cwnd, cwnd_temp);
816 | }
817 | // move data from snd_queue to snd_buf
818 | c = 0;
819 | for (int i = 0; i < snd_queue.Count; i++)
820 | {
821 | Segment item = snd_queue[i];
822 | if (_itimediff(snd_nxt, snd_una + cwnd_temp) >= 0)
823 | {
824 | break;
825 | }
826 | Segment newseg = item;
827 | newseg.conv = conv;
828 | newseg.cmd = IKCP_CMD_PUSH;
829 | newseg.wnd = seg.wnd;
830 | newseg.ts = cur;
831 | newseg.sn = snd_nxt++;
832 | newseg.una = rcv_nxt;
833 | newseg.resendts = cur;
834 | newseg.rto = rx_rto;
835 | newseg.fastack = 0;
836 | newseg.xmit = 0;
837 | snd_buf.Add(newseg);
838 | c++;
839 | }
840 | if (c > 0)
841 | {
842 | snd_queue.RemoveRange(0, c);
843 | }
844 | // calculate resent
845 | int resent = (fastresend > 0) ? fastresend : int.MaxValue;
846 | int rtomin = (nodelay == 0) ? (rx_rto >> 3) : 0;
847 | // flush data segments
848 | for (int i = 0; i < snd_buf.Count; i++)
849 | {
850 | Segment segment = snd_buf[i];
851 | bool needsend = false;
852 | if (segment.xmit == 0)
853 | {
854 | needsend = true;
855 | segment.xmit++;
856 | segment.rto = rx_rto;
857 | segment.resendts = cur + segment.rto + rtomin;
858 | }
859 | else if (_itimediff(cur, segment.resendts) >= 0)
860 | {
861 | needsend = true;
862 | segment.xmit++;
863 | xmit++;
864 | if (nodelay == 0)
865 | {
866 | segment.rto += rx_rto;
867 | }
868 | else
869 | {
870 | segment.rto += rx_rto / 2;
871 | }
872 | segment.resendts = cur + segment.rto;
873 | lost = 1;
874 | }
875 | else if (segment.fastack >= resent)
876 | {
877 | needsend = true;
878 | segment.xmit++;
879 | segment.fastack = 0;
880 | segment.resendts = cur + segment.rto;
881 | change++;
882 | }
883 | if (needsend)
884 | {
885 | segment.ts = cur;
886 | segment.wnd = seg.wnd;
887 | segment.una = rcv_nxt;
888 | int need = IKCP_OVERHEAD + segment.data.Size;
889 | if (buffer.Size + need > mtu)
890 | {
891 | this.Output(buffer);
892 | }
893 | segment.Encode(buffer);
894 | if (segment.data.Size > 0)
895 | {
896 | buffer.WriteBytesFrom(segment.data);
897 | }
898 | if (segment.xmit >= dead_link)
899 | {
900 | state = -1;
901 | }
902 | }
903 | }
904 | // flash remain segments
905 | if (buffer.Size > 0)
906 | {
907 | this.Output(buffer);
908 | }
909 | // update ssthresh
910 | if (change != 0)
911 | {
912 | int inflight = snd_nxt - snd_una;
913 | ssthresh = inflight / 2;
914 | if (ssthresh < IKCP_THRESH_MIN)
915 | {
916 | ssthresh = IKCP_THRESH_MIN;
917 | }
918 | cwnd = ssthresh + resent;
919 | incr = cwnd * mss;
920 | }
921 | if (lost != 0)
922 | {
923 | ssthresh = cwnd / 2;
924 | if (ssthresh < IKCP_THRESH_MIN)
925 | {
926 | ssthresh = IKCP_THRESH_MIN;
927 | }
928 | cwnd = 1;
929 | incr = mss;
930 | }
931 | if (cwnd < 1)
932 | {
933 | cwnd = 1;
934 | incr = mss;
935 | }
936 | }
937 |
938 | /**
939 | * update state (call it repeatedly, every 10ms-100ms), or you can ask
940 | * ikcp_check when to call it again (without ikcp_input/_send calling).
941 | *
942 | * @param current current timestamp in millisec.
943 | */
944 | public void Update(long current)
945 | {
946 | this.current = (int)current;
947 | if (updated == 0)
948 | {
949 | updated = 1;
950 | ts_flush = this.current;
951 | }
952 | int slap = _itimediff(this.current, ts_flush);
953 | if (slap >= 10000 || slap < -10000)
954 | {
955 | ts_flush = this.current;
956 | slap = 0;
957 | }
958 | if (slap >= 0)
959 | {
960 | ts_flush += interval;
961 | if (_itimediff(this.current, ts_flush) >= 0)
962 | {
963 | ts_flush = this.current + interval;
964 | }
965 | Flush();
966 | }
967 | }
968 |
969 | /**
970 | * Determine when should you invoke ikcp_update: returns when you should
971 | * invoke ikcp_update in millisec, if there is no ikcp_input/_send calling.
972 | * you can call ikcp_update in that time, instead of call update repeatly.
973 | * Important to reduce unnacessary ikcp_update invoking. use it to schedule
974 | * ikcp_update (eg. implementing an epoll-like mechanism, or optimize
975 | * ikcp_update when handling massive kcp connections)
976 | *
977 | * @param current
978 | * @return
979 | */
980 | public int Check(long current)
981 | {
982 | int cur = (int)current;
983 | if (updated == 0)
984 | {
985 | return cur;
986 | }
987 | int ts_flush_temp = this.ts_flush;
988 | int tm_packet = 0x7fffffff;
989 | if (_itimediff(cur, ts_flush_temp) >= 10000 || _itimediff(cur, ts_flush_temp) < -10000)
990 | {
991 | ts_flush_temp = cur;
992 | }
993 | if (_itimediff(cur, ts_flush_temp) >= 0)
994 | {
995 | return cur;
996 | }
997 | int tm_flush = _itimediff(ts_flush_temp, cur);
998 | for (int i = 0; i < snd_buf.Count; i++)
999 | {
1000 | Segment seg = snd_buf[i];
1001 | int diff = _itimediff(seg.resendts, cur);
1002 | if (diff <= 0)
1003 | {
1004 | return cur;
1005 | }
1006 | if (diff < tm_packet)
1007 | {
1008 | tm_packet = diff;
1009 | }
1010 | }
1011 | int minimal = tm_packet < tm_flush ? tm_packet : tm_flush;
1012 | if (minimal >= interval)
1013 | {
1014 | minimal = interval;
1015 | }
1016 | return cur + minimal;
1017 | }
1018 |
1019 | /**
1020 | * change MTU size, default is 1400
1021 | *
1022 | * @param mtu
1023 | * @return
1024 | */
1025 | public int SetMtu(int mtu)
1026 | {
1027 | if (mtu < 50 || mtu < IKCP_OVERHEAD)
1028 | {
1029 | return -1;
1030 | }
1031 | //ByteBuf buf = new ByteBuf((mtu + IKCP_OVERHEAD) * 3);
1032 | this.mtu = mtu;
1033 | mss = mtu - IKCP_OVERHEAD;
1034 | buffer.EnsureCapacity((mtu + IKCP_OVERHEAD) * 3);
1035 | return 0;
1036 | }
1037 |
1038 | /**
1039 | * interval per update
1040 | *
1041 | * @param interval
1042 | * @return
1043 | */
1044 | public int Interval(int interval)
1045 | {
1046 | if (interval > 5000)
1047 | {
1048 | interval = 5000;
1049 | }
1050 | else if (interval < 10)
1051 | {
1052 | interval = 10;
1053 | }
1054 | this.interval = interval;
1055 | return 0;
1056 | }
1057 |
1058 | /**
1059 | * fastest: ikcp_nodelay(kcp, 1, 20, 2, 1) nodelay: 0:disable(default),
1060 | * 1:enable interval: internal update timer interval in millisec, default is
1061 | * 100ms resend: 0:disable fast resend(default), 1:enable fast resend nc:
1062 | * 0:normal congestion control(default), 1:disable congestion control
1063 | *
1064 | * @param nodelay
1065 | * @param interval
1066 | * @param resend
1067 | * @param nc
1068 | * @return
1069 | */
1070 | public int NoDelay(int nodelay, int interval, int resend, int nc)
1071 | {
1072 | if (nodelay >= 0)
1073 | {
1074 | this.nodelay = nodelay;
1075 | if (nodelay != 0)
1076 | {
1077 | rx_minrto = IKCP_RTO_NDL;
1078 | }
1079 | else
1080 | {
1081 | rx_minrto = IKCP_RTO_MIN;
1082 | }
1083 | }
1084 | if (interval >= 0)
1085 | {
1086 | if (interval > 5000)
1087 | {
1088 | interval = 5000;
1089 | }
1090 | else if (interval < 10)
1091 | {
1092 | interval = 10;
1093 | }
1094 | this.interval = interval;
1095 | }
1096 | if (resend >= 0)
1097 | {
1098 | fastresend = resend;
1099 | }
1100 | if (nc >= 0)
1101 | {
1102 | nocwnd = nc;
1103 | }
1104 | return 0;
1105 | }
1106 |
1107 | /**
1108 | * set maximum window size: sndwnd=32, rcvwnd=32 by default
1109 | *
1110 | * @param sndwnd
1111 | * @param rcvwnd
1112 | * @return
1113 | */
1114 | public int WndSize(int sndwnd, int rcvwnd)
1115 | {
1116 | if (sndwnd > 0)
1117 | {
1118 | snd_wnd = sndwnd;
1119 | }
1120 | if (rcvwnd > 0)
1121 | {
1122 | rcv_wnd = rcvwnd;
1123 | }
1124 | return 0;
1125 | }
1126 |
1127 | /**
1128 | * get how many packet is waiting to be sent
1129 | *
1130 | * @return
1131 | */
1132 | public int WaitSnd()
1133 | {
1134 | return snd_buf.Count + snd_queue.Count;
1135 | }
1136 |
1137 | public void SetNextUpdate(int nextUpdate)
1138 | {
1139 | this.nextUpdate = nextUpdate;
1140 | }
1141 |
1142 | public int GetNextUpdate()
1143 | {
1144 | return nextUpdate;
1145 | }
1146 |
1147 | public bool IsStream()
1148 | {
1149 | return stream;
1150 | }
1151 |
1152 | public void SetStream(bool stream)
1153 | {
1154 | this.stream = stream;
1155 | }
1156 |
1157 | public void SetMinRto(int min)
1158 | {
1159 | rx_minrto = min;
1160 | }
1161 | public void SetConv(int conv)
1162 | {
1163 | this.conv = conv;
1164 | }
1165 | }
1166 |
1167 |
1168 |
--------------------------------------------------------------------------------