Exemplo n.º 1
0
 public static void Ignore(this Task task)
 {
     task.ContinueWith(x => {
         AcToolsLogging.Write(x.Exception?.Flatten());
     }, TaskContinuationOptions.NotOnRanToCompletion);
 }
Exemplo n.º 2
0
        public static async Task <Result> StartAsync(IAcsStarter starter, StartProperties properties, IProgress <ProgressState> progress = null,
                                                     CancellationToken cancellation = default(CancellationToken))
        {
            if (_busy)
            {
                return(null);
            }
            _busy = true;

            if (OptionDebugMode)
            {
                progress?.Report(ProgressState.Waiting);
                await Task.Delay(500, cancellation);

                _busy = false;
                return(GetResult());
            }

            RemoveResultJson();
            KeyboardListener listener = null;

            if (properties.SetKeyboardListener)
            {
                try {
                    listener = new KeyboardListener();
                    listener.Subscribe();
                } catch (Exception e) {
                    AcToolsLogging.Write("Can’t set listener: " + e);
                }
            }

            try {
                progress?.Report(ProgressState.Preparing);
                await Task.Run(() => properties.Set(), cancellation);

                if (cancellation.IsCancellationRequested || OptionRaceIniTestMode)
                {
                    return(null);
                }

                progress?.Report(ProgressState.Launching);
                await starter.RunAsync(cancellation);

                if (cancellation.IsCancellationRequested)
                {
                    return(null);
                }

                var process = await starter.WaitUntilGameAsync(cancellation);

                await Task.Run(() => properties.SetGame(process), cancellation);

                if (cancellation.IsCancellationRequested)
                {
                    return(null);
                }

                progress?.Report(ProgressState.Waiting);
                await starter.WaitGameAsync(cancellation);

                if (cancellation.IsCancellationRequested)
                {
                    return(null);
                }
            } finally {
                _busy = false;

                if (cancellation.IsCancellationRequested)
                {
                    starter.CleanUp();
                }
                else
                {
                    progress?.Report(ProgressState.Finishing);
                    await starter.CleanUpAsync(cancellation);
                }

                properties.RevertChanges();
                listener?.Dispose();
            }

            return(GetResult());
        }
