~ruther/NosSmooth

ref: 99aaa9b108e0e125d0c7795f4d35bcc3ba8e0b90 NosSmooth/Extensions/NosSmooth.Extensions.Combat/Operations/WalkInRangeOperation.cs -rw-r--r-- 6.0 KiB
99aaa9b1 — Rutherther Merge pull request #71 from plsfixrito/PtctlPacket- 2 years ago
                                                                                
1
2
3
4
5
6
7
8
9
10
11
12
13
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
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
//
//  WalkInRangeOperation.cs
//
//  Copyright (c) František Boháček. All rights reserved.
//  Licensed under the MIT license. See LICENSE file in the project root for full license information.

using System.Diagnostics;
using NosSmooth.Extensions.Combat.Errors;
using NosSmooth.Extensions.Pathfinding;
using NosSmooth.Extensions.Pathfinding.Errors;
using NosSmooth.Game.Data.Entities;
using NosSmooth.Game.Data.Info;
using NosSmooth.Game.Errors;
using NosSmooth.Packets.Client.Inventory;
using Remora.Results;

namespace NosSmooth.Extensions.Combat.Operations;

/// <summary>
/// A combat operation that walks into a given range of an entity.
/// </summary>
/// <param name="WalkManager">The walk manager.</param>
/// <param name="Entity">The entity to walk to.</param>
/// <param name="Distance">The maximal distance from the entity.</param>
public record WalkInRangeOperation
(
    WalkManager WalkManager,
    IEntity Entity,
    float Distance
) : ICombatOperation
{
    private Task<Result>? _walkInRangeOperation;
    private CancellationTokenSource? _ct;
    private bool _disposed;

    /// <inheritdoc />
    public OperationQueueType QueueType => OperationQueueType.TotalControl;

    /// <inheritdoc />
    public bool MayBeCancelled => true;

    /// <inheritdoc />
    public Task<Result> BeginExecution(ICombatState combatState, CancellationToken ct = default)
    {
        if (_walkInRangeOperation is not null)
        {
            return Task.FromResult(Result.FromSuccess());
        }

        _ct = new CancellationTokenSource();
        _walkInRangeOperation = Task.Run
        (
            () => UseAsync(combatState, _ct.Token),
            _ct.Token
        );
        return Task.FromResult(Result.FromSuccess());
    }

    /// <inheritdoc />
    public async Task<Result> WaitForFinishedAsync(ICombatState combatState, CancellationToken ct = default)
    {
        if (IsFinished())
        {
            return Result.FromSuccess();
        }

        await BeginExecution(combatState, ct);
        if (_walkInRangeOperation is null)
        {
            throw new UnreachableException();
        }

        try
        {
            return await _walkInRangeOperation;
        }
        catch (OperationCanceledException)
        {
            return Result.FromSuccess();
        }
        catch (Exception e)
        {
            return e;
        }
    }

    /// <inheritdoc />
    public bool IsExecuting()
        => _walkInRangeOperation is not null && !IsFinished();

    /// <inheritdoc />
    public bool IsFinished()
        => _walkInRangeOperation?.IsCompleted ?? false;

    /// <inheritdoc />
    public Result CanBeUsed(ICombatState combatState)
    {
        var character = combatState.Game.Character;
        if (character is null)
        {
            return new CharacterNotInitializedError();
        }

        if (character.CantMove)
        {
            return new CannotBeUsedError(CanBeUsedResponse.MustWait, new CharacterCannotMoveError());
        }

        return Result.FromSuccess();
    }

    /// <inheritdoc />
    public void Cancel()
    {
        _ct?.Cancel();
    }

    private async Task<Result> UseAsync(ICombatState combatState, CancellationToken ct = default)
    {
        var character = combatState.Game.Character;
        if (character is null)
        {
            return new CharacterNotInitializedError();
        }

        var distance = Distance;
        while (distance >= 0)
        {
            var position = Entity.Position;
            if (position is null)
            {
                return new NotInitializedError("entity's position");
            }

            var currentPosition = character.Position;
            if (currentPosition is null)
            {
                return new CharacterNotInitializedError("Position");
            }

            if (Entity.Position?.DistanceSquared(currentPosition.Value) <= Distance * Distance)
            {
                return Result.FromSuccess();
            }

            var closePosition = GetClosePosition(currentPosition.Value, position.Value, distance);
            if (closePosition == currentPosition)
            {
                return Result.FromSuccess();
            }

            using var goToCancellationTokenSource = CancellationTokenSource.CreateLinkedTokenSource(ct);
            var walkResultTask = WalkManager.GoToAsync
                (closePosition.X, closePosition.Y, true, goToCancellationTokenSource.Token);

            while (!walkResultTask.IsCompleted)
            {
                await Task.Delay(5, ct);
                if (Entity.Position != position)
                {
                    goToCancellationTokenSource.Cancel();
                    await walkResultTask;
                }
            }

            if (Entity.Position != position)
            {
                continue;
            }

            var walkResult = await walkResultTask;
            if ((character.Position - Entity.Position)?.DistanceSquared(Position.Zero) <= Distance * Distance)
            {
                return Result.FromSuccess();
            }

            if (!walkResult.IsSuccess && walkResult.Error is PathNotFoundError)
            {
                if (distance - 1 > 0)
                {
                    distance--;
                }
                else
                {
                    distance = 0;
                }

                continue;
            }

            return walkResult;
        }

        return Result.FromSuccess();
    }

    private Position GetClosePosition(Position start, Position target, double distance)
    {
        var diff = start - target;
        if (diff.DistanceSquared(Position.Zero) < distance * distance)
        {
            return start;
        }

        var diffLength = Math.Sqrt(diff.DistanceSquared(Position.Zero));
        return target + ((distance / diffLength) * diff);
    }

    /// <inheritdoc />
    public void Dispose()
    {
        if (_disposed)
        {
            return;
        }
        _disposed = true;
        _ct?.Cancel();
        _walkInRangeOperation?.Dispose();
        _ct?.Dispose();
    }
}
Do not follow this link