Example #1
0
 protected override bool OnClose(params object[] args)
 {
     if (!IsOpen)
     {
         return(true);
     }
     foreach (var kvp in copySlots)
     {
         caches.Put(kvp.Value);
     }
     copySlots.Clear();
     selectedItems.Clear();
     SourceContainer.DarkIf(null);
     SourceContainer.MarkIf(null);
     SourceContainer = null;
     SourceHandler   = null;
     ZetanUtility.SetActive(tips, true);
     dialog        = string.Empty;
     SelectionType = ItemSelectionType.SelectNum;
     canSelect     = null;
     onConfirm     = null;
     if (!confirm)
     {
         onCancel?.Invoke();
     }
     onCancel = null;
     WindowsManager.CloseWindow <ItemWindow>();
     return(true);
 }
Example #2
0
        public PackageHandler GetFile(string id, string version)
        {
            var sourceBlob = SourceContainer.GetBlockBlobReference(
                StorageHelpers.GetPackageBlobName(id, version));

            return(new AzurePackageHandler(sourceBlob));
        }
Example #3
0
 protected override bool OnOpen(params object[] args)
 {
     if (IsOpen)
     {
         return(true);
     }
     if (args != null && args.Length > 8)
     {
         WindowsManager.CloseWindow <ItemWindow>();
         var par = (selectionType : (ItemSelectionType)args[0], container : (ISlotContainer)args[1], handler : (IInventoryHandler)args[2], confirm : args[3] as Action <List <ItemWithAmount> >,
                    title : args[4] as string, confirmDialog : args[5] as string, typeLimit : (int)args[6], amountLimit : (int)args[7], selectCondition : args[8] as Predicate <ItemSlotBase>, cancel : args[9] as Action);
         SelectionType    = par.selectionType;
         SourceContainer  = par.container;
         SourceHandler    = par.handler;
         windowTitle.text = par.title;
         dialog           = par.confirmDialog;
         typeLimit        = par.typeLimit;
         amountLimit      = par.amountLimit;
         if (par.selectCondition != null)
         {
             canSelect = par.selectCondition;
         }
         else
         {
             canSelect = (a) => { return(true); }
         };
         SourceContainer.DarkIf(x => !canSelect(x));
         onConfirm = par.confirm;
         onCancel  = par.cancel;
         confirm   = false;
         RegisterNotify();
         return(true);
     }
     return(false);
 }
Example #4
0
        public override Task Rebuild()
        {
            this.DebugDepth("Rebuild");

            var rebuildLock = this.RebuildLock();

            return(ApplicationController.Instance.Tasks.Execute(
                       "Mirror".Localize(),
                       null,
                       (reporter, cancellationToken) =>
            {
                SourceContainer.Visible = true;
                RemoveAllButSource();

                var oldMatrix = this.Matrix;
                this.Matrix = Matrix4X4.Identity;

                var mirrorMatrix = Matrix4X4.Identity;
                switch (MirrorOn)
                {
                case MirrorAxis.X_Axis:
                    mirrorMatrix = this.ApplyAtBoundsCenter(Matrix4X4.CreateScale(-1, 1, 1));
                    break;

                case MirrorAxis.Y_Axis:
                    mirrorMatrix = this.ApplyAtBoundsCenter(Matrix4X4.CreateScale(1, -1, 1));
                    break;

                case MirrorAxis.Z_Axis:
                    mirrorMatrix = this.ApplyAtBoundsCenter(Matrix4X4.CreateScale(1, 1, -1));
                    break;
                }

                foreach (var sourceItem in SourceContainer.VisibleMeshes())
                {
                    var originalMesh = sourceItem.Mesh;
                    var transformedMesh = originalMesh.Copy(CancellationToken.None);

                    var sourceToThisMatrix = sourceItem.WorldMatrix(this);

                    // move it to us then mirror then move it back
                    transformedMesh.Transform(sourceToThisMatrix * mirrorMatrix * sourceToThisMatrix.Inverted);

                    transformedMesh.ReverseFaces();

                    var newMesh = new Object3D()
                    {
                        Mesh = transformedMesh
                    };
                    newMesh.CopyWorldProperties(sourceItem, this, Object3DPropertyFlags.All, false);
                    this.Children.Add(newMesh);
                }

                this.Matrix = oldMatrix;
                SourceContainer.Visible = false;
                rebuildLock.Dispose();
                Parent?.Invalidate(new InvalidateArgs(this, InvalidateType.Children));
                return Task.CompletedTask;
            }));
        }
        private async Task CopyPackageToDestination(SharedAccessBlobPolicy policy, string packageBlobName)
        {
            // Identify the source and destination blobs
            var sourceBlob = SourceContainer.GetBlockBlobReference(packageBlobName);
            var destBlob   = DestinationContainer.GetBlockBlobReference(packageBlobName);

            // If the destination blob already exists, it will be overwritten. NO harm done
            // While it should not happen, to prevent several requests, do not check if it exists

            if (!await sourceBlob.ExistsAsync())
            {
                Log.SourceBlobMissing(sourceBlob.Name);
            }
            else
            {
                // Need to use Shared Access Signature since blobs to be copied are in a private container
                // Create a Shared Access Signature (SAS) Uri, for every blob to be copied
                // Set start time as Now and expiry time as Now + 12 hours
                policy.SharedAccessStartTime  = DateTimeOffset.Now;
                policy.SharedAccessExpiryTime = DateTimeOffset.Now + TimeSpan.FromHours(12);
                var sourceContainerSharedAccessUri = SourceContainer.GetSharedAccessSignature(policy);
                Log.SharedAccessSignatureURI(sourceContainerSharedAccessUri);

                var sourceUri = new Uri(sourceBlob.Uri, sourceContainerSharedAccessUri);

                // Start the copy or overwrite
                Log.StartingCopy(sourceUri.AbsoluteUri, destBlob.Uri.AbsoluteUri);
                if (!WhatIf)
                {
                    await destBlob.StartCopyFromBlobAsync(sourceUri);
                }
                Log.StartedCopy(sourceUri.AbsoluteUri, destBlob.Uri.AbsoluteUri);
            }
        }
        private async Task BackupPackage(string sourceBlobName, string destinationBlobName)
        {
            // Identify the source and destination blobs
            var sourceBlob = SourceContainer.GetBlockBlobReference(sourceBlobName);
            var destBlob   = DestinationContainer.GetBlockBlobReference(destinationBlobName);

            if (await destBlob.ExistsAsync())
            {
                Log.BackupExists(destBlob.Name);
            }
            else if (!await sourceBlob.ExistsAsync())
            {
                Log.SourceBlobMissing(sourceBlob.Name);
            }
            else
            {
                // Start the copy
                Log.StartingCopy(sourceBlob.Name, destBlob.Name);
                if (!WhatIf)
                {
                    await destBlob.StartCopyFromBlobAsync(sourceBlob);
                }
                Log.StartedCopy(sourceBlob.Name, destBlob.Name);
            }
        }