Exemplo n.º 3
0
        private void SplitShot(int width, int height, double downscale, RendererShotFormat format, SplitCallback callback, out int cuts,
                               [CanBeNull] IProgress <Tuple <string, double?> > progress, CancellationToken cancellation)
        {
            ShotInProcessValue++;

            var original = new { Width, Height, ResolutionMultiplier, TimeFactor };

            ResolutionMultiplier = 1d;
            AutoAdjustTarget     = false;
            AutoRotate           = false;
            TimeFactor           = 0f;

            cuts = Math.Ceiling(width / OptionMaxWidth).FloorToInt();
            if (cuts < 1)
            {
                cuts = 1;
            }

            width  /= cuts;
            height /= cuts;

            var expand = UseSslr || UseAo;
            int extraWidth, extraHeight;

            if (expand)
            {
                extraWidth  = (width * OptionGBufferExtra).RoundToInt();
                extraHeight = (height * OptionGBufferExtra).RoundToInt();
            }
            else
            {
                extraWidth  = width;
                extraHeight = height;
            }

            Width  = extraWidth;
            Height = extraHeight;

            var baseCut = expand ?
                          Matrix.Transformation2D(Vector2.Zero, 0f, new Vector2(1f / OptionGBufferExtra), Vector2.Zero, 0f, Vector2.Zero) :
                          Matrix.Identity;

            try {
                var temporary = OptionTemporaryDirectory;
                if (expand && temporary != null)
                {
                    FileUtils.EnsureDirectoryExists(temporary);

                    for (var i = 0; i < cuts * cuts; i++)
                    {
                        var x = i % cuts;
                        var y = i / cuts;
                        progress?.Report(new Tuple <string, double?>($"x={x}, y={y}, piece by piece", (double)i / (cuts * cuts) * 0.5));
                        if (cancellation.IsCancellationRequested)
                        {
                            return;
                        }

                        SetCutProjection(cuts, x, y, baseCut);
                        var filename = Path.Combine(temporary, $"tmp-{y:D2}-{x:D2}{format.GetExtension()}");
                        using (var stream = File.Open(filename, FileMode.Create, FileAccess.ReadWrite)) {
                            Shot(extraWidth, extraHeight, downscale, 1d, stream, format);
                        }
                    }

                    var shotWidth  = (width * downscale).RoundToInt();
                    var shotHeight = (height * downscale).RoundToInt();
                    AcToolsLogging.Write($"Rendered: downscale={downscale}, {shotWidth}×{shotHeight}, {LastShotWidth}×{LastShotHeight}");

                    using (var blender = new PiecesBlender(shotWidth, shotHeight, OptionGBufferExtra)) {
                        blender.Initialize();

                        for (var i = 0; i < cuts * cuts; i++)
                        {
                            var x = i % cuts;
                            var y = i / cuts;
                            progress?.Report(new Tuple <string, double?>($"X={x}, Y={y}, smoothing", (double)i / (cuts * cuts) * 0.5 + 0.5));
                            if (cancellation.IsCancellationRequested)
                            {
                                return;
                            }

                            callback(s => blender.Process(new Pieces(temporary, $"tmp-{{0:D2}}-{{1:D2}}{format.GetExtension()}", y, x), s),
                                     x, y, shotWidth, shotHeight);
                        }
                    }

                    AcToolsLogging.Write("Blended");
                }
                else
                {
                    for (var i = 0; i < cuts * cuts; i++)
                    {
                        var x = i % cuts;
                        var y = i / cuts;
                        progress?.Report(new Tuple <string, double?>($"X={x}, Y={y}", (double)i / (cuts * cuts)));
                        if (cancellation.IsCancellationRequested)
                        {
                            return;
                        }

                        SetCutProjection(cuts, x, y, baseCut);
                        callback(s => Shot(extraWidth, extraHeight, downscale, expand ? OptionGBufferExtra : 1d, s, format),
                                 x, y, (original.Width * downscale).RoundToInt(), (original.Height * downscale).RoundToInt());
                    }
                }
            } finally {
                Camera.CutProj = null;
                Camera.SetLens(Camera.Aspect);

                Width  = original.Width;
                Height = original.Height;
                ResolutionMultiplier = original.ResolutionMultiplier;
                TimeFactor           = original.TimeFactor;

                ShotInProcessValue--;
            }
        }
Exemplo n.º 4
0
 protected static IntPtr CreateNewFormForHandle()
 {
     AcToolsLogging.Write("Creating new form to get its handle…");
     Application.Current.Dispatcher?.Invoke(() => { _form2 = new FormWithHandle(); });
     return(_form2.Handle);
 }
