Esempio n. 1
0
        public void MarkDirty(IHaveCells target, bool allowMultiple = false)
        {
            // TODO Lock or use thread-safe collections
            // Because notify can be parallel
            var dirties = this.dirties[CurrentCellIndex];

            lock (dirties) // TODO Better use a thread-safe collection to reduce blocking
            {
                var dirty = dirties.Find(it => ReferenceEquals(it.Inner, target));
                if (dirty == null)
                {
                    dirty = new Dirty
                    {
                        Phase = 1,
                        Inner = target,
                    };
                    dirties.Add(dirty);
                }
                else if (dirty.Phase == 1)
                {
                    if (!allowMultiple)
                    {
                        throw new InvalidOperationException("Cannot mark dirty for same target twice in same run");
                    }
                }
                else if (dirty.Phase >= 2 && dirty.Phase <= 4)
                {
                    dirty.Phase = 1;
                }
                else
                {
                    throw new NotImplementedException(dirty.Phase.ToString());
                }
            }
        }
Esempio n. 2
0
 public void Draw(Rect canvas)
 {
     if (UiHelper.LabeledPaintableCheckbox(canvas, _stuffText, ref _state))
     {
         Dirty.Set(true);
     }
 }
Esempio n. 3
0
        public override bool Save()
        {
            var columns = new List <PropertyInfo>();

            while (Dirty.TryTake(out var e))
            {
                columns.Add(e);
            }

            try
            {
                if (Target is IEntity <int> ei && ei.Id < 0)
                {
                    var t = _data.Add <T>(e => Target.CopyPrimitivesTo(e));
                    ei.Id = (int)t.Id;
                    return(true);
                }
                if (_data.Update(Target, columns.Select(e => e.Name).ToArray()))
                {
                    IsDirty = false;
                    return(true);
                }
                return(false);
            }
            catch
            {
                foreach (var p in columns)
                {
                    Dirty.Add(p);
                }
                throw;
            }
        }
 static void Main(string[] args)
 {
     _Integer = new Dirty <int>(10);
     Console.WriteLine("Dirty: {0}, value: {1}", _Integer.IsDirty, Integer);
     Integer = 15;
     Console.WriteLine("Dirty: {0}, value: {1}", _Integer.IsDirty, Integer);
 }
Esempio n. 5
0
        public void MarkDirty(IHaveCells target, bool allowMultiple = false)
        {
            var dirties = this.dirties[CurrentCellIndex];

            lock (dirties) // TODO Better use a thread-safe collection to reduce blocking
            {
                var dirty = dirties.Find(it => ReferenceEquals(it.Inner, target));
                // TODO If use thread-safe collection, should lock on dirty too
                // at least in debug mode, to avoid accidentally using 2 threads to write to same
                if (dirty == null)
                {
                    dirty = new Dirty
                    {
                        Phase = 1,
                        Inner = target,
                    };
                    dirties.Add(dirty);
                }
                else if (dirty.Phase == 1)
                {
                    if (!allowMultiple)
                    {
                        throw new InvalidOperationException("Cannot mark dirty for same target twice in same run");
                    }
                }
                else if (dirty.Phase >= 2 && dirty.Phase <= 4)
                {
                    dirty.Phase = 1;
                }
                else
                {
                    throw new NotImplementedException(dirty.Phase.ToString());
                }
            }
        }
Esempio n. 6
0
    public void SetDirty(Dirty dirty, Action updateCall)
    {
        switch (dirty)
        {
        case Dirty.RequireUpdate:
            if (IsDirty == false)
            {
                m_UpdateCoroutine = Core.Start(implCleanUpdate(updateCall));
            }
            break;

        case Dirty.FixedUpdate:
            if (IsDirty == false)
            {
                m_UpdateCoroutine = Core.Start(implWaitFixedUpdateAndDo(updateCall));
            }
            break;

        case Dirty.Clean:
        case Dirty.Dirty:
        case Dirty.None:
            implStopUpdate();
            break;
        }

        m_CurrentState = dirty;
    }