Example #7
0
        protected async Task CopyOrOverwritePackage(string sourceContainerSharedAccessUri, string sourceBlobName, string destinationBlobName, string packageHash)
        {
            // Identify the source and destination blobs
            var sourceBlob = SourceContainer.GetBlockBlobReference(sourceBlobName);
            var destBlob   = DestinationContainer.GetBlockBlobReference(destinationBlobName);

            // If the destination blob already exists, it will be overwritten
            // To prevent several requests, do not check if it exists

            if (!await sourceBlob.ExistsAsync())
            {
                Log.SourceBlobMissing(sourceBlob.Name);
            }
            else
            {
                var sourceUri = new Uri(sourceBlob.Uri, sourceContainerSharedAccessUri);
                // Start the copy or overwrite
                Log.StartingCopy(sourceUri.AbsoluteUri, destBlob.Uri.AbsoluteUri);
                if (!WhatIf)
                {
                    await destBlob.StartCopyFromBlobAsync(sourceUri);
                }
                Log.StartedCopy(sourceUri.AbsoluteUri, destBlob.Uri.AbsoluteUri);
            }
        }
        protected override void AdjustModel(TPreviewableDomainModel model)
        {
            base.AdjustModel(model);
            var    ravenEntityPreviewStorage = SourceContainer.Resolve <TPreviewRepository>();
            var    destinationModelId        = GetDestinationModelId(model);
            Stream stream;
            var    previewFile = ravenEntityPreviewStorage.GetPreviewFile(destinationModelId, out stream);

            if (previewFile != null && stream != null)
            {
                var location = previewFile.Id.Split('/').FirstOrDefault() ?? "unidentified";
                previewFile = PreviewFile.Create(previewFile.FileName, previewFile.ContentType, previewFile.ContentLength, location);
                using (var ms = new MemoryStream())
                {
                    stream.CopyTo(ms);
                    _ = ms.Seek(0, SeekOrigin.Begin);
                    previewFile.SetContent(ms.ToByteArray());
                    stream.Dispose();
                }
                SetDestinationModelPreview(model, previewFile);
            }

            // Fix situation when referenced file can not be retriewed
            if (previewFile == null)
            {
                SetDestinationModelPreview(model, null);
            }
        }
Example #9
0
 /// <summary>
 ///     CA1063 recomendation match
 /// </summary>
 /// <param name="full"> </param>
 protected virtual void Dispose(bool full)
 {
     if (null != SourceContainer)
     {
         SourceContainer.Release(this);
     }
 }
Example #10
0
        public override Task Rebuild()
        {
            this.DebugDepth("Rebuild");

            var rebuildLocks = this.RebuilLockAll();

            var valuesChanged = false;

            // check if we have be initialized

            return(TaskBuilder(
                       "Repair".Localize(),
                       (reporter, cancellationToken) =>
            {
                SourceContainer.Visible = true;
                RemoveAllButSource();

                var inititialVertices = 0;
                var inititialFaces = 0;
                var finalVertices = 0;
                var finalFaces = 0;
                foreach (var sourceItem in SourceContainer.VisibleMeshes())
                {
                    var originalMesh = sourceItem.Mesh;
                    inititialFaces += originalMesh.Faces.Count;
                    inititialVertices += originalMesh.Vertices.Count;
                    var repairedMesh = Repair(originalMesh, cancellationToken);
                    finalFaces += repairedMesh.Faces.Count;
                    finalVertices += repairedMesh.Vertices.Count;

                    var repairedChild = new Object3D()
                    {
                        Mesh = repairedMesh
                    };
                    repairedChild.CopyWorldProperties(sourceItem, this, Object3DPropertyFlags.All, false);
                    this.Children.Add(repairedChild);
                }

                this.InitialFaces = inititialFaces;
                this.InitialVertices = inititialVertices;
                this.FinalFaces = finalFaces;
                this.FinalVertices = finalVertices;

                SourceContainer.Visible = false;

                UiThread.RunOnIdle(() =>
                {
                    rebuildLocks.Dispose();
                    if (valuesChanged)
                    {
                        Invalidate(InvalidateType.DisplayValues);
                    }
                    Parent?.Invalidate(new InvalidateArgs(this, InvalidateType.Children));
                });

                return Task.CompletedTask;
            }));
        }