Exemplo n.º 5
0
        public bool Apply(int steerLock, bool isReset, out int appliedValue)
        {
            appliedValue = Math.Min(Math.Max(steerLock, MinimumSteerLock), MaximumSteerLock);
            var cmd0 = new byte[] { 0x1, 0xf5, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0 };
            var cmd1 = new byte[] { 0x1, 0xf8, 0x09, 0x01, 0x06, 0x01, 0x0, 0x0 };
            var cmd2 = new byte[] { 0x1, 0xf8, 0x81 }
            .Concat(BitConverter.GetBytes((ushort)appliedValue))
            .Concat(new byte[] { 0x0, 0x0, 0x0 }).ToArray();
            var cmdE = new byte[] { 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0 };

            return(HidDevices.Enumerate(0xEB7, 0x7).Aggregate(false, (a, b) => {
                using (b) {
                    try {
                        AcToolsLogging.Write($"Set to {steerLock}: " + b.DevicePath);
                        AcToolsLogging.Write($"Device state: connected={b.IsConnected}, description={b.Description}");
                        AcToolsLogging.Write(
                            $"Device caps: Usage={b.Capabilities.Usage}, UsagePage={b.Capabilities.UsagePage}, FeatureReportByteLength={b.Capabilities.FeatureReportByteLength}");
                        AcToolsLogging.Write(
                            $"Device caps: OutputReportByteLength={b.Capabilities.OutputReportByteLength}, InputReportByteLength={b.Capabilities.InputReportByteLength}");
                        AcToolsLogging.Write(
                            $"Device caps: NumberLinkCollectionNodes={b.Capabilities.NumberLinkCollectionNodes}, NumberInputButtonCaps={b.Capabilities.NumberInputButtonCaps}");
                        AcToolsLogging.Write(
                            $"Device caps: NumberInputValueCaps={b.Capabilities.NumberInputValueCaps}, NumberInputDataIndices={b.Capabilities.NumberInputDataIndices}");
                        AcToolsLogging.Write(
                            $"Device caps: NumberOutputButtonCaps={b.Capabilities.NumberOutputButtonCaps}, NumberOutputValueCaps={b.Capabilities.NumberOutputValueCaps}");
                        AcToolsLogging.Write(
                            $"Device caps: NumberOutputDataIndices={b.Capabilities.NumberOutputDataIndices}, NumberFeatureButtonCaps={b.Capabilities.NumberFeatureButtonCaps}");
                        AcToolsLogging.Write(
                            $"Device caps: NumberFeatureValueCaps={b.Capabilities.NumberFeatureValueCaps}, NumberFeatureDataIndices={b.Capabilities.NumberFeatureDataIndices}");
                        if (b.Capabilities.Usage != 4)
                        {
                            AcToolsLogging.Write("Unknown usage for setting a lock");
                            // return a;
                        }
                        b.OpenDevice();
                        AcToolsLogging.Write($"Device state: opened={b.IsOpen}, handle={b.WriteHandle}, read={b.ReadHandle}");
                        if (b.WriteDataThrowy(cmd0, 0))
                        {
                            AcToolsLogging.Write($"First command sent: {cmd0.Select(x => x.ToString("X2")).JoinToString(" ")}");
                            AcToolsLogging.Write($"Device state post-writing first command: opened={b.IsOpen}, handle={b.WriteHandle}");
                            if (b.WriteDataThrowy(cmd1, 0))
                            {
                                AcToolsLogging.Write($"Second command sent: {cmd1.Select(x => x.ToString("X2")).JoinToString(" ")}");
                                if (b.WriteDataThrowy(cmd2, 0))
                                {
                                    AcToolsLogging.Write($"Third command sent: {cmd2.Select(x => x.ToString("X2")).JoinToString(" ")}");
                                    if (b.Write(cmd2))
                                    {
                                        AcToolsLogging.Write($"Empty command sent: {cmdE.Select(x => x.ToString("X2")).JoinToString(" ")}");
                                        AcToolsLogging.Write($"Device state post-writing: opened={b.IsOpen}, handle={b.WriteHandle}");
                                        b.CloseDevice();
                                        return true;
                                    }
                                }
                            }
                        }
                        else
                        {
                            AcToolsLogging.Write($"Failed to sent even the first command: {Marshal.GetLastWin32Error()}");
                        }
                        AcToolsLogging.Write($"Device state post-writing: opened={b.IsOpen}, handle={b.WriteHandle}");
                    } catch (Exception e) {
                        AcToolsLogging.Write($"Error: {e}");
                    }
                }
                return a;
            }));
        }
Exemplo n.º 6
0
 private static void Log(bool value, [CallerMemberName] string m = null, [CallerLineNumber] int l = -1)
 {
     AcToolsLogging.Write($"Result [{m}:{l}]: {value}");
 }
Exemplo n.º 7
0
 protected static void Apply()
 {
     AcToolsLogging.Write("Applying…");
     Log(LogiUpdate());
 }