Esempio n. 7
0
        private void LazyComputeConvexPartitions()
        {
            if (_dirty.HasFlag(Dirty.ConvexPartitions))
            {
                // Clear previous list (just to be safe)
                _convexPartitions = new List <Vector[]>();

                if (IsConvex)
                {
                    // Create the convex mimic from this polygon
                    _convexPartitions.Add(_vertices.ToArray());
                }
                else
                {
                    // Compute fragments
                    foreach (var indices in PolygonTools.DecomposeConvexIndices(_vertices))
                    {
                        // Create a convex fragment from this polygon
                        var vertices = indices.Select(i => _vertices[i]);
                        _convexPartitions.Add(vertices.ToArray());
                    }
                }

                _dirty &= ~Dirty.ConvexPartitions;
            }
        }
Esempio n. 8
0
 private void LazyComputeMetrics()
 {
     if (_dirty.HasFlag(Dirty.Metrics))
     {
         PolygonTools.ComputeMetrics(_vertices, out _area, out _center, out _centroid);
         _dirty &= ~Dirty.Metrics;
     }
 }
Esempio n. 9
0
 private void LazyComputeConvexStatus()
 {
     if (_dirty.HasFlag(Dirty.IsConvex))
     {
         _isConvex = PolygonTools.IsConvexPolygon(_vertices);
         _dirty   &= ~Dirty.IsConvex;
     }
 }
Esempio n. 10
0
        public async Task <bool> SaveAsync(IDataTransaction transaction)
        {
            var columns = new List <PropertyInfo>();

            while (Dirty.TryTake(out var e))
            {
                columns.Add(e);
            }

            IDataTransaction tr = null;

            try
            {
                tr = transaction ?? _data.GetTransaction();

                if (Target is IEntity <int> ei && ei.Id < 0)
                {
                    var t = await tr.AddAsync <T>(e => Target.CopyPrimitivesTo(e));

                    if (transaction == null)
                    {
                        tr.Done();
                    }
                    ei.Id = (int)t.Id;
                    return(true);
                }

                if (await tr.UpdateAsync(Target, columns.Select(GetColumnName)))
                {
                    if (transaction == null)
                    {
                        tr.Done();
                    }

                    IsDirty = false;
                    return(true);
                }

                return(false);
            }
            catch (Exception ex)
            {
                foreach (var p in columns)
                {
                    Dirty.Add(p);
                }

                throw new DataException("Save failure", ex);
            }
            finally
            {
                if (transaction == null)
                {
                    tr?.Dispose();
                }
            }
        }
Esempio n. 11
0
 private void LazyComputeBounds()
 {
     if (_dirty.HasFlag(Dirty.Bounds))
     {
         // Lazy evaluation of bounds
         _bounds = Rectangle.FromPoints(_vertices);
         _dirty &= ~Dirty.Bounds;
     }
 }
Esempio n. 12
0
        private void BtnDbConfig_Click(object sender, EventArgs e)
        {
            Dirty deleg = SetLogicDirty;

            using (var dialog = new FormSettings(deleg))
            {
                dialog.ShowDialog(this);
            }
            return;
        }
Esempio n. 13
0
        public void RegisterDirty(TModel e)
        {
            TIdentity id = createIdentity(e);

            if (!All.ContainsKey(id))
            {
                return;
            }

            if (!Removed.Contains(e) && !Dirty.Contains(e))
            {
                Dirty.Add(e);
            }
        }
Esempio n. 14
0
 public void RefreshAssets()
 {
     // Copies the Dirty hash set with ToHashSet so that if another thread changes Dirty, it doesn't mess up this loop
     foreach (string assetName in Dirty)
     {
         // If this asset hasn't failed to refresh and it's been loaded and it successfully merges (will attempt to load only if the other two are true)
         if (!Failed.Contains(assetName) && Assets.ContainsKey(assetName) && !this.Merge(assetName, Originals.GetDefault(assetName, null)))
         {
             ModEntry.INSTANCE.Monitor.Log($"Failed to merge {assetName}. Will not try to merge it again.", LogLevel.Warn);
             Failed.Add(assetName);
         }
     }
     Dirty.Clear();
 }