Example #11
0
        public override Task Rebuild()
        {
            this.DebugDepth("Rebuild");

            var rebuildLocks = this.RebuilLockAll();

            var valuesChanged = false;

            // check if we have be initialized
            if (Mode == ReductionMode.Polygon_Count)
            {
                TargetCount   = agg_basics.Clamp(TargetCount, 4, SourcePolygonCount, ref valuesChanged);
                TargetPercent = TargetCount / (double)SourcePolygonCount * 100;
            }
            else
            {
                TargetPercent = agg_basics.Clamp(TargetPercent, 0, 100, ref valuesChanged);
                TargetCount   = (int)(SourcePolygonCount * TargetPercent / 100);
            }

            return(TaskBuilder(
                       "Reduce".Localize(),
                       (reporter, cancellationToken) =>
            {
                SourceContainer.Visible = true;
                RemoveAllButSource();

                foreach (var sourceItem in SourceContainer.VisibleMeshes())
                {
                    var originalMesh = sourceItem.Mesh;
                    var targetCount = (int)(originalMesh.Faces.Count * TargetPercent / 100);
                    var reducedMesh = Reduce(originalMesh, targetCount);

                    var newMesh = new Object3D()
                    {
                        Mesh = reducedMesh,
                        OwnerID = sourceItem.ID
                    };
                    newMesh.CopyProperties(sourceItem, Object3DPropertyFlags.All);
                    this.Children.Add(newMesh);
                }

                SourceContainer.Visible = false;

                UiThread.RunOnIdle(() =>
                {
                    rebuildLocks.Dispose();
                    if (valuesChanged)
                    {
                        Invalidate(InvalidateType.DisplayValues);
                    }
                    Parent?.Invalidate(new InvalidateArgs(this, InvalidateType.Children));
                });

                return Task.CompletedTask;
            }));
        }
Example #12
0
        private void Intersect(CancellationToken cancellationToken, IProgress <ProgressStatus> reporter)
        {
            SourceContainer.Visible = true;
            RemoveAllButSource();

            var participants = SourceContainer.VisibleMeshes();

            if (participants.Count() < 2)
            {
                if (participants.Count() == 1)
                {
                    var newMesh = new Object3D();
                    newMesh.CopyProperties(participants.First(), Object3DPropertyFlags.All);
                    newMesh.Mesh = participants.First().Mesh;
                    this.Children.Add(newMesh);
                    SourceContainer.Visible = false;
                }
                return;
            }

            var first            = participants.First();
            var resultsMesh      = first.Mesh;
            var firstWorldMatrix = first.WorldMatrix(SourceContainer);

            var    totalOperations    = participants.Count() - 1;
            double amountPerOperation = 1.0 / totalOperations;
            double percentCompleted   = 0;

            ProgressStatus progressStatus = new ProgressStatus();

            foreach (var item in participants)
            {
                if (item != first)
                {
                    var itemWorldMatrix = item.WorldMatrix(SourceContainer);
                    resultsMesh = BooleanProcessing.Do(item.Mesh, itemWorldMatrix,
                                                       resultsMesh, firstWorldMatrix,
                                                       2,
                                                       reporter, amountPerOperation, percentCompleted, progressStatus, cancellationToken);
                    // after the first union we are working with the transformed mesh and don't need the first transform
                    firstWorldMatrix = Matrix4X4.Identity;

                    percentCompleted           += amountPerOperation;
                    progressStatus.Progress0To1 = percentCompleted;
                    reporter?.Report(progressStatus);
                }
            }

            var resultsItem = new Object3D()
            {
                Mesh = resultsMesh
            };

            resultsItem.CopyProperties(first, Object3DPropertyFlags.All & (~Object3DPropertyFlags.Matrix));
            this.Children.Add(resultsItem);
            SourceContainer.Visible = false;
        }
        private void Merge(IProgress <ProgressStatus> reporter, CancellationToken cancellationToken)
        {
            SourceContainer.Visible = true;
            RemoveAllButSource();

            var participants = SourceContainer.VisiblePaths();

            if (participants.Count() < 2)
            {
                if (participants.Count() == 1)
                {
                    var newMesh = new Object3D();
                    newMesh.CopyProperties(participants.First(), Object3DPropertyFlags.All);
                    newMesh.Mesh = participants.First().Mesh;
                    this.Children.Add(newMesh);
                    SourceContainer.Visible = false;
                }

                return;
            }

            var first = participants.First();
            var resultsVertexSource = (first as IPathObject).VertexSource.Transform(first.Matrix);

            var    totalOperations    = participants.Count() - 1;
            double amountPerOperation = 1.0 / totalOperations;
            double percentCompleted   = 0;

            var progressStatus = new ProgressStatus();

            foreach (var item in participants)
            {
                if (item != first &&
                    item is IPathObject pathItem)
                {
                    var itemVertexSource = pathItem.VertexSource.Transform(item.Matrix);

                    if (union)
                    {
                        resultsVertexSource = resultsVertexSource.Union(itemVertexSource);
                    }
                    else
                    {
                        resultsVertexSource = resultsVertexSource.MergePaths(itemVertexSource, ClipperLib.ClipType.ctIntersection);
                    }

                    percentCompleted           += amountPerOperation;
                    progressStatus.Progress0To1 = percentCompleted;
                    reporter?.Report(progressStatus);
                }
            }

            this.VertexSource = resultsVertexSource;

            SourceContainer.Visible = false;
        }
Example #14
0
        protected virtual IEnumerable <TDomainModel> GetSourceDocuments()
        {
            if (PageSize > 0)
            {
                var pageReadingOptions = SourceContainer.Resolve <PageReadingOptions>();
                pageReadingOptions.PageSize = PageSize;
            }

            return(SourceContainer.Resolve <IDomainModelContext>().GetAll <TDomainModel>());
        }
        public override Task Rebuild()
        {
            this.DebugDepth("Rebuild");

            var rebuildLocks = this.RebuilLockAll();

            var valuesChanged = false;

            return(TaskBuilder(
                       "Find Slice".Localize(),
                       (reporter, cancellationToken) =>
            {
                var polygons = new Polygons();
                VertexSource = polygons.PolygonToPathStorage();

                var newChildren = new List <Object3D>();
                foreach (var sourceItem in SourceContainer.VisibleMeshes())
                {
                    var meshPolygons = Cut(sourceItem);

                    polygons = polygons.CreateUnion(meshPolygons.polygons);

                    var newMesh = new Object3D()
                    {
                        Mesh = meshPolygons.mesh,
                        OwnerID = sourceItem.ID
                    };
                    newMesh.CopyProperties(sourceItem, Object3DPropertyFlags.All);
                    newChildren.Add(newMesh);
                }

                VertexSource = polygons.PolygonToPathStorage();

                RemoveAllButSource();
                SourceContainer.Visible = false;
                foreach (var child in newChildren)
                {
                    this.Children.Add(child);
                }

                UiThread.RunOnIdle(() =>
                {
                    rebuildLocks.Dispose();
                    if (valuesChanged)
                    {
                        Invalidate(InvalidateType.DisplayValues);
                    }
                    Parent?.Invalidate(new InvalidateArgs(this, InvalidateType.Children));
                });

                return Task.CompletedTask;
            }));
        }