Exemplo n.º 8
0
        private void ExportCollada_Mesh(XmlWriter xml, string name, IReadOnlyList <Kn5Node> unsorted)
        {
            AcToolsLogging.Write($"{name}: {unsorted.Sum(x => x.Vertices.Length)} vertices, {unsorted.Sum(x => x.Indices.Length / 3d)} triangles");

            xml.WriteStartElement("geometry");
            xml.WriteAttributeStringSafe("id", $"{name}-mesh");
            xml.WriteAttributeStringSafe("name", name);

            xml.WriteStartElement("mesh");

            var nodes = unsorted.Count == 1 ? unsorted :
                        unsorted.OrderBy(x => int.Parse(x.UniqueName.Split(new[] { "_SUB" }, StringSplitOptions.None).Last())).ToList();

            /* coordinates */
            var vertexCount = nodes.Sum(x => x.Vertices.Length);

            xml.WriteStartElement("source");
            xml.WriteAttributeStringSafe("id", $"{name}-mesh-positions");
            xml.WriteStartElement("float_array");
            xml.WriteAttributeStringSafe("id", $"{name}-mesh-positions-array");
            xml.WriteAttributeString("count", vertexCount * 3);
            xml.WriteString(nodes.SelectMany(x => x.Vertices).SelectMany(x => x.Position).JoinToString(" "));
            xml.WriteEndElement(); // float_array

            xml.WriteStartElement("technique_common");
            xml.WriteStartElement("accessor");
            xml.WriteAttributeStringSafe("source", $"#{name}-mesh-positions-array");
            xml.WriteAttributeString("count", vertexCount);
            xml.WriteAttributeString("stride", 3);

            xml.WriteElement("param",
                             "name", "X",
                             "type", "float");
            xml.WriteElement("param",
                             "name", "Y",
                             "type", "float");
            xml.WriteElement("param",
                             "name", "Z",
                             "type", "float");

            xml.WriteEndElement(); // accessor
            xml.WriteEndElement(); // technique_common
            xml.WriteEndElement(); // source

            /* normals */
            xml.WriteStartElement("source");
            xml.WriteAttributeStringSafe("id", $"{name}-mesh-normals");
            xml.WriteStartElement("float_array");
            xml.WriteAttributeStringSafe("id", $"{name}-mesh-normals-array");
            xml.WriteAttributeString("count", vertexCount * 3);
            xml.WriteString(nodes.SelectMany(x => x.Vertices).SelectMany(x => x.Normal).JoinToString(" "));
            xml.WriteEndElement(); // float_array

            xml.WriteStartElement("technique_common");
            xml.WriteStartElement("accessor");
            xml.WriteAttributeStringSafe("source", $"#{name}-mesh-normals-array");
            xml.WriteAttributeString("count", vertexCount);
            xml.WriteAttributeString("stride", "3");

            xml.WriteElement("param",
                             "name", "X",
                             "type", "float");
            xml.WriteElement("param",
                             "name", "Y",
                             "type", "float");
            xml.WriteElement("param",
                             "name", "Z",
                             "type", "float");

            xml.WriteEndElement(); // accessor
            xml.WriteEndElement(); // technique_common
            xml.WriteEndElement(); // source

            /* uv */
            xml.WriteStartElement("source");
            xml.WriteAttributeStringSafe("id", $"{name}-mesh-map-0");
            xml.WriteStartElement("float_array");
            xml.WriteAttributeStringSafe("id", $"{name}-mesh-map-0-array");
            xml.WriteAttributeString("count", vertexCount * 2);
            xml.WriteString(nodes.SelectMany(x => x.Vertices).SelectMany(x => new[] { x.TexC[0], -x.TexC[1] }).JoinToString(" "));
            xml.WriteEndElement(); // float_array

            xml.WriteStartElement("technique_common");
            xml.WriteStartElement("accessor");
            xml.WriteAttributeStringSafe("source", $"#{name}-mesh-map-0-array");
            xml.WriteAttributeString("count", vertexCount);
            xml.WriteAttributeString("stride", 2);

            xml.WriteElement("param",
                             "name", "S",
                             "type", "float");
            xml.WriteElement("param",
                             "name", "T",
                             "type", "float");

            xml.WriteEndElement(); // accessor
            xml.WriteEndElement(); // technique_common
            xml.WriteEndElement(); // source

            /* vertices */
            xml.WriteStartElement("vertices");
            xml.WriteAttributeStringSafe("id", $"{name}-mesh-vertices");
            xml.WriteElement("input",
                             "semantic", "POSITION",
                             "source", $"#{name}-mesh-positions");
            xml.WriteEndElement();

            /* triangles */
            var offset = 0;

            foreach (var node in nodes)
            {
                xml.WriteStartElement("triangles");
                xml.WriteAttributeStringSafe("original_node", $"{node.UniqueName}");
                xml.WriteAttributeStringSafe("material", $"{Materials.Values.ElementAt((int)node.MaterialId).Name}-material");
                xml.WriteAttributeString("count", node.Indices.Length / 3);

                xml.WriteElement("input",
                                 "semantic", "VERTEX",
                                 "source", $"#{name}-mesh-vertices",
                                 "offset", 0);
                xml.WriteElement("input",
                                 "semantic", "NORMAL",
                                 "source", $"#{name}-mesh-normals",
                                 "offset", 1);
                xml.WriteElement("input",
                                 "semantic", "TEXCOORD",
                                 "source", $"#{name}-mesh-map-0",
                                 "offset", 2,
                                 "set", 0);

                var inner = offset;
                xml.WriteElementString("p", node.Indices.SelectMany(x => new[] { x + inner, x + inner, x + inner }).JoinToString(" "));
                xml.WriteEndElement(); // triangles

                offset += node.Vertices.Length;
            }

            xml.WriteEndElement(); // mesh
            xml.WriteEndElement(); // geometry
        }