Esempio n. 15
0
        void ChangeOverlay(byte x, byte y, ushort value)
        {
            var index = Index(x, y);

            if (index < 0 || index >= _mapData.Overlay.Length)
            {
                CoreUtil.LogError($"Tried to update invalid overlay index {index} (max {_mapData.Overlay.Length}");
            }
            else
            {
                _mapData.Overlay[Index(x, y)] = value;
                Dirty?.Invoke(this, new DirtyTileEventArgs(x, y, IconChangeType.Overlay));
            }
        }
Esempio n. 16
0
        public override string ToString()
        {
            var columns = Dirty.ToList();
            var sb      = new StringBuilder();

            foreach (var p in columns)
            {
                sb
                .Append(p.Name)
                .Append("=")
                .Append(p.GetValue(Target)?.ToString() ?? "null")
                .Append("\n");
            }
            return(sb.ToString());
        }
Esempio n. 17
0
        //public void RegisterClean(TModel e)
        //{
        //    Dirty.Remove(e);
        //}

        public TModel RegisterRemoved(TModel e)
        {
            if (New.Remove(e))
            {
                return(e);
            }

            Dirty.Remove(e);
            if (!Removed.Contains(e))
            {
                Removed.Add(e);
            }

            return(e);
        }
Esempio n. 18
0
        private void LazyComputeNormals()
        {
            if (_dirty.HasFlag(Dirty.Normals))
            {
                _normals.Clear();

                // Compute normals
                for (var i = 0; i < Vertices.Count; i++)
                {
                    var normal = PolygonTools.GetNormal(_vertices, i);
                    _normals.Add(normal);
                }

                _dirty &= ~Dirty.Normals;
            }
        }
Esempio n. 19
0
        public void Prepare()
        {
            _weightText = "TKUtils.Fields.Weight".TranslateSimple();

            _comparisonOptions = Data.ComparisonTypes.Values.Select(
                i => new FloatMenuOption(
                    i.AsOperator(),
                    () =>
            {
                _comparison = i;
                Dirty.Set(true);
            }
                    )
                )
                                 .ToList();
        }
Esempio n. 20
0
        public void Prepare()
        {
            _priceText = Label;

            _comparisonOptions = Data.ComparisonTypes.Values.Select(
                i => new FloatMenuOption(
                    i.AsOperator(),
                    () =>
            {
                _comparison = i;
                Dirty.Set(true);
            }
                    )
                )
                                 .ToList();
        }
Esempio n. 21
0
 public void AssetLoading(object sender, IContentEventHelper e)
 {
     try {
         Originals[e.AssetName] = e.Data;
         Dirty.Remove(e.AssetName);
         if (this.Merge(e.AssetName, e.Data))
         {
             e.ReplaceWith(Assets[e.AssetName]);
         }
         else
         {
             Assets[e.AssetName] = e.Data;
         }
     } catch (Exception ex) {
         ex.ToString();
     }
 }
Esempio n. 22
0
        public void Update(bool forceUpdate = false)
        {
            BitArray oldOutput = (BitArray)Output.Clone();

            GetOutput(forceUpdate);

            if (KeepDirty)
            {
                Dirty.Or(oldOutput.Xor(Output));
            }
            else
            {
                Dirty = (BitArray)oldOutput.Xor(Output).Clone();
            }
            OldInput = (BitArray)Input.Clone();
            FirstRun = false;
        }
Esempio n. 23
0
    public void SetDirty(Dirty dirty)
    {
        switch (dirty)
        {
        case Dirty.Clean:
        case Dirty.Dirty:
        case Dirty.None:
            implStopUpdate();
            break;

        case Dirty.RequireUpdate:
        case Dirty.FixedUpdate:
            new ErrorResultDescriptor("invalid parameter use action argument function");
            break;
        }

        m_CurrentState = dirty;
    }