Example #16
0
        public void DrawEditor(Object3DControlsLayer layer, List <Object3DView> transparentMeshes, DrawEventArgs e)
        {
            var sourceAabb     = this.SourceContainer.GetAxisAlignedBoundingBox();
            var rotationCenter = SourceContainer.GetSmallestEnclosingCircleAlongZ().Center + RotationOffset;

            var center = new Vector3(rotationCenter.X, rotationCenter.Y, sourceAabb.Center.Z);

            // render the top and bottom rings
            layer.World.RenderCylinderOutline(this.WorldMatrix(), center, 1, sourceAabb.ZSize, 15, Color.Red, Color.Red, 5);

            // turn the lighting back on
            GL.Enable(EnableCap.Lighting);
        }
        public override Task Rebuild()
        {
            this.DebugDepth("Rebuild");

            var rebuildLocks = this.RebuilLockAll();

            var valuesChanged = false;

            return(TaskBuilder(
                       "Plane Cut".Localize(),
                       (reporter, cancellationToken) =>
            {
                var newChildren = new List <Object3D>();
                var root = SourceContainer.Children.First();
                root = root == null ? SourceContainer : root;
                foreach (var sourceItem in SourceContainer.VisibleMeshes())
                {
                    var reducedMesh = Cut(sourceItem);

                    var newMesh = new Object3D()
                    {
                        Mesh = reducedMesh,
                        OwnerID = sourceItem.ID
                    };
                    newMesh.CopyWorldProperties(sourceItem, root, Object3DPropertyFlags.All);
                    newChildren.Add(newMesh);
                }

                var sourceContainer = SourceContainer;
                this.Children.Modify(list =>
                {
                    list.Clear();
                    list.Add(sourceContainer);
                    foreach (var child in newChildren)
                    {
                        list.Add(child);
                    }
                    sourceContainer.Visible = false;
                });

                UiThread.RunOnIdle(() =>
                {
                    rebuildLocks.Dispose();
                    Invalidate(InvalidateType.DisplayValues);
                    Parent?.Invalidate(new InvalidateArgs(this, InvalidateType.Children));
                });

                return Task.CompletedTask;
            }));
        }
Example #18
0
 public void Clear()
 {
     foreach (var kvp in copySlots)
     {
         caches.Put(kvp.Value);
     }
     if (SourceContainer != null)
     {
         SourceContainer.MarkIf(null);
     }
     copySlots.Clear();
     selectedItems.Clear();
     ZetanUtility.SetActive(tips, true);
     WindowsManager.CloseWindow <ItemWindow>();
 }
Example #19
0
        private async void releases_releaseSourcesButton_Click(object sender, EventArgs e)
        {
            ReleaseSources api = new ReleaseSources {
                ApiKey = apiKey
            };

            api.Arguments.release_id = 51;
            if (fredValidationButton.Checked)
            {
                api.Arguments.Validators.Clear();
            }
            SourceContainer container = syncButton.Checked ? api.Fetch() : await api.FetchAsync();

            ShowResults(api);
        }
Example #20
0
        private async void sources_sourceButton_Click(object sender, EventArgs e)
        {
            Source api = new Source()
            {
                ApiKey = apiKey
            };

            api.Arguments.source_id = 1;
            if (fredValidationButton.Checked)
            {
                api.Arguments.Validators.Clear();
            }
            SourceContainer container = syncButton.Checked ? api.Fetch() : await api.FetchAsync();

            ShowResults(api);
        }
Example #21
0
        public override Task Rebuild()
        {
            this.DebugDepth("Rebuild");

            var rebuildLocks = this.RebuilLockAll();

            var valuesChanged = false;

            return(TaskBuilder(
                       "Reduce".Localize(),
                       (reporter, cancellationToken) =>
            {
                var newChildren = new List <Object3D>();
                foreach (var sourceItem in SourceContainer.VisibleMeshes())
                {
                    var originalMesh = sourceItem.Mesh;
                    var reducedMesh = Cut(originalMesh);

                    var newMesh = new Object3D()
                    {
                        Mesh = reducedMesh,
                        OwnerID = sourceItem.ID
                    };
                    newMesh.CopyProperties(sourceItem, Object3DPropertyFlags.All);
                    newChildren.Add(newMesh);
                }

                RemoveAllButSource();
                SourceContainer.Visible = false;
                foreach (var child in newChildren)
                {
                    this.Children.Add(child);
                }

                rebuildLocks.Dispose();

                if (valuesChanged)
                {
                    Invalidate(InvalidateType.DisplayValues);
                }

                Parent?.Invalidate(new InvalidateArgs(this, InvalidateType.Children));

                return Task.CompletedTask;
            }));
        }