Exemplo n.º 9
0
        private async void OnGameStarted()
        {
            var id = ++_applyId;

            if (!_valueToSet.HasValue)
            {
                return;
            }
            var value = _valueToSet.Value;

            var process = AcProcess.TryToFind();

            if (process == null)
            {
                AcToolsLogging.NonFatalErrorNotifyBackground($"Can’t set {ControllerName} steer lock", "Failed to find game process");
                return;
            }

            IntPtr?initializationHandle;

            if (!_options.SpecifyHandle)
            {
                AcToolsLogging.Write("Handle won’t be specified");
                initializationHandle = null;
            }
            else if (_options.UseOwnHandle)
            {
                initializationHandle = CreateNewFormForHandle();
            }
            else
            {
                AcToolsLogging.Write("AC handle will be used");
                initializationHandle = process.MainWindowHandle;
            }

            Initialize(initializationHandle);

            await Task.Delay(500);

            AcToolsLogging.Write("Waited for half a second, moving on…");

            if (_applyId != id)
            {
                AcToolsLogging.Write("Obsolete run, terminating");
                return;
            }

            SetWheelRange(value);

            var isForeground = true;
            var setIndex     = 1;
            var windows      = process.GetWindowsHandles().ToArray();

            while (!process.HasExitedSafe())
            {
                var isForegroundNow = Array.IndexOf(windows, User32.GetForegroundWindow()) != -1;
                if (isForegroundNow != isForeground)
                {
                    if (isForegroundNow)
                    {
                        SetWheelRange(value + setIndex);
                        setIndex = 1 - setIndex;
                    }

                    isForeground = isForegroundNow;
                }

                await Task.Delay(50).ConfigureAwait(false);
            }
        }