Esempio n. 24
0
        public void Draw(Rect canvas)
        {
            (Rect label, Rect field) = canvas.Split(0.75f);
            UiHelper.Label(label, _categoryText);

            if (UiHelper.TextField(field, Category, out string input))
            {
                Category = input;
                Dirty.Set(true);
            }

            if (!UiHelper.FieldButton(field, Exclude ? "!=" : "=", Exclude ? _includeTooltip : _excludeTooltip))
            {
                return;
            }

            Exclude = !Exclude;
            Dirty.Set(true);
        }
Esempio n. 25
0
        public void Draw(Rect canvas)
        {
            (Rect label, Rect field) = canvas.Split(0.75f);
            UiHelper.Label(label, _defNameText);

            if (UiHelper.TextField(field, _defName, out string input))
            {
                _defName = input;
                Dirty.Set(true);
            }

            if (!UiHelper.FieldButton(field, _exclude ? "!=" : "=", _exclude ? _includeTooltip : _excludeTooltip))
            {
                return;
            }

            _exclude = !_exclude;
            Dirty.Set(true);
        }
Esempio n. 26
0
        public void Draw(Rect canvas)
        {
            (Rect label, Rect field) = canvas.Split(0.75f);
            UiHelper.Label(label, _priceText);

            (Rect button, Rect input) = field.Split(0.3f);

            if (Widgets.ButtonText(button, _comparison.AsOperator()))
            {
                Find.WindowStack.Add(new FloatMenu(_comparisonOptions));
            }

            if (!UiHelper.NumberField(input, out int value, ref _priceBuffer, ref _priceBufferValid))
            {
                return;
            }

            _price = value;
            Dirty.Set(true);
        }
Esempio n. 27
0
        public void PlaceBlock(byte x, byte y, ushort blockId, bool overwrite)
        {
            if (blockId >= _blockList.Count)
            {
                CoreUtil.LogError($"Tried to set out-of-range block {blockId} (max id {_blockList.Count-1})");
                return;
            }

            var block = _blockList[blockId];

            for (int j = 0; j < block.Height; j++)
            {
                for (int i = 0; i < block.Width; i++)
                {
                    var targetIndex      = Index(x + i, y + j);
                    var targetBlockIndex = j * block.Width + i;

                    if (targetIndex < 0 || targetIndex > _mapData.Underlay.Length)
                    {
                        CoreUtil.LogError($"Tried to set out-of-range index {targetIndex}, @ ({x},{y}) + ({i},{j}) for block {blockId}");
                        return;
                    }

                    int underlay    = _mapData.Underlay[targetIndex];
                    int newUnderlay = block.Underlay[targetBlockIndex];
                    if (newUnderlay > 1 && (overwrite || underlay <= 1))
                    {
                        _mapData.Underlay[targetIndex] = newUnderlay;
                        Dirty?.Invoke(this, new DirtyTileEventArgs(x + i, y + j, IconChangeType.Underlay));
                    }

                    int overlay    = _mapData.Overlay[targetIndex];
                    int newOverlay = block.Overlay[targetBlockIndex];
                    if (overwrite || overlay > 1)
                    {
                        _mapData.Overlay[targetIndex] = newOverlay;
                        Dirty?.Invoke(this, new DirtyTileEventArgs(x + i, y + j, IconChangeType.Overlay));
                    }
                }
            }
        }
Esempio n. 28
0
        private void CopyDirties(int from, int to)
        {
            var fromDirties = dirties[from];
            var toDirties   = dirties[to];

            for (int i = 0, n = fromDirties.Count; i < n; ++i)
            {
                var dirty = fromDirties[i];
                if (dirty.Phase < 2)
                {
                    throw new NotImplementedException();
                }
                else if (dirty.Phase > 10)
                {
                    continue;
                }

                // TODO Parallel if profiler tell it's slow
                dirty.Inner.CopyCell(WriteCellIndex, to);

                var existing = toDirties.Find(it => ReferenceEquals(it.Inner, dirty.Inner));
                if (existing == null)
                {
                    existing = new Dirty
                    {
                        Phase = 11,
                        Inner = dirty.Inner,
                    };
                    toDirties.Add(existing);
                }
                else
                {
                    throw new NotImplementedException();
                }
            }
        }