Example #22
0
    private void TakeOut(ItemSlot copy, bool all = false)
    {
        if (!copy.IsEmpty)
        {
            if (all || copy.Data.amount < 2)
            {
                RemoveSlot(copy);
            }
            else
            {
                AmountWindow.StartInput((amount) =>
                {
                    if (copy.Data.amount < amount)
                    {
                        MessageManager.Instance.New("物品数量已改变,请重试");
                    }
                    else
                    {
                        copy.Data.amount -= (int)amount;
                        if (copy.Data.amount < 1)
                        {
                            RemoveSlot(copy);
                        }
                        else
                        {
                            copy.Refresh();
                        }
                    }
                }, copy.Data.amount, "取出数量");
            }
        }

        void RemoveSlot(ItemSlot copy)
        {
            copySlots.Remove(copy.Item.ID);
            caches.Put(copy);
            selectedItems.Remove(copy.Item);
            SourceContainer.MarkIf(s => selectedItems.Contains(s.Item));
            if (copySlots.Count < 1)
            {
                ZetanUtility.SetActive(tips, true);
            }
        }
    }
Example #23
0
        public override Task Rebuild()
        {
            this.DebugDepth("Rebuild");

            var rebuildLocks = this.RebuilLockAll();

            var valuesChanged = false;

            // check if we have be initialized

            return(TaskBuilder(
                       "Repair".Localize(),
                       (reporter, cancellationToken) =>
            {
                SourceContainer.Visible = true;
                RemoveAllButSource();

                foreach (var sourceItem in SourceContainer.VisibleMeshes())
                {
                    var originalMesh = sourceItem.Mesh;
                    var reducedMesh = Repair(originalMesh, cancellationToken);

                    var newMesh = new Object3D()
                    {
                        Mesh = reducedMesh
                    };
                    newMesh.CopyProperties(sourceItem, Object3DPropertyFlags.All);
                    this.Children.Add(newMesh);
                }

                SourceContainer.Visible = false;
                rebuildLocks.Dispose();

                if (valuesChanged)
                {
                    Invalidate(InvalidateType.DisplayValues);
                }

                Parent?.Invalidate(new InvalidateArgs(this, InvalidateType.Children));

                return Task.CompletedTask;
            }));
        }
        public override Task Rebuild()
        {
            this.DebugDepth("Rebuild");

            var rebuildLocks = this.RebuilLockAll();

            var valuesChanged = false;

            return(TaskBuilder(
                       "Hollow".Localize(),
                       (reporter, cancellationToken) =>
            {
                SourceContainer.Visible = true;
                RemoveAllButSource();

                foreach (var sourceItem in SourceContainer.VisibleMeshes())
                {
                    var newMesh = new Object3D()
                    {
                        Mesh = HollowOut(sourceItem.Mesh, this.Distance, this.NumCells)
                    };
                    newMesh.CopyProperties(sourceItem, Object3DPropertyFlags.All);
                    this.Children.Add(newMesh);
                }

                SourceContainer.Visible = false;

                UiThread.RunOnIdle(() =>
                {
                    rebuildLocks.Dispose();
                    if (valuesChanged)
                    {
                        Invalidate(InvalidateType.DisplayValues);
                    }
                    Parent?.Invalidate(new InvalidateArgs(this, InvalidateType.Children));
                });

                return Task.CompletedTask;
            }));
        }
Example #25
0
        private void Combine(CancellationToken cancellationToken, IProgress <ProgressStatus> reporter)
        {
            SourceContainer.Visible = true;
            RemoveAllButSource();

            var participants = SourceContainer.VisibleMeshes();

            if (participants.Count() < 2)
            {
                if (participants.Count() == 1)
                {
                    var newMesh = new Object3D();
                    newMesh.CopyProperties(participants.First(), Object3DPropertyFlags.All);
                    newMesh.Mesh = participants.First().Mesh;
                    this.Children.Add(newMesh);
                    SourceContainer.Visible = false;
                }

                return;
            }

            var items       = participants.Select(i => (i.Mesh, i.WorldMatrix(SourceContainer)));
            var resultsMesh = BooleanProcessing.DoArray(items,
                                                        BooleanProcessing.CsgModes.Union,
                                                        Processing,
                                                        InputResolution,
                                                        OutputResolution,
                                                        reporter,
                                                        cancellationToken);

            var resultsItem = new Object3D()
            {
                Mesh = resultsMesh
            };

            resultsItem.CopyProperties(participants.First(), Object3DPropertyFlags.All & (~Object3DPropertyFlags.Matrix));
            this.Children.Add(resultsItem);
            SourceContainer.Visible = false;
        }
        protected override IEnumerable <ResultFile> GetSourceDocuments()
        {
            var       fileSession = SourceContainer.Resolve <IAsyncFilesSession>();
            const int size        = 1024;
            var       page        = 0;

            var query = fileSession.Query().OnDirectory("scenarioresults", true).Take(size);
            FilesQueryStatistics stats = null;

            do
            {
                var source = query.Skip(page * size);
                source = page == 0 ? source.Statistics(out stats) : source;
                foreach (var item in source.ToListAsync().Result)
                {
                    var scenarioDir = Path.GetFileName(item.Directory);
                    if (scenarioDir != null && Guid.TryParse(scenarioDir, out var scenarioId))
                    {
                        using (var stream = fileSession.DownloadAsync(item).Result)
                            using (var contentStream = new MemoryStream())
                            {
                                stream.CopyTo(contentStream);
                                yield return(new ResultFile
                                {
                                    ScenarioId = scenarioId,
                                    FileId = Path.GetFileNameWithoutExtension(item.Name),
                                    IsCompressed =
                                        item.Extension?.Equals(".zip", StringComparison.InvariantCultureIgnoreCase) ??
                                        false,
                                    Content = contentStream.ToArray()
                                });
                            }
                    }
                }
                page++;
            } while (page * size <= (stats?.TotalResults ?? 0));
        }