Exemplo n.º 10
0
        public static async Task <Result> StartAsync(IAcsStarter starter, StartProperties properties, IProgress <ProgressState> progress = null,
                                                     CancellationToken cancellation = default)
        {
            if (_busy)
            {
                return(null);
            }
            _busy = true;

            if (OptionDebugMode)
            {
                progress?.Report(ProgressState.Waiting);
                await Task.Delay(500, cancellation);

                _busy = false;
                return(GetResult(DateTime.MinValue));
            }

            RemoveResultJson();
            IKeyboardListener listener = null;

            if (properties.SetKeyboardListener)
            {
                try {
                    listener = KeyboardListenerFactory.Get();
                    listener.Subscribe();
                } catch (Exception e) {
                    AcToolsLogging.Write("Can’t set listener: " + e);
                }
            }

            var start = DateTime.Now;

            try {
                progress?.Report(ProgressState.Preparing);
                await Task.Run(() => properties.Set(), cancellation);

                if (cancellation.IsCancellationRequested || OptionRaceIniTestMode)
                {
                    return(null);
                }

                while (true)
                {
                    progress?.Report(ProgressState.Launching);
                    await starter.RunAsync(cancellation);

                    if (cancellation.IsCancellationRequested)
                    {
                        return(null);
                    }

                    var process = await starter.WaitUntilGameAsync(cancellation);

                    await Task.Run(() => properties.SetGame(process), cancellation);

                    if (cancellation.IsCancellationRequested)
                    {
                        return(null);
                    }

                    progress?.Report(ProgressState.Waiting);
                    await starter.WaitGameAsync(cancellation);

                    if (cancellation.IsCancellationRequested)
                    {
                        return(null);
                    }

                    var raceIni = new IniFile(AcPaths.GetRaceIniFilename());
                    if (raceIni["RESTART"].GetBool("ACTIVE", false))
                    {
                        raceIni["RESTART"].Set("ACTIVE", false);
                        raceIni.Save();
                    }
                    else
                    {
                        break;
                    }
                }
            } finally {
                _busy = false;

                if (cancellation.IsCancellationRequested)
                {
                    starter.CleanUp();
                }
                else
                {
                    progress?.Report(ProgressState.Finishing);
                    await starter.CleanUpAsync(cancellation);
                }

                properties.RevertChanges();
                listener?.Dispose();
            }

            return(GetResult(start));
        }
Exemplo n.º 11
0
        protected override void ParseString(string data)
        {
            Clear();

            var started   = -1;
            var key       = double.NaN;
            var malformed = -1;
            var line      = 1;

            for (var i = 0; i < data.Length; i++)
            {
                switch (data[i])
                {
                case '\r':
                    if (i + 1 < data.Length)
                    {
                        var next = data[i + 1];
                        if (next == '\n' || next == '\r')
                        {
                            continue;
                        }
                    }

                    AcToolsLogging.Write($@"Unexpected “\r” at {line}");
                    malformed = line;
                    break;

                case '|':
                    if (started != -1)
                    {
                        if (!double.IsNaN(key) || !FlexibleParser.TryParseDouble(data.Substring(started, i - started), out key))
                        {
                            if (malformed == -1)
                            {
                                if (!double.IsNaN(key))
                                {
                                    AcToolsLogging.Write($@"Key already defined! But then, there is a second one, at {line}");
                                }
                                else
                                {
                                    AcToolsLogging.Write($@"Failed to parse key “{data.Substring(started, i - started)}” at {line}");
                                }

                                malformed = line;
                            }

                            SkipLine(data, ref i, ref line);
                            key = double.NaN;
                        }
                        started = -1;
                    }
                    break;

                case '\n':
                    Finish(Values, data, i, line, ref key, ref started, ref malformed);
                    line++;
                    break;

                case '/':
                    if (i + 1 < data.Length && data[i + 1] == '/')
                    {
                        goto case ';';
                    }
                    goto default;

                case ';':
                    Finish(Values, data, i, line, ref key, ref started, ref malformed);
                    SkipLine(data, ref i, ref line);
                    break;

                default:
                    if (started == -1)
                    {
                        started = i;
                    }
                    break;
                }
            }

            Finish(Values, data, data.Length, line, ref key, ref started, ref malformed);

            if (malformed != -1)
            {
                ErrorsCatcher?.Catch(this, malformed);
            }
        }