Esempio n. 29
0
 protected void OnDirty(int x, int y, IconChangeType type) => Dirty?.Invoke(this, new DirtyTileEventArgs(x, y, type));
Esempio n. 30
0
        private static void Update(DrawingContext context, Scene scene, VisualNode node, Rect clip, bool forceRecurse)
        {
            var visual       = node.Visual;
            var opacity      = visual.Opacity;
            var clipToBounds = visual.ClipToBounds;

#pragma warning disable CS0618 // Type or member is obsolete
            var clipToBoundsRadius = visual is IVisualWithRoundRectClip roundRectClip ?
                                     roundRectClip.ClipToBoundsRadius :
                                     default;
#pragma warning restore CS0618 // Type or member is obsolete

            var bounds      = new Rect(visual.Bounds.Size);
            var contextImpl = (DeferredDrawingContextImpl)context.PlatformImpl;

            contextImpl.Layers.Find(node.LayerRoot !)?.Dirty.Add(node.Bounds);

            if (visual.IsVisible)
            {
                var m = node != scene.Root ?
                        Matrix.CreateTranslation(visual.Bounds.Position) :
                        Matrix.Identity;

                var renderTransform = Matrix.Identity;

                if (visual.RenderTransform != null)
                {
                    var origin = visual.RenderTransformOrigin.ToPixels(new Size(visual.Bounds.Width, visual.Bounds.Height));
                    var offset = Matrix.CreateTranslation(origin);
                    renderTransform = (-offset) * visual.RenderTransform.Value * (offset);
                }

                m = renderTransform * m;

                using (contextImpl.BeginUpdate(node))
                    using (context.PushPostTransform(m))
                        using (context.PushTransformContainer())
                        {
                            var globalBounds = bounds.TransformToAABB(contextImpl.Transform);
                            var clipBounds   = clipToBounds ?
                                               globalBounds.Intersect(clip) :
                                               clip;

                            forceRecurse = forceRecurse ||
                                           node.ClipBounds != clipBounds ||
                                           node.Opacity != opacity ||
                                           node.Transform != contextImpl.Transform;

                            node.Transform          = contextImpl.Transform;
                            node.ClipBounds         = clipBounds;
                            node.ClipToBounds       = clipToBounds;
                            node.LayoutBounds       = globalBounds;
                            node.ClipToBoundsRadius = clipToBoundsRadius;
                            node.GeometryClip       = visual.Clip?.PlatformImpl;
                            node.Opacity            = opacity;

                            // TODO: Check equality between node.OpacityMask and visual.OpacityMask before assigning.
                            node.OpacityMask = visual.OpacityMask?.ToImmutable();

                            if (ShouldStartLayer(visual))
                            {
                                if (node.LayerRoot != visual)
                                {
                                    MakeLayer(scene, node);
                                }
                                else
                                {
                                    UpdateLayer(node, scene.Layers[node.LayerRoot]);
                                }
                            }
                            else if (node.LayerRoot == node.Visual && node.Parent != null)
                            {
                                ClearLayer(scene, node);
                            }

                            if (node.ClipToBounds)
                            {
                                clip = clip.Intersect(node.ClipBounds);
                            }

                            try
                            {
                                visual.Render(context);
                            }
                            catch { }

                            var transformed = new TransformedBounds(new Rect(visual.Bounds.Size), clip, node.Transform);
                            visual.TransformedBounds = transformed;

                            if (forceRecurse)
                            {
                                var visualChildren = (IList <IVisual>)visual.VisualChildren;

                                node.TryPreallocateChildren(visualChildren.Count);

                                if (visualChildren.Count == 1)
                                {
                                    var childNode = GetOrCreateChildNode(scene, visualChildren[0], node);
                                    Update(context, scene, (VisualNode)childNode, clip, forceRecurse);
                                }
                                else if (visualChildren.Count > 1)
                                {
                                    var count          = visualChildren.Count;
                                    var sortedChildren = new (IVisual visual, int index)[count];