Example #27
0
        public override Task Rebuild()
        {
            this.DebugDepth("Rebuild");

            bool valuesChanged = false;

            // ensure we have good values
            StartPercent = agg_basics.Clamp(StartPercent, 0, 100, ref valuesChanged);

            if (Diameter < 1 || Diameter > 100000)
            {
                if (Diameter == double.MaxValue)
                {
                    var aabb = this.GetAxisAlignedBoundingBox();
                    // uninitialized set to a reasonable value
                    Diameter = (int)aabb.XSize;
                }

                Diameter      = Math.Min(100000, Math.Max(1, Diameter));
                valuesChanged = true;
            }

            MinSidesPerRotation = agg_basics.Clamp(MinSidesPerRotation, 3, 360, ref valuesChanged);

            var rebuildLocks = this.RebuilLockAll();

            return(ApplicationController.Instance.Tasks.Execute(
                       "Curve".Localize(),
                       null,
                       (reporter, cancellationToken) =>
            {
                var sourceAabb = this.SourceContainer.GetAxisAlignedBoundingBox();

                var radius = Diameter / 2;
                var circumference = MathHelper.Tau * radius;
                double numRotations = sourceAabb.XSize / circumference;
                double numberOfCuts = numRotations * MinSidesPerRotation;
                double cutSize = sourceAabb.XSize / numberOfCuts;
                double cutPosition = sourceAabb.MinXYZ.X + cutSize;
                var cuts = new List <double>();
                for (int i = 0; i < numberOfCuts; i++)
                {
                    cuts.Add(cutPosition);
                    cutPosition += cutSize;
                }

                var rotationCenter = new Vector3(sourceAabb.MinXYZ.X + (sourceAabb.MaxXYZ.X - sourceAabb.MinXYZ.X) * (StartPercent / 100),
                                                 BendCcw ? sourceAabb.MaxXYZ.Y + radius : sourceAabb.MinXYZ.Y - radius,
                                                 sourceAabb.Center.Z);

                var curvedChildren = new List <IObject3D>();

                var status = new ProgressStatus();

                foreach (var sourceItem in SourceContainer.VisibleMeshes())
                {
                    var originalMesh = sourceItem.Mesh;
                    status.Status = "Copy Mesh".Localize();
                    reporter.Report(status);
                    var transformedMesh = originalMesh.Copy(CancellationToken.None);
                    var itemMatrix = sourceItem.WorldMatrix(SourceContainer);

                    // transform into this space
                    transformedMesh.Transform(itemMatrix);

                    if (SplitMesh)
                    {
                        status.Status = "Split Mesh".Localize();
                        reporter.Report(status);

                        // split the mesh along the x axis
                        transformedMesh.SplitOnPlanes(Vector3.UnitX, cuts, cutSize / 8);
                    }

                    for (int i = 0; i < transformedMesh.Vertices.Count; i++)
                    {
                        var position = transformedMesh.Vertices[i];

                        var angleToRotate = ((position.X - rotationCenter.X) / circumference) * MathHelper.Tau - MathHelper.Tau / 4;
                        var distanceFromCenter = rotationCenter.Y - position.Y;
                        if (!BendCcw)
                        {
                            angleToRotate = -angleToRotate;
                            distanceFromCenter = -distanceFromCenter;
                        }

                        var rotatePosition = new Vector3Float(Math.Cos(angleToRotate), Math.Sin(angleToRotate), 0) * distanceFromCenter;
                        rotatePosition.Z = position.Z;
                        transformedMesh.Vertices[i] = rotatePosition + new Vector3Float(rotationCenter.X, radius + sourceAabb.MaxXYZ.Y, 0);
                    }

                    // transform back into item local space
                    transformedMesh.Transform(Matrix4X4.CreateTranslation(-rotationCenter) * itemMatrix.Inverted);

                    if (SplitMesh)
                    {
                        status.Status = "Merge Vertices".Localize();
                        reporter.Report(status);

                        transformedMesh.MergeVertices(.1);
                    }

                    transformedMesh.CalculateNormals();

                    var curvedChild = new Object3D()
                    {
                        Mesh = transformedMesh
                    };
                    curvedChild.CopyWorldProperties(sourceItem, SourceContainer, Object3DPropertyFlags.All, false);
                    curvedChild.Visible = true;
                    curvedChild.Translate(new Vector3(rotationCenter));
                    if (!BendCcw)
                    {
                        curvedChild.Translate(0, -sourceAabb.YSize - Diameter, 0);
                    }

                    curvedChildren.Add(curvedChild);
                }

                RemoveAllButSource();
                this.SourceContainer.Visible = false;

                this.Children.Modify((list) =>
                {
                    list.AddRange(curvedChildren);
                });

                UiThread.RunOnIdle(() =>
                {
                    rebuildLocks.Dispose();
                    if (valuesChanged)
                    {
                        Invalidate(InvalidateType.DisplayValues);
                    }
                    Parent?.Invalidate(new InvalidateArgs(this, InvalidateType.Children));
                });

                return Task.CompletedTask;
            }));
        }