Exemplo n.º 12
0
        bool TestAabb(string key, Kn5Node obj, ITestEntry value)
        {
            var aabb3 = GetAabb3Dictionary();

            if (!aabb3.TryGetValue(obj, out var aabb))
            {
                return(false);
            }

            string cutKey;

            if (key.StartsWith("aabbRel"))
            {
                cutKey = key.Substring(7);
                if (aabb3.TryGetValue(_kn5.RootNode, out var aabbModel))
                {
                    aabb.Min.Y = aabb.Min.Y.LerpInv(aabbModel.Min.Y, aabbModel.Max.Y);
                    aabb.Max.Y = aabb.Max.Y.LerpInv(aabbModel.Min.Y, aabbModel.Max.Y);
                    aabb.Min.Z = aabb.Min.Z.LerpInv(aabbModel.Min.Z, aabbModel.Max.Z);
                    aabb.Max.Z = aabb.Max.Z.LerpInv(aabbModel.Min.Z, aabbModel.Max.Z);
                    if (cutKey.EndsWith("X") && !cutKey.StartsWith("Size"))
                    {
                        aabb.Min.X /= Math.Max(aabbModel.Max.X, aabbModel.Min.X);
                        aabb.Max.X /= Math.Max(aabbModel.Max.X, aabbModel.Min.X);
                    }
                    else
                    {
                        aabb.Min.X = aabb.Min.X.LerpInv(aabbModel.Min.X, aabbModel.Max.X);
                        aabb.Max.X = aabb.Max.X.LerpInv(aabbModel.Min.X, aabbModel.Max.X);
                    }
                }
            }
            else
            {
                cutKey = key.Substring(4);
            }

            switch (cutKey)
            {
            case "Size":
                return(value.Test(aabb.Size.Length()));

            case "SizeX":
                return(value.Test(aabb.Size.X));

            case "SizeY":
                return(value.Test(aabb.Size.Y));

            case "SizeZ":
                return(value.Test(aabb.Size.Z));

            case "CenterX":
                return(value.Test(aabb.Center.X));

            case "CenterY":
                return(value.Test(aabb.Center.Y));

            case "CenterZ":
                return(value.Test(aabb.Center.Z));

            case "MinX":
                return(value.Test(aabb.Min.X));

            case "MinY":
                return(value.Test(aabb.Min.Y));

            case "MinZ":
                return(value.Test(aabb.Min.Z));

            case "MaxX":
                return(value.Test(aabb.Max.X));

            case "MaxY":
                return(value.Test(aabb.Max.Y));

            case "MaxZ":
                return(value.Test(aabb.Max.Z));

            default:
                AcToolsLogging.Write("Unknown property: " + key);
                return(false);
            }
        }
Exemplo n.º 13
0
 public static void Ignore <T>(this Task <T> task)
 {
     task.ContinueWith(x => {
         AcToolsLogging.Write(x.Exception?.Flatten());
     }, TaskContinuationOptions.OnlyOnFaulted);
 }
Exemplo n.º 14
0
        private static string ToString(object v)
        {
            if (v == null)
            {
                return(null);
            }

            var t = Nullable.GetUnderlyingType(v.GetType()) ?? v.GetType();

            if (t.IsEnum)
            {
                return(v.ToString());
            }

            switch (Type.GetTypeCode(t))
            {
            case TypeCode.Empty:
            case TypeCode.DBNull:
                return(null);

            case TypeCode.Boolean:
                return(((bool)v).ToString(CultureInfo.InvariantCulture));

            case TypeCode.Char:
                return(((char)v).ToString(CultureInfo.InvariantCulture));

            case TypeCode.SByte:
                return(((sbyte)v).ToString(CultureInfo.InvariantCulture));

            case TypeCode.Byte:
                return(((byte)v).ToString(CultureInfo.InvariantCulture));

            case TypeCode.Int16:
                return(((short)v).ToString(CultureInfo.InvariantCulture));

            case TypeCode.UInt16:
                return(((ushort)v).ToString(CultureInfo.InvariantCulture));

            case TypeCode.Int32:
                return(((int)v).ToString(CultureInfo.InvariantCulture));

            case TypeCode.UInt32:
                return(((uint)v).ToString(CultureInfo.InvariantCulture));

            case TypeCode.Int64:
                return(((long)v).ToString(CultureInfo.InvariantCulture));

            case TypeCode.UInt64:
                return(((ulong)v).ToString(CultureInfo.InvariantCulture));

            case TypeCode.Single:
                return(((float)v).ToString(CultureInfo.InvariantCulture));

            case TypeCode.Double:
                return(((double)v).ToString(CultureInfo.InvariantCulture));

            case TypeCode.Decimal:
                return(((decimal)v).ToString(CultureInfo.InvariantCulture));

            case TypeCode.DateTime:
                return(((DateTime)v).ToString(CultureInfo.InvariantCulture));

            case TypeCode.String:
                return((string)v);

            case TypeCode.Object:
                if (!Registered.TryGetValue(t, out var p))
                {
                    AcToolsLogging.Write($"Not supported type: {t}");
                }
                else
                {
                    try {
                        return(p.Serialize(v));
                    } catch (Exception e) {
                        AcToolsLogging.Write(e);
                    }
                }
                return(null);

            default:
                throw new ArgumentOutOfRangeException();
            }
        }