Example #28
0
        public override Task Rebuild()
        {
            this.DebugDepth("Rebuild");

            bool valuesChanged = false;

            if (Angle < 1 || Angle > 100000)
            {
                Angle         = Math.Min(100000, Math.Max(1, Angle));
                valuesChanged = true;
            }

            if (RotationDistance < 0 || RotationDistance > 100000)
            {
                RotationDistance = Math.Min(100000, Math.Max(0, RotationDistance));
                valuesChanged    = true;
            }

            if (RotationSlices < 3 || RotationSlices > 300)
            {
                RotationSlices = Math.Min(300, Math.Max(3, RotationSlices));
                valuesChanged  = true;
            }

            if (EndHeightPercent < 1 || EndHeightPercent > 100)
            {
                EndHeightPercent = Math.Min(100, Math.Max(1, EndHeightPercent));
                valuesChanged    = true;
            }

            if (StartHeightPercent < 0 || StartHeightPercent > EndHeightPercent - 1)
            {
                StartHeightPercent = Math.Min(EndHeightPercent - 1, Math.Max(0, StartHeightPercent));
                valuesChanged      = true;
            }

            if (OverrideRadius < .01)
            {
                OverrideRadius = Math.Max(this.GetAxisAlignedBoundingBox().XSize, this.GetAxisAlignedBoundingBox().YSize);
                valuesChanged  = true;
            }

            var rebuildLocks = this.RebuilLockAll();

            return(ApplicationController.Instance.Tasks.Execute(
                       "Twist".Localize(),
                       null,
                       (reporter, cancellationToken) =>
            {
                var sourceAabb = this.SourceContainer.GetAxisAlignedBoundingBox();

                var bottom = sourceAabb.MinXYZ.Z;
                var top = sourceAabb.ZSize * EndHeightPercent / 100.0;
                var size = sourceAabb.ZSize;
                if (Advanced)
                {
                    bottom += sourceAabb.ZSize * StartHeightPercent / 100.0;
                    size = top - bottom;
                }

                double numberOfCuts = RotationSlices;

                double cutSize = size / numberOfCuts;
                var cuts = new List <double>();
                for (int i = 0; i < numberOfCuts + 1; i++)
                {
                    var ratio = i / numberOfCuts;
                    if (Advanced)
                    {
                        var goal = ratio;
                        var current = .5;
                        var next = .25;
                        // look for an x value that equals the goal
                        for (int j = 0; j < 64; j++)
                        {
                            var xAtY = Easing.Specify(EasingType, EasingOption, current);
                            if (xAtY < goal)
                            {
                                current += next;
                            }
                            else if (xAtY > goal)
                            {
                                current -= next;
                            }

                            next *= .5;
                        }

                        ratio = current;
                    }

                    cuts.Add(bottom - cutSize + (size * ratio));
                }

                // get the rotation from the center of the circumscribed circle of the convex hull
                var enclosingCircle = SourceContainer.GetSmallestEnclosingCircleAlongZ();
                var rotationCenter = enclosingCircle.Center + RotationOffset;

                var twistedChildren = new List <IObject3D>();

                var status = new ProgressStatus();

                foreach (var sourceItem in SourceContainer.VisibleMeshes())
                {
                    var originalMesh = sourceItem.Mesh;
                    status.Status = "Copy Mesh".Localize();
                    reporter.Report(status);
                    var transformedMesh = originalMesh.Copy(CancellationToken.None);
                    var itemMatrix = sourceItem.WorldMatrix(SourceContainer);

                    // transform into this space
                    transformedMesh.Transform(itemMatrix);

                    status.Status = "Split Mesh".Localize();
                    reporter.Report(status);

                    // split the mesh along the z axis
                    transformedMesh.SplitOnPlanes(Vector3.UnitZ, cuts, cutSize / 8);

                    for (int i = 0; i < transformedMesh.Vertices.Count; i++)
                    {
                        var position = transformedMesh.Vertices[i];

                        var ratio = (position.Z - bottom) / size;

                        if (Advanced)
                        {
                            if (position.Z < bottom)
                            {
                                ratio = 0;
                            }
                            else if (position.Z > top)
                            {
                                ratio = 1;
                            }
                            else
                            {
                                ratio = (position.Z - bottom) / size;
                                ratio = Easing.Specify(EasingType, EasingOption, ratio);
                            }
                        }

                        var angleToRotate = ratio * Angle / 360.0 * MathHelper.Tau;
                        if (RotationType == RotationTypes.Distance)
                        {
                            IRadiusProvider radiusProvider = RadiusProvider;

                            // start off with assuming we want to set the radius
                            var radius = this.OverrideRadius;
                            if (radiusProvider != null && !this.EditRadius)
                            {
                                // have a radius provider and not wanting to edit
                                radius = radiusProvider.Radius;
                            }
                            else if (!this.EditRadius)
                            {
                                // not wanting to edit
                                radius = enclosingCircle.Radius;
                            }

                            if (this.PreferedRadius != radius)
                            {
                                this.PreferedRadius = radius;
                                this.OverrideRadius = radius;
                                UiThread.RunOnIdle(() => Invalidate(InvalidateType.DisplayValues));
                            }

                            angleToRotate = ratio * (RotationDistance / radius);
                        }

                        if (!TwistCw)
                        {
                            angleToRotate = -angleToRotate;
                        }

                        var positionXy = new Vector2(position) - rotationCenter;
                        positionXy.Rotate(angleToRotate);
                        positionXy += rotationCenter;
                        transformedMesh.Vertices[i] = new Vector3Float(positionXy.X, positionXy.Y, position.Z);
                    }

                    // transform back into item local space
                    transformedMesh.Transform(itemMatrix.Inverted);

                    //transformedMesh.MergeVertices(.1);
                    transformedMesh.CalculateNormals();

                    var twistedChild = new Object3D()
                    {
                        Mesh = transformedMesh
                    };
                    twistedChild.CopyWorldProperties(sourceItem, SourceContainer, Object3DPropertyFlags.All, false);
                    twistedChild.Visible = true;

                    twistedChildren.Add(twistedChild);
                }

                RemoveAllButSource();
                this.SourceContainer.Visible = false;

                this.Children.Modify((list) =>
                {
                    list.AddRange(twistedChildren);
                });

                rebuildLocks.Dispose();

                if (valuesChanged)
                {
                    Invalidate(InvalidateType.DisplayValues);
                }

                Parent?.Invalidate(new InvalidateArgs(this, InvalidateType.Children));

                return Task.CompletedTask;
            }));
        }
Example #29
0
        private void SubtractAndReplace(CancellationToken cancellationToken, IProgress <ProgressStatus> reporter)
        {
            SourceContainer.Visible = true;
            RemoveAllButSource();

            var parentOfPaintTargets = SourceContainer.DescendantsAndSelfMultipleChildrenFirstOrSelf();

            if (parentOfPaintTargets.Children.Count() < 2)
            {
                if (parentOfPaintTargets.Children.Count() == 1)
                {
                    this.Children.Add(SourceContainer.Clone());
                    SourceContainer.Visible = false;
                }

                return;
            }

            SubtractObject3D_2.CleanUpSelectedChildrenNames(this);

            var paintObjects = parentOfPaintTargets.Children
                               .Where((i) => SelectedChildren
                                      .Contains(i.ID))
                               .SelectMany(c => c.VisibleMeshes())
                               .ToList();

            var keepItems = parentOfPaintTargets.Children
                            .Where((i) => !SelectedChildren
                                   .Contains(i.ID));

            var keepVisibleItems = keepItems.SelectMany(c => c.VisibleMeshes()).ToList();

            if (paintObjects.Any() &&
                keepVisibleItems.Any())
            {
                var    totalOperations    = paintObjects.Count * keepVisibleItems.Count;
                double amountPerOperation = 1.0 / totalOperations;
                double percentCompleted   = 0;

                var progressStatus = new ProgressStatus
                {
                    Status = "Do CSG"
                };

                foreach (var keep in keepVisibleItems)
                {
                    var keepResultsMesh = keep.Mesh;
                    var keepWorldMatrix = keep.WorldMatrix(SourceContainer);

                    foreach (var paint in paintObjects)
                    {
                        Mesh paintMesh = BooleanProcessing.Do(keepResultsMesh,
                                                              keepWorldMatrix,
                                                              // paint data
                                                              paint.Mesh,
                                                              paint.WorldMatrix(SourceContainer),
                                                              // operation type
                                                              2,
                                                              // reporting data
                                                              reporter,
                                                              amountPerOperation,
                                                              percentCompleted,
                                                              progressStatus,
                                                              cancellationToken);

                        keepResultsMesh = BooleanProcessing.Do(keepResultsMesh,
                                                               keepWorldMatrix,
                                                               // point data
                                                               paint.Mesh,
                                                               paint.WorldMatrix(SourceContainer),
                                                               // operation type
                                                               1,
                                                               // reporting data
                                                               reporter,
                                                               amountPerOperation,
                                                               percentCompleted,
                                                               progressStatus,
                                                               cancellationToken);

                        // after the first time we get a result the results mesh is in the right coordinate space
                        keepWorldMatrix = Matrix4X4.Identity;

                        // store our intersection (paint) results mesh
                        var paintResultsItem = new Object3D()
                        {
                            Mesh    = paintMesh,
                            Visible = false,
                            OwnerID = paint.ID
                        };
                        // copy all the properties but the matrix
                        paintResultsItem.CopyWorldProperties(paint, SourceContainer, Object3DPropertyFlags.All & (~(Object3DPropertyFlags.Matrix | Object3DPropertyFlags.Visible)));
                        // and add it to this
                        this.Children.Add(paintResultsItem);

                        // report our progress
                        percentCompleted           += amountPerOperation;
                        progressStatus.Progress0To1 = percentCompleted;
                        reporter?.Report(progressStatus);
                    }

                    // store our results mesh
                    var keepResultsItem = new Object3D()
                    {
                        Mesh    = keepResultsMesh,
                        Visible = false,
                        OwnerID = keep.ID
                    };
                    // copy all the properties but the matrix
                    keepResultsItem.CopyWorldProperties(keep, SourceContainer, Object3DPropertyFlags.All & (~(Object3DPropertyFlags.Matrix | Object3DPropertyFlags.Visible)));
                    // and add it to this
                    this.Children.Add(keepResultsItem);
                }

                foreach (var child in Children)
                {
                    child.Visible = true;
                }

                SourceContainer.Visible = false;
            }
        }
Example #30
0
        public override Task Rebuild()
        {
            this.DebugDepth("Rebuild");

            var rebuildLocks = this.RebuilLockAll();

            return(ApplicationController.Instance.Tasks.Execute(
                       "Pinch".Localize(),
                       null,
                       (reporter, cancellationToken) =>
            {
                SourceContainer.Visible = true;
                RemoveAllButSource();

                // remember the current matrix then clear it so the parts will rotate at the original wrapped position
                var currentMatrix = Matrix;
                Matrix = Matrix4X4.Identity;

                var aabb = SourceContainer.GetAxisAlignedBoundingBox();

                bool valuesChanged = false;

                PinchPercent = agg_basics.Clamp(PinchPercent, 0, 3, ref valuesChanged);

                foreach (var sourceItem in SourceContainer.VisibleMeshes())
                {
                    var originalMesh = sourceItem.Mesh;
                    var transformedMesh = originalMesh.Copy(CancellationToken.None);
                    var itemMatrix = sourceItem.WorldMatrix(SourceContainer);
                    var invItemMatrix = itemMatrix.Inverted;

                    for (int i = 0; i < originalMesh.Vertices.Count; i++)
                    {
                        var pos = originalMesh.Vertices[i];
                        pos = pos.Transform(itemMatrix);

                        var ratioToApply = PinchPercent / 100.0;

                        var distFromCenter = pos.X - aabb.Center.X;
                        var distanceToPinch = distFromCenter * (1 - ratioToApply);
                        var delta = (aabb.Center.X + distFromCenter * ratioToApply) - pos.X;

                        // find out how much to pinch based on y position
                        var amountOfRatio = (pos.Y - aabb.MinXYZ.Y) / aabb.YSize;

                        var newPos = new Vector3Float(pos.X + delta * amountOfRatio, pos.Y, pos.Z);

                        transformedMesh.Vertices[i] = newPos.Transform(invItemMatrix);
                    }

                    transformedMesh.CalculateNormals();

                    var newMesh = new Object3D()
                    {
                        Mesh = transformedMesh
                    };
                    newMesh.CopyWorldProperties(sourceItem, this, Object3DPropertyFlags.All, false);
                    this.Children.Add(newMesh);
                }

                // set the matrix back
                Matrix = currentMatrix;
                SourceContainer.Visible = false;
                rebuildLocks.Dispose();

                if (valuesChanged)
                {
                    Invalidate(InvalidateType.DisplayValues);
                }

                Invalidate(InvalidateType.Children);
                return Task.CompletedTask;
            }));
        }