Exemplo n.º 15
0
        private static object FromString(Type targetType, object v, object targetNullValue)
        {
            var t = Nullable.GetUnderlyingType(targetType) ?? targetType;
            var s = v.ToString();

            if (t.IsEnum)
            {
                try {
                    return(Enum.Parse(t, s));
                } catch {
                    AcToolsLogging.Write($"Invalid {t} value: {s}");
                    return(targetNullValue);
                }
            }

            switch (Type.GetTypeCode(t))
            {
            case TypeCode.Empty:
                return(null);

            case TypeCode.DBNull:
                return(DBNull.Value);

            case TypeCode.Boolean:
                var byteString = s;
                return(byteString == "1" || string.Equals(byteString, "true", StringComparison.OrdinalIgnoreCase) ? true
                            : byteString == "0" || string.Equals(byteString, "false", StringComparison.OrdinalIgnoreCase) ? false : targetNullValue);

            case TypeCode.Char:
                return(char.TryParse(s, out var char_) ? char_ : targetNullValue);

            case TypeCode.SByte:
                return(sbyte.TryParse(s, Ns, Cu, out var sbyte_) ? sbyte_ : targetNullValue);

            case TypeCode.Byte:
                return(byte.TryParse(s, Ns, Cu, out var byte_) ? byte_ : targetNullValue);

            case TypeCode.Int16:
                return(short.TryParse(s, Ns, Cu, out var short_) ? short_ : targetNullValue);

            case TypeCode.UInt16:
                return(ushort.TryParse(s, Ns, Cu, out var ushort_) ? ushort_ : targetNullValue);

            case TypeCode.Int32:
                return(int.TryParse(s, Ns, Cu, out var int_) ? int_ : targetNullValue);

            case TypeCode.UInt32:
                return(uint.TryParse(s, Ns, Cu, out var uint_) ? uint_ : targetNullValue);

            case TypeCode.Int64:
                return(long.TryParse(s, Ns, Cu, out var long_) ? long_ : targetNullValue);

            case TypeCode.UInt64:
                return(ulong.TryParse(s, Ns, Cu, out var ulong_) ? ulong_ : targetNullValue);

            case TypeCode.Single:
                return(float.TryParse(s, Ns, Cu, out var float_) ? float_ : targetNullValue);

            case TypeCode.Double:
                return(double.TryParse(s, Ns, Cu, out var double_) ? double_ : targetNullValue);

            case TypeCode.Decimal:
                return(decimal.TryParse(s, Ns, Cu, out var decimal_) ? decimal_ : targetNullValue);

            case TypeCode.DateTime:
                return(DateTime.TryParse(s, Cu, DateTimeStyles.AssumeLocal, out var dateTime) ? dateTime : targetNullValue);

            case TypeCode.String:
                return(s);

            case TypeCode.Object:
                if (!Registered.TryGetValue(t, out var p))
                {
                    AcToolsLogging.Write($"Not supported type: {t}");
                }
                else
                {
                    try {
                        return(p.Deserialize(s) ?? targetNullValue);
                    } catch (Exception e) {
                        AcToolsLogging.Write(t.FullName);
                        AcToolsLogging.Write(e);
                    }
                }
                return(targetNullValue);

            default:
                throw new ArgumentOutOfRangeException();
            }
        }
Exemplo n.º 16
0
 private static void SaveAsDds_Compressor(Stream stream, byte[] imageData, PreferredDdsFormat format, [CanBeNull] IProgress <double> progress)
 {
     using (var input = new MemoryStream(imageData))
         using (var image = (Bitmap)Image.FromStream(input)) {
             GetCompressor(format, image.Width, image.Height).Process(image.Width, image.Height, CopySafe(image), stream,
                                                                      new CompressProgress(progress),
                                                                      new CompressLog(s => AcToolsLogging.Write(s)));
         }
 }