System.Math.Min(decimal, decimal)

Here are the examples of the csharp api System.Math.Min(decimal, decimal) taken from open source projects. By voting up you can indicate which examples are most useful and appropriate.

6154 Examples 7

19 Source : Cursor.cs
with GNU Affero General Public License v3.0
from 0ceal0t

private static float GetStatusTime(StatusNameId status, float statusDuration) {
            if (statusDuration == 0) return 0;
            if (status.Status.Id == 0) return 0;
            var ret = (UIHelper.PlayerStatus.TryGetValue(status.Status, out var value) ? (value.RemainingTime > 0 ? value.RemainingTime : value.RemainingTime * -1) : 0) / statusDuration;
            return Math.Min(ret, 1f);
        }

19 Source : CelesteNetRenderHelperComponent.cs
with MIT License
from 0x0ade

public void Rect(float x, float y, float width, float height, Color color) {
            int xi = (int) Math.Floor(x);
            int yi = (int) Math.Floor(y);
            int wi = (int) Math.Ceiling(x + width) - xi;
            int hi = (int) Math.Ceiling(y + height) - yi;

            Rectangle rect = new(xi, yi, wi, hi);

            MDraw.SpriteBatch.Draw(
                BlurRT,
                rect, rect,
                Color.White * Math.Min(1f, color.A / 255f * 2f)
            );

            MDraw.Rect(xi, yi, wi, hi, color);
        }

19 Source : GmicPipeServer.cs
with GNU General Public License v3.0
from 0xC0000054

private unsafe string PrepareCroppedLayers(InputMode inputMode, RectangleF cropRect)
        {
            if (inputMode == InputMode.NoInput)
            {
                return string.Empty;
            }

            IReadOnlyList<GmicLayer> layers = GetRequestedLayers(inputMode);

            if (layers.Count == 0)
            {
                return string.Empty;
            }

            if (memoryMappedFiles.Capacity < layers.Count)
            {
                memoryMappedFiles.Capacity = layers.Count;
            }

            StringBuilder reply = new StringBuilder();

            foreach (GmicLayer layer in layers)
            {
                Surface surface = layer.Surface;
                bool disposeSurface = false;
                int destinationImageStride = surface.Stride;

                if (cropRect != WholeImageCropRect)
                {
                    int cropX = (int)Math.Floor(cropRect.X * layer.Width);
                    int cropY = (int)Math.Floor(cropRect.Y * layer.Height);
                    int cropWidth = (int)Math.Min(layer.Width - cropX, 1 + Math.Ceiling(cropRect.Width * layer.Width));
                    int cropHeight = (int)Math.Min(layer.Height - cropY, 1 + Math.Ceiling(cropRect.Height * layer.Height));

                    try
                    {
                        surface = layer.Surface.CreateWindow(cropX, cropY, cropWidth, cropHeight);
                    }
                    catch (ArgumentOutOfRangeException ex)
                    {
                        throw new InvalidOperationException(string.Format("Surface.CreateWindow bounds invalid, cropRect={0}", cropRect.ToString()), ex);
                    }
                    disposeSurface = true;
                    destinationImageStride = cropWidth * ColorBgra.SizeOf;
                }

                string mapName = "pdn_" + Guid.NewGuid().ToString();

                try
                {
                    MemoryMappedFile file = MemoryMappedFile.CreateNew(mapName, surface.Scan0.Length);
                    memoryMappedFiles.Add(file);

                    using (MemoryMappedViewAccessor accessor = file.CreateViewAccessor())
                    {
                        byte* destination = null;
                        RuntimeHelpers.PrepareConstrainedRegions();
                        try
                        {
                            accessor.SafeMemoryMappedViewHandle.AcquirePointer(ref destination);

                            for (int y = 0; y < surface.Height; y++)
                            {
                                ColorBgra* src = surface.GetRowAddressUnchecked(y);
                                byte* dst = destination + (y * destinationImageStride);

                                Buffer.MemoryCopy(src, dst, destinationImageStride, destinationImageStride);
                            }
                        }
                        finally
                        {
                            if (destination != null)
                            {
                                accessor.SafeMemoryMappedViewHandle.ReleasePointer();
                            }
                        }
                    }
                }
                finally
                {
                    if (disposeSurface)
                    {
                        surface.Dispose();
                    }
                }

                reply.AppendFormat(
                    CultureInfo.InvariantCulture,
                    "{0},{1},{2},{3}\n",
                    mapName,
                    surface.Width.ToString(CultureInfo.InvariantCulture),
                    surface.Height.ToString(CultureInfo.InvariantCulture),
                    destinationImageStride.ToString(CultureInfo.InvariantCulture));
            }

            return reply.ToString();
        }

19 Source : GamePlayTest.cs
with Apache License 2.0
from 2881099

[Fact]
		public void Create() {
			Dictionary<string, GameInfo> db = new Dictionary<string, GameInfo>();
			GamePlay.OnGetData = id => db.TryGetValue(id, out var tryout) ? tryout : null;
			GamePlay.OnSaveData = (id, d) => {
				db.TryAdd(id, d);
			};

			replacedert.Throws<ArgumentException>(() => GamePlay.Create(null, 2, 5));
			replacedert.Throws<ArgumentException>(() => GamePlay.Create(new[] { "���1", "���2", "���3", "���4" }, 2, 5));
			replacedert.Throws<ArgumentException>(() => GamePlay.Create(new[] { "���1", "���2" }, 2, 5));

			var ddz = GamePlay.Create(new[] { "���1", "���2", "���3" }, 2, 5);
			var data = db[ddz.Id];
			//ϴ�ƣ�����
			replacedert.NotNull(ddz);
			replacedert.NotNull(data);
			replacedert.Equal(GameStage.δ��ʼ, data.stage);

			ddz.Shuffle();
			replacedert.Equal(0, data.bong);
			replacedert.Empty(data.chupai);
			replacedert.Equal(3, data.dipai.Length);
			replacedert.Equal(2, data.multiple);
			replacedert.Equal(0, data.multipleAddition);
			replacedert.Equal(5, data.multipleAdditionMax);
			replacedert.Equal(3, data.players.Count);
			replacedert.Equal(GamePlayerRole.δ֪, data.players[0].role);
			replacedert.Equal(GamePlayerRole.δ֪, data.players[1].role);
			replacedert.Equal(GamePlayerRole.δ֪, data.players[2].role);
			replacedert.Equal(17, data.players[0].pokerInit.Count);
			replacedert.Equal(17, data.players[1].pokerInit.Count);
			replacedert.Equal(17, data.players[2].pokerInit.Count);
			replacedert.Equal(17, data.players[0].poker.Count);
			replacedert.Equal(17, data.players[1].poker.Count);
			replacedert.Equal(17, data.players[2].poker.Count);
			replacedert.Equal("���1", data.players[0].id);
			replacedert.Equal("���2", data.players[1].id);
			replacedert.Equal("���3", data.players[2].id);
			replacedert.Equal(GameStage.���, data.stage);

			//���Ƿ��ظ�
			replacedert.Equal(54, data.players[0].poker.Concat(data.players[1].poker).Concat(data.players[2].poker).Concat(data.dipai).Distinct().Count());

			//GetById
			replacedert.Equal(GamePlay.GetById(ddz.Id).Id, ddz.Id);
			replacedert.Throws<ArgumentException>(() => GamePlay.GetById(null));
			replacedert.Throws<ArgumentException>(() => GamePlay.GetById(""));
			replacedert.Throws<ArgumentException>(() => GamePlay.GetById("slkdjglkjsdg"));

			//������
			replacedert.Throws<ArgumentException>(() => ddz.SelectLandlord("���10", 1));
			replacedert.Throws<ArgumentException>(() => ddz.SelectFarmer("���10"));
			replacedert.Throws<ArgumentException>(() => ddz.SelectLandlord(data.players[Math.Min(data.playerIndex + 1, data.players.Count - 1)].id, 1));
			replacedert.Throws<ArgumentException>(() => ddz.SelectFarmer(data.players[Math.Min(data.playerIndex + 1, data.players.Count - 1)].id));
			ddz.SelectLandlord(data.players[data.playerIndex].id, 1);
			replacedert.Equal(GameStage.���, data.stage);
			replacedert.Throws<ArgumentException>(() => ddz.SelectLandlord(data.players[data.playerIndex].id, 1));
			replacedert.Throws<ArgumentException>(() => ddz.SelectLandlord(data.players[data.playerIndex].id, 100));
			ddz.SelectLandlord(data.players[data.playerIndex].id, 2);
			replacedert.Equal(GameStage.���, data.stage);
			ddz.SelectLandlord(data.players[data.playerIndex].id, 3);
			replacedert.Equal(GameStage.���, data.stage);

			ddz.SelectFarmer(data.players[data.playerIndex].id);
			replacedert.Equal(GameStage.���, data.stage);
			replacedert.Equal(2, data.players.Where(a => a.role == GamePlayerRole.δ֪).Count());

			//�Էⶥ�������õ���
			//ddz.SelectLandlord(data.players[data.playerIndex].player, 5);
			//����ũ�񶼲������ɱ��ֵ������õ���
			ddz.SelectFarmer(data.players[data.playerIndex].id);

			replacedert.Equal(GameStage.������, data.stage);
			replacedert.Equal(GamePlayerRole.����, data.players[data.playerIndex].role);
			replacedert.Equal(2, data.players.Where(a => a.role == GamePlayerRole.ũ��).Count());


		}

19 Source : RedisClientPool.cs
with MIT License
from 2881099

public static void PrevReheatConnectionPool(ObjectPool<RedisClient> pool, int minPoolSize)
        {
            if (minPoolSize <= 0) minPoolSize = Math.Min(5, pool.Policy.PoolSize);
            if (minPoolSize > pool.Policy.PoolSize) minPoolSize = pool.Policy.PoolSize;
            var initTestOk = true;
            var initStartTime = DateTime.Now;
            var initConns = new ConcurrentBag<Object<RedisClient>>();

            try
            {
                var conn = pool.Get();
                initConns.Add(conn);
                conn.Value.Ping();
            }
            catch (Exception ex)
            {
                initTestOk = false; //预热一次失败,后面将不进行
                pool.SetUnavailable(ex);
            }
            for (var a = 1; initTestOk && a < minPoolSize; a += 10)
            {
                if (initStartTime.Subtract(DateTime.Now).TotalSeconds > 3) break; //预热耗时超过3秒,退出
                var b = Math.Min(minPoolSize - a, 10); //每10个预热
                var initTasks = new Task[b];
                for (var c = 0; c < b; c++)
                {
                    initTasks[c] = TaskEx.Run(() =>
                    {
                        try
                        {
                            var conn = pool.Get();
                            initConns.Add(conn);
                        }
                        catch
                        {
                            initTestOk = false;  //有失败,下一组退出预热
                        }
                    });
                }
                Task.WaitAll(initTasks);
            }
            while (initConns.TryTake(out var conn)) pool.Return(conn);
        }

19 Source : CSRedisCache.cs
with MIT License
from 2881099

private static long? GetExpirationInSeconds(DateTimeOffset creationTime, DateTimeOffset? absoluteExpiration, DistributedCacheEntryOptions options) {
			if (absoluteExpiration.HasValue && options.SlidingExpiration.HasValue) {
				return (long) Math.Min(
					(absoluteExpiration.Value - creationTime).TotalSeconds,
					options.SlidingExpiration.Value.TotalSeconds);
			} else if (absoluteExpiration.HasValue) {
				return (long) (absoluteExpiration.Value - creationTime).TotalSeconds;
			} else if (options.SlidingExpiration.HasValue) {
				return (long) options.SlidingExpiration.Value.TotalSeconds;
			}
			return null;
		}

19 Source : RedisClientPool.cs
with MIT License
from 2881099

public static void PrevReheatConnectionPool(ObjectPool<RedisClient> pool, int minPoolSize)
        {
            if (minPoolSize <= 0) minPoolSize = Math.Min(5, pool.Policy.PoolSize);
            if (minPoolSize > pool.Policy.PoolSize) minPoolSize = pool.Policy.PoolSize;
            var initTestOk = true;
            var initStartTime = DateTime.Now;
            var initConns = new ConcurrentBag<Object<RedisClient>>();

            try
            {
                var conn = pool.Get();
                initConns.Add(conn);
                pool.Policy.OnCheckAvailable(conn);
            }
            catch (Exception ex)
            {
                initTestOk = false; //预热一次失败,后面将不进行
                pool.SetUnavailable(ex);
            }
            for (var a = 1; initTestOk && a < minPoolSize; a += 10)
            {
                if (initStartTime.Subtract(DateTime.Now).TotalSeconds > 3) break; //预热耗时超过3秒,退出
                var b = Math.Min(minPoolSize - a, 10); //每10个预热
                var initTasks = new Task[b];
                for (var c = 0; c < b; c++)
                {
                    initTasks[c] = TaskEx.Run(() =>
                    {
                        try
                        {
                            var conn = pool.Get();
                            initConns.Add(conn);
                            pool.Policy.OnCheckAvailable(conn);
                        }
                        catch
                        {
                            initTestOk = false;  //有失败,下一组退出预热
                        }
                    });
                }
                Task.WaitAll(initTasks);
            }
            while (initConns.TryTake(out var conn)) pool.Return(conn);
        }

19 Source : PlayerStatusHandler.cs
with GNU Lesser General Public License v3.0
from 8720826

private async Task DoWork(PlayerEnreplacedy player)
        {
            await _mudProvider.ShowMessage(player.Id, $"你正在{player.Status}。。。");
            WorkTypeEnum workType = WorkTypeEnum.伐木;
            switch (player.Status)
            {
                case PlayerStatusEnum.伐木:
                    workType = WorkTypeEnum.伐木;
                    break;
                case PlayerStatusEnum.挖矿:
                    workType = WorkTypeEnum.挖矿;
                    break;
                case PlayerStatusEnum.打猎:
                    workType = WorkTypeEnum.打猎;
                    break;
                case PlayerStatusEnum.采药:
                    workType = WorkTypeEnum.采药;
                    break;
                case PlayerStatusEnum.钓鱼:
                    workType = WorkTypeEnum.钓鱼;
                    break;
                case PlayerStatusEnum.打工:
                    workType = WorkTypeEnum.打工;
                    break;

                default:
                    return;
            }

            var ids = (await _roomItemDropDomainService.GetAll()).Where(x => x.RoomId == player.RoomId).Select(x=>x.ItemDropId).ToList();

            var itemDrop = (await _itemDropDomainService.GetAll()).Where(x => ids.Contains(x.Id)).FirstOrDefault(x => x.WorkType == workType);
            if (itemDrop == null)
            {
                return;
            }
           

            var itemDropRates = (await _itemDropRateDomainService.GetAll()).Where(x => x.ItemDropId == itemDrop.Id).ToList();
            if (itemDropRates?.Count == 0)
            {
                return;
            }

            var random = new Random();
            int maxWeight = 100;//掉落总权重
            var itemDropModels = new List<ItemDropRateModel>();
            foreach (var itemDropRate in itemDropRates.OrderBy(x=>x.Order))
            {
                if (itemDropRate.Percent < random.Next(0, 100))
                {
                    continue;
                }

                int number = random.Next(Math.Min(itemDropRate.MinNumber, itemDropRate.MaxNumber), itemDropRate.MaxNumber + 1);
                if (number <= 0)
                {
                    continue;
                }

                //掉落
                maxWeight -= itemDropRate.Weight;

                var itemDropModel = new ItemDropRateModel
                {
                    DropType = itemDropRate.DropType,
                    Number = number,
                    WareId = itemDropRate.WareId
                };
                itemDropModels.Add(itemDropModel);



                if (maxWeight <= 0)
                {
                    break;
                }
            }

            if (itemDropModels.Count == 0)
            {
                //没有掉落
                return;
            }

            var playerAttributeChanged = false;
            List<string> dropContents = new List<string>() ;

            foreach (var itemDropModel in itemDropModels)
            {
                switch (itemDropModel.DropType)
                {
                    case ItemDropTypeEnum.潜能:
                        playerAttributeChanged = true;
                        player.Pot += itemDropModel.Number;
                        dropContents.Add($"潜能 +{itemDropModel.Number}");
                        break;
                    case ItemDropTypeEnum.经验:
                        playerAttributeChanged = true;
                        player.Exp += itemDropModel.Number;
                        dropContents.Add($"经验 +{itemDropModel.Number}");
                        break;
                    case ItemDropTypeEnum.金钱:
                        playerAttributeChanged = true;
                        player.Money += itemDropModel.Number;
                        dropContents.Add($" +{itemDropModel.Number.ToMoney()}");
                        break;
                    case ItemDropTypeEnum.物品:
                        #region MyRegion
                        int wareId = itemDropModel.WareId;
                        int number = itemDropModel.Number;

                        var ware = await _wareDomainService.Get(wareId);
                        if (ware == null)
                        {
                            continue;
                        }

                        dropContents.Add($"{number}{ware.Unit}{ware.Name}");

                        var canStack = ware.Category != WareCategoryEnum.武器;

                        if (canStack)
                        {
                            var playerWare = await _playerWareDomainService.Get(x => x.WareId == ware.Id && x.PlayerId == player.Id);
                            if (playerWare == null)
                            {
                                playerWare = new PlayerWareEnreplacedy
                                {
                                    IsBind = false,
                                    IsTemp = false,
                                    Level = 1,
                                    Number = number,
                                    Damage = 0,
                                    PlayerId = player.Id,
                                    Status = WareStatusEnum.卸下,
                                    WareId = wareId,
                                    WareName = ware.Name
                                };
                                await _playerWareDomainService.Add(playerWare);
                            }
                            else
                            {
                                playerWare.Number += number;
                                await _playerWareDomainService.Update(playerWare);
                            }
                        }
                        else
                        {
                            var playerWare = new PlayerWareEnreplacedy
                            {
                                IsBind = false,
                                IsTemp = false,
                                Level = 1,
                                Number = number,
                                Damage = 0,
                                PlayerId = player.Id,
                                Status = WareStatusEnum.卸下,
                                WareId = wareId,
                                WareName = ware.Name
                            };
                            await _playerWareDomainService.Add(playerWare);
                        }
                        #endregion


                        break;
                }
               
            }

            if (playerAttributeChanged)
            {
                await _bus.RaiseEvent(new PlayerAttributeChangedEvent(player)).ConfigureAwait(false);
            }


            if (dropContents.Count > 0)
            {
                await _mudProvider.ShowMessage(player.Id, $"获得{ string.Join(",", dropContents)   }。");   
            }


        }

19 Source : CloudDownsample - Copy.cs
with GNU Lesser General Public License v3.0
from 9and3

protected override void SolveInstance(IGH_DataAccess DA) {

            // Input
            GH_Cloud cgh = new GH_Cloud();
            DA.GetData(0, ref cgh);

            int n = 50;
            DA.GetData(1, ref n);
            n = Math.Min(cgh.Value.Count, Math.Max(0,n));

            var c = PInvokeCSharp.TestOpen3D.Downsample(cgh.Value, n);
            //var c = PInvokeCSharp.TestOpen3D.DownsampleRhino(cgh.Value, n);
            //this.Message = c.Count.ToString();

            DA.SetData(0, new GH_Cloud(c));


        }

19 Source : CloudDownsample.cs
with GNU Lesser General Public License v3.0
from 9and3

protected override void SolveInstance(IGH_DataAccess DA) {

            // Input
            GH_Cloud cgh = new GH_Cloud();
            DA.GetData(0, ref cgh);

            int n = 50;
            DA.GetData(1, ref n);
            n = Math.Min(cgh.Value.Count, Math.Max(0,n));


            DA.SetData(0, new GH_Cloud(DownsampleUniform(cgh.Value,n)));


        }

19 Source : PointCloudToMeshComponentFull.cs
with GNU Lesser General Public License v3.0
from 9and3

protected override void SolveInstance(IGH_DataAccess DA) {

            int Downsample = 5000;
            int NormalsNeighbours = 100;
            bool debug = false;

            int maximumDeptOfReconstructionSurfaceTree = 8;
            int targetWidthOfTheFinestLevelOctree = 0;
            double ratioBetweenReconCubeAndBBCubeStd = 1.1;
            bool ReconstructorUsingLinearInterpolation = false;

            DA.GetData(1, ref Downsample);
            DA.GetData(2, ref NormalsNeighbours);
            DA.GetData(3, ref debug);
            DA.GetData(4, ref maximumDeptOfReconstructionSurfaceTree);
            DA.GetData(5, ref targetWidthOfTheFinestLevelOctree);
            DA.GetData(6, ref ratioBetweenReconCubeAndBBCubeStd);
            DA.GetData(7, ref ReconstructorUsingLinearInterpolation);

            //Guid to PointCloud
            //PointCloud c = new PointCloud();
            PointCloudGH c = new PointCloudGH();

            string debugInfo = debug ? "1" : "0";
            

            if (DA.GetData(0, ref c)) {
                if (!c.IsValid) return;
                if (c.Value.Count==0) return;
                Downsample = Math.Min(Downsample, c.Value.Count);

               // var watch = System.Diagnostics.Stopwatch.StartNew();
                // the code that you want to measure comes here

                /////////////////////////////////////////////////////////////////
                //Get Directory
                /////////////////////////////////////////////////////////////////
                string replacedemblyLocation = System.Reflection.replacedembly.GetExecutingreplacedembly().Location;
                string replacedemblyPath = System.IO.Path.GetDirectoryName(replacedemblyLocation);


                /////////////////////////////////////////////////////////////////
                //write PointCloud to PLY
                /////////////////////////////////////////////////////////////////
                PlyReaderWriter.PlyWriter.SavePLY(c.Value, replacedemblyPath + @"\in.ply");
                //Rhino.RhinoApp.WriteLine("PointCloudToMesh. Saved Input: " + replacedemblyPath + @"\in.ply");
                //watch.Stop();
                //Rhino.RhinoApp.WriteLine((watch.ElapsedMilliseconds / 1000.0).ToString());

                /////////////////////////////////////////////////////////////////
                //Ply to Mesh to Obj
                /////////////////////////////////////////////////////////////////
                //watch = System.Diagnostics.Stopwatch.StartNew();
                //tring argument = replacedemblyPath + "TestVisualizer.exe " + "-1 " + "100";//--asci 
                string argument = " "+Downsample.ToString()+ " " + NormalsNeighbours.ToString() + " " + debugInfo + " " + maximumDeptOfReconstructionSurfaceTree.ToString() + " " + targetWidthOfTheFinestLevelOctree.ToString() + " " + ratioBetweenReconCubeAndBBCubeStd.ToString() + " " + Convert.ToInt32(ReconstructorUsingLinearInterpolation).ToString();
                //--asci 
                                                                                                                  // Rhino.RhinoApp.WriteLine("PointCloudToMesh. Arguments: " + argument );



                // Rhino.RhinoApp.WriteLine("PointCloudToMesh. Directory: " + replacedemblyPath + @"\TestVisualizer.exe");

                if (debug) {
                    var proc = new System.Diagnostics.Process {
                        StartInfo = new System.Diagnostics.ProcessStartInfo {
                            FileName = replacedemblyPath + @"\TestVisualizer.exe",//filePath+"PoissonRecon.exe",
                            Arguments = argument,
                            //UseShellExecute = false,
                            //RedirectStandardOutput = true,
                            CreateNoWindow = false,
                            // WindowStyle = System.Diagnostics.ProcessWindowStyle.Hidden,
                            WorkingDirectory = replacedemblyPath + @"\TestVisualizer.exe"
                        }
                    };

                    proc.Start();
                 
                    proc.WaitForExit();
                } else {
                    var proc = new System.Diagnostics.Process {
                        StartInfo = new System.Diagnostics.ProcessStartInfo {
                            FileName = replacedemblyPath + @"\TestVisualizer.exe",//filePath+"PoissonRecon.exe",
                            Arguments = argument,
                            //UseShellExecute = false,
                            //RedirectStandardOutput = true,
                            CreateNoWindow = true,
                             WindowStyle = System.Diagnostics.ProcessWindowStyle.Hidden,
                            WorkingDirectory = replacedemblyPath + @"\TestVisualizer.exe"
                        }
                    };
                    proc.Start();
                    proc.WaitForExit();
                }

               // watch.Stop();
                //Rhino.RhinoApp.WriteLine((watch.ElapsedMilliseconds / 1000.0).ToString());

                /////////////////////////////////////////////////////////////////
                //Read Obj
                /////////////////////////////////////////////////////////////////
                ///

                //Outputs
               // watch = System.Diagnostics.Stopwatch.StartNew();

                // Initialize
                var obj = new ObjParser.Obj();

                // Read Wavefront OBJ file
                //obj.LoadObj(@"C:\libs\windows\out.obj");
            

                //PlyReaderWriter.PlyLoader plyLoader = new PlyReaderWriter.PlyLoader();
                //Mesh mesh3D = plyLoader.load(replacedemblyPath + @"\out.ply")[0];


                //Rhino.RhinoApp.WriteLine(replacedemblyPath + @"\windows\out.obj");
                obj.LoadObj(replacedemblyPath + @"\out.obj");

                Mesh mesh3D = new Mesh();
                foreach (ObjParser.Types.Vertex v in obj.VertexList) {
                    mesh3D.Vertices.Add(new Point3d(v.X, v.Y, v.Z));
                    mesh3D.VertexColors.Add(System.Drawing.Color.FromArgb((int)(v.r * 255), (int)(v.g * 255), (int)(v.b * 255)  ));
                }
 
                int num = checked(mesh3D.Vertices.Count - 1);

                foreach (ObjParser.Types.Face f in obj.FaceList) {

                    string[] lineData = f.ToString().Split(' ');
                    string[] v0 = lineData[1].Split('/');
                    string[] v1 = lineData[2].Split('/');
                    string[] v2 = lineData[3].Split('/');

                    MeshFace mf3D = new MeshFace(Convert.ToInt32(v0[0]) - 1, Convert.ToInt32(v1[0]) - 1, Convert.ToInt32(v2[0]) - 1);
                    if (mf3D.IsValid())
                        if (!(mf3D.A > num || mf3D.B > num || mf3D.C > num || mf3D.D > num))
                            mesh3D.Faces.AddFace(mf3D);


                }








                DA.SetData(0, mesh3D);

                /////////////////////////////////////////////////////////////////
                //Output Iso Values
                /////////////////////////////////////////////////////////////////
                string[] lines = System.IO.File.ReadAllLines(replacedemblyPath + @"\out.txt");
                double[] iso = new double[lines.Length];
                for (int i = 0; i < lines.Length; i++) { 
                    iso[i] = Convert.ToDouble(lines[i]);
                }
                //watch.Stop();
                //Rhino.RhinoApp.WriteLine((watch.ElapsedMilliseconds/1000.0).ToString());

                DA.SetDataList(1, iso);

            }


        }

19 Source : PointCloudToMeshComponent.cs
with GNU Lesser General Public License v3.0
from 9and3

protected override void SolveInstance(IGH_DataAccess DA) {

            int Downsample = 5000;
            int NormalsNeighbours = 100;
            bool debug = false;

            DA.GetData(1, ref Downsample);
            DA.GetData(2, ref NormalsNeighbours);
            DA.GetData(3, ref debug);


            //Guid to PointCloud
            //PointCloud c = new PointCloud();
            PointCloudGH c = new PointCloudGH();

            string debugInfo = debug ? "1" : "0";
            

            if (DA.GetData(0, ref c)) {
                if (!c.IsValid) return;
                if (c.Value.Count == 0) return;
                Downsample = Math.Min(Downsample, c.Value.Count);

               // var watch = System.Diagnostics.Stopwatch.StartNew();
                // the code that you want to measure comes here

                /////////////////////////////////////////////////////////////////
                //Get Directory
                /////////////////////////////////////////////////////////////////
                string replacedemblyLocation = System.Reflection.replacedembly.GetExecutingreplacedembly().Location;
                string replacedemblyPath = System.IO.Path.GetDirectoryName(replacedemblyLocation);


                /////////////////////////////////////////////////////////////////
                //write PointCloud to PLY
                /////////////////////////////////////////////////////////////////
                PlyReaderWriter.PlyWriter.SavePLY(c.Value, replacedemblyPath + @"\in.ply");
                //Rhino.RhinoApp.WriteLine("PointCloudToMesh. Saved Input: " + replacedemblyPath + @"\in.ply");
                //watch.Stop();
                //Rhino.RhinoApp.WriteLine((watch.ElapsedMilliseconds / 1000.0).ToString());

                /////////////////////////////////////////////////////////////////
                //Ply to Mesh to Obj
                /////////////////////////////////////////////////////////////////
                //watch = System.Diagnostics.Stopwatch.StartNew();
                //tring argument = replacedemblyPath + "TestVisualizer.exe " + "-1 " + "100";//--asci 
                string argument = " "+Downsample.ToString()+ " " + NormalsNeighbours.ToString() + " " + debugInfo + " 8 0 1.1 0";//--asci 
                                                                                                                  // Rhino.RhinoApp.WriteLine("PointCloudToMesh. Arguments: " + argument );

      
                //int maximumDeptOfReconstructionSurfaceTree = atoi(argv[4]);//8
                //int targetWidthOfTheFinestLevelOctree = atoi(argv[5]);//0
                //float ratioBetweenReconCubeAndBBCubeStd = atof(argv[6]);    // 1.1
                //bool ReconstructorUsingLinearInterpolation = atoi(argv[7]) == 1;//0


                // Rhino.RhinoApp.WriteLine("PointCloudToMesh. Directory: " + replacedemblyPath + @"\TestVisualizer.exe");

                if (debug) {
                    var proc = new System.Diagnostics.Process {
                        StartInfo = new System.Diagnostics.ProcessStartInfo {
                            FileName = replacedemblyPath + @"\TestVisualizer.exe",//filePath+"PoissonRecon.exe",
                            Arguments = argument,
                            //UseShellExecute = false,
                            //RedirectStandardOutput = true,
                            CreateNoWindow = false,
                            // WindowStyle = System.Diagnostics.ProcessWindowStyle.Hidden,
                            WorkingDirectory = replacedemblyPath + @"\TestVisualizer.exe"
                        }
                    };

                    proc.Start();
                 
                    proc.WaitForExit();
                } else {
                    var proc = new System.Diagnostics.Process {
                        StartInfo = new System.Diagnostics.ProcessStartInfo {
                            FileName = replacedemblyPath + @"\TestVisualizer.exe",//filePath+"PoissonRecon.exe",
                            Arguments = argument,
                            //UseShellExecute = false,
                            //RedirectStandardOutput = true,
                            CreateNoWindow = true,
                             WindowStyle = System.Diagnostics.ProcessWindowStyle.Hidden,
                            WorkingDirectory = replacedemblyPath + @"\TestVisualizer.exe"
                        }
                    };
                    proc.Start();
                    proc.WaitForExit();
                }

               // watch.Stop();
                //Rhino.RhinoApp.WriteLine((watch.ElapsedMilliseconds / 1000.0).ToString());

                /////////////////////////////////////////////////////////////////
                //Read Obj
                /////////////////////////////////////////////////////////////////
                ///

                //Outputs
               // watch = System.Diagnostics.Stopwatch.StartNew();

                // Initialize
                var obj = new ObjParser.Obj();

                // Read Wavefront OBJ file
                //obj.LoadObj(@"C:\libs\windows\out.obj");
            

                //PlyReaderWriter.PlyLoader plyLoader = new PlyReaderWriter.PlyLoader();
                //Mesh mesh3D = plyLoader.load(replacedemblyPath + @"\out.ply")[0];


                //Rhino.RhinoApp.WriteLine(replacedemblyPath + @"\windows\out.obj");
                obj.LoadObj(replacedemblyPath + @"\out.obj");

                Mesh mesh3D = new Mesh();
                foreach (ObjParser.Types.Vertex v in obj.VertexList) {
                    mesh3D.Vertices.Add(new Point3d(v.X, v.Y, v.Z));
                    mesh3D.VertexColors.Add(System.Drawing.Color.FromArgb((int)(v.r * 255), (int)(v.g * 255), (int)(v.b * 255)  ));
                }
 
                int num = checked(mesh3D.Vertices.Count - 1);

                foreach (ObjParser.Types.Face f in obj.FaceList) {

                    string[] lineData = f.ToString().Split(' ');
                    string[] v0 = lineData[1].Split('/');
                    string[] v1 = lineData[2].Split('/');
                    string[] v2 = lineData[3].Split('/');

                    MeshFace mf3D = new MeshFace(Convert.ToInt32(v0[0]) - 1, Convert.ToInt32(v1[0]) - 1, Convert.ToInt32(v2[0]) - 1);
                    if (mf3D.IsValid())
                        if (!(mf3D.A > num || mf3D.B > num || mf3D.C > num || mf3D.D > num))
                            mesh3D.Faces.AddFace(mf3D);


                }








                DA.SetData(0, mesh3D);

                /////////////////////////////////////////////////////////////////
                //Output Iso Values
                /////////////////////////////////////////////////////////////////
                string[] lines = System.IO.File.ReadAllLines(replacedemblyPath + @"\out.txt");
                double[] iso = new double[lines.Length];
                for (int i = 0; i < lines.Length; i++) { 
                    iso[i] = Convert.ToDouble(lines[i]);
                }
                //watch.Stop();
                //Rhino.RhinoApp.WriteLine((watch.ElapsedMilliseconds/1000.0).ToString());

                DA.SetDataList(1, iso);

            }


        }

19 Source : ByteBuffer.cs
with MIT License
from a1q123456

private void WriteToBufferNoCheck(ReadOnlySpan<byte> bytes)
        {
            lock (_sync)
            {
                var requiredLength = bytes.Length;
                int available = BufferBytesAvailable();
                if (available < requiredLength)
                {
                    var bytesIndex = 0;
                    do
                    {
                        var buffer = _buffers.Last();
                        var seq = bytes.Slice(bytesIndex, Math.Min(available, requiredLength));
                        seq.CopyTo(buffer.replacedpan(_bufferEnd));
                        _bufferEnd += seq.Length;
                        requiredLength -= seq.Length;
                        available -= seq.Length;
                        bytesIndex += seq.Length;

                        if (available == 0)
                        {
                            AddNewBufferSegment();
                            available = BufferBytesAvailable();
                        }
                    }
                    while (requiredLength != 0);
                }
                else
                {
                    var buffer = _buffers.Last();
                    bytes.CopyTo(buffer.replacedpan(_bufferEnd));
                    _bufferEnd += bytes.Length;
                }
            }
            _dataWritten?.Invoke();
        }

19 Source : ByteBuffer.cs
with MIT License
from a1q123456

private void TakeOutMemoryNoCheck(Span<byte> buffer)
        {
            lock (_sync)
            {
                var discardBuffers = new List<byte[]>();
                bool prevDiscarded = false;
                if (Length < buffer.Length && _maxiumBufferSize >= 0)
                {
                    throw new InvalidProgramException();
                }
                foreach (var b in _buffers)
                {
                    if (buffer.Length == 0)
                    {
                        break;
                    }
                    var start = 0;
                    var end = BufferSegmentSize;
                    var isFirst = b == _buffers.First() || prevDiscarded;
                    var isLast = b == _buffers.Last();
                    if (isFirst)
                    {
                        start = _bufferStart;
                    }
                    if (isLast)
                    {
                        end = _bufferEnd;
                    }
                    var length = end - start;
                    var needToCopy = Math.Min(buffer.Length, length);

                    b.replacedpan(start, needToCopy).CopyTo(buffer);

                    start += needToCopy;
                    if (isFirst)
                    {
                        _bufferStart += needToCopy;
                    }

                    if (end - start == 0)
                    {
                        if (isFirst)
                        {
                            _bufferStart = 0;
                        }
                        if (isLast)
                        {
                            _bufferEnd = 0;
                        }
                        discardBuffers.Add(b);
                        prevDiscarded = true;
                    }
                    else
                    {
                        prevDiscarded = false;
                    }

                    buffer = buffer.Slice(needToCopy);
                }
                //Console.WriteLine(Length);
                Debug.replacedert(buffer.Length == 0 || _maxiumBufferSize < 0);
                while (discardBuffers.Any())
                {
                    var b = discardBuffers.First();
                    _arrayPool.Return(b);
                    discardBuffers.Remove(b);
                    _buffers.Remove(b);
                }
                if (!_buffers.Any())
                {
                    AddNewBufferSegment();
                }
            }
            if (Length <= _maxiumBufferSize && _maxiumBufferSize >= 0)
            {
                _memoryUnderLimit?.Invoke();
            }
        }

19 Source : Form1.cs
with MIT License
from a1xd

public void ResizeAndCenter()
        {
            ResetAutoScroll();

            var workingArea = Screen.FromControl(this).WorkingArea;
            var chartsPreferredSize = chartsPanel.GetPreferredSize(Constants.MaxSize);

            Size = new Size
            {
                Width = Math.Min(workingArea.Width, optionsPanel.Size.Width + chartsPreferredSize.Width),
                Height = Math.Min(workingArea.Height, chartsPreferredSize.Height + 48)
            };

            Location = new Point
            {
                X = workingArea.X + (workingArea.Width - Size.Width) / 2,
                Y = workingArea.Y + (workingArea.Height - Size.Height) / 2
            };

        }

19 Source : MatchingEngine.cs
with Apache License 2.0
from Aaronontheweb

public static (Fill bidFill, Fill askFill) FillOrders(Order bid, Order ask, ITimestamper timeService = null)
        {
            timeService = timeService ?? CurrentUtcTimestamper.Instance;
            var settlementPrice = bid.Price;

            // pick the lower of the two values - if I'm buying 5 but was only sold 2, actual is 2.
            var actualSold = Math.Min(bid.RemainingQuanreplacedy, ask.RemainingQuanreplacedy);

            var partialAsk = ask.RemainingQuanreplacedy > actualSold;
            var partialBid = bid.RemainingQuanreplacedy > actualSold;

            // generate a fill for each order
            var time = timeService.Now;
            var askFill = new Fill(ask.OrderId,  bid.StockId, actualSold, settlementPrice, bid.OrderId, time, partialAsk);
            var bidFill = new Fill(bid.OrderId, bid.StockId, actualSold, settlementPrice, ask.OrderId, time, partialBid);

            return (bidFill, askFill);
        }

19 Source : BindableAvalonEditor.cs
with MIT License
from Abdesol

protected static void OnDependencyPropertyChanged(DependencyObject obj, DependencyPropertyChangedEventArgs args)
        {
            var target = (BindableAvalonEditor)obj;

            if (target.Doreplacedent != null)
            {
                var caretOffset = target.CaretOffset;
                var newValue = args.NewValue;

                if (newValue == null)
                {
                    newValue = "";
                }

                target.Doreplacedent.Text = (string)newValue;
                target.CaretOffset = Math.Min(caretOffset, newValue.ToString().Length);
            }
        }

19 Source : InsightWindow.cs
with MIT License
from Abdesol

protected override void OnSourceInitialized(EventArgs e)
		{
			Rect caret = this.TextArea.Caret.CalculateCaretRectangle();
			Point pointOnScreen = this.TextArea.TextView.PointToScreen(caret.Location - this.TextArea.TextView.ScrollOffset);
			Rect workingArea = System.Windows.Forms.Screen.FromPoint(pointOnScreen.ToSystemDrawing()).WorkingArea.ToWpf().TransformFromDevice(this);

			MaxHeight = workingArea.Height;
			MaxWidth = Math.Min(workingArea.Width, Math.Max(1000, workingArea.Width * 0.6));

			base.OnSourceInitialized(e);
		}

19 Source : SimpleSegment.cs
with MIT License
from Abdesol

public static SimpleSegment GetOverlap(ISegment segment1, ISegment segment2)
		{
			int start = Math.Max(segment1.Offset, segment2.Offset);
			int end = Math.Min(segment1.EndOffset, segment2.EndOffset);
			if (end < start)
				return SimpleSegment.Invalid;
			else
				return new SimpleSegment(start, end - start);
		}

19 Source : EditingCommandHandler.cs
with MIT License
from Abdesol

static void OnDeleteLine(object target, ExecutedRoutedEventArgs args)
		{
			TextArea textArea = GetTextArea(target);
			if (textArea != null && textArea.Doreplacedent != null) {
				int firstLineIndex, lastLineIndex;
				if (textArea.Selection.Length == 0) {
					// There is no selection, simply delete current line
					firstLineIndex = lastLineIndex = textArea.Caret.Line;
				} else {
					// There is a selection, remove all lines affected by it (use Min/Max to be independent from selection direction)
					firstLineIndex = Math.Min(textArea.Selection.StartPosition.Line, textArea.Selection.EndPosition.Line);
					lastLineIndex = Math.Max(textArea.Selection.StartPosition.Line, textArea.Selection.EndPosition.Line);
				}
				DoreplacedentLine startLine = textArea.Doreplacedent.GetLineByNumber(firstLineIndex);
				DoreplacedentLine endLine = textArea.Doreplacedent.GetLineByNumber(lastLineIndex);
				textArea.Selection = Selection.Create(textArea, startLine.Offset, endLine.Offset + endLine.TotalLength);
				textArea.RemoveSelectedText();
				args.Handled = true;
			}
		}

19 Source : TextRangeProvider.cs
with MIT License
from Abdesol

public string GetText(int maxLength)
		{
			Log("{0}.GetText({1})", ID, maxLength);
			if (maxLength < 0)
				return doc.GetText(segment);
			else
				return doc.GetText(segment.Offset, Math.Min(segment.Length, maxLength));
		}

19 Source : TextRangeProvider.cs
with MIT License
from Abdesol

void SetEndpoint(TextPatternRangeEndpoint endpoint, int targetOffset)
		{
			if (endpoint == TextPatternRangeEndpoint.Start) {
				// set start of this range to targetOffset
				segment = new AnchorSegment(doc, targetOffset, Math.Max(0, segment.EndOffset - targetOffset));
			} else {
				// set end of this range to targetOffset
				int newStart = Math.Min(segment.Offset, targetOffset);
				segment = new AnchorSegment(doc, newStart, targetOffset - newStart);
			}
		}

19 Source : TextRangeProvider.cs
with MIT License
from Abdesol

public int MoveEndpointByUnit(TextPatternRangeEndpoint endpoint, TextUnit unit, int count)
		{
			Log("{0}.MoveEndpointByUnit({1}, {2}, {3})", ID, endpoint, unit, count);
			int offset = GetEndpoint(endpoint);
			switch (unit) {
				case TextUnit.Character:
					offset = MoveOffset(offset, CaretPositioningMode.Normal, count);
					break;
				case TextUnit.Format:
				case TextUnit.Word:
					offset = MoveOffset(offset, CaretPositioningMode.WordStart, count);
					break;
				case TextUnit.Line:
				case TextUnit.Paragraph:
					int line = doc.GetLineByOffset(offset).LineNumber;
					int newLine = Math.Max(1, Math.Min(doc.LineCount, line + count));
					offset = doc.GetLineByNumber(newLine).Offset;
					break;
				case TextUnit.Doreplacedent:
					offset = count < 0 ? 0 : doc.TextLength;
					break;
			}
			SetEndpoint(endpoint, offset);
			return count;
		}

19 Source : VisualLine.cs
with MIT License
from Abdesol

public int GetNextCaretPosition(int visualColumn, LogicalDirection direction, CaretPositioningMode mode, bool allowVirtualSpace)
		{
			if (!HreplacedtopsInVirtualSpace(mode))
				allowVirtualSpace = false;

			if (elements.Count == 0) {
				// special handling for empty visual lines:
				if (allowVirtualSpace) {
					if (direction == LogicalDirection.Forward)
						return Math.Max(0, visualColumn + 1);
					else if (visualColumn > 0)
						return visualColumn - 1;
					else
						return -1;
				} else {
					// even though we don't have any elements,
					// there's a single caret stop at visualColumn 0
					if (visualColumn < 0 && direction == LogicalDirection.Forward)
						return 0;
					else if (visualColumn > 0 && direction == LogicalDirection.Backward)
						return 0;
					else
						return -1;
				}
			}

			int i;
			if (direction == LogicalDirection.Backward) {
				// Search Backwards:
				// If the last element doesn't handle line borders, return the line end as caret stop

				if (visualColumn > this.VisualLength && !elements[elements.Count - 1].HandlesLineBorders && HasImplicitStopAtLineEnd(mode)) {
					if (allowVirtualSpace)
						return visualColumn - 1;
					else
						return this.VisualLength;
				}
				// skip elements that start after or at visualColumn
				for (i = elements.Count - 1; i >= 0; i--) {
					if (elements[i].VisualColumn < visualColumn)
						break;
				}
				// search last element that has a caret stop
				for (; i >= 0; i--) {
					int pos = elements[i].GetNextCaretPosition(
						Math.Min(visualColumn, elements[i].VisualColumn + elements[i].VisualLength + 1),
						direction, mode);
					if (pos >= 0)
						return pos;
				}
				// If we've found nothing, and the first element doesn't handle line borders,
				// return the line start as normal caret stop.
				if (visualColumn > 0 && !elements[0].HandlesLineBorders && HasImplicitStopAtLineStart(mode))
					return 0;
			} else {
				// Search Forwards:
				// If the first element doesn't handle line borders, return the line start as caret stop
				if (visualColumn < 0 && !elements[0].HandlesLineBorders && HasImplicitStopAtLineStart(mode))
					return 0;
				// skip elements that end before or at visualColumn
				for (i = 0; i < elements.Count; i++) {
					if (elements[i].VisualColumn + elements[i].VisualLength > visualColumn)
						break;
				}
				// search first element that has a caret stop
				for (; i < elements.Count; i++) {
					int pos = elements[i].GetNextCaretPosition(
						Math.Max(visualColumn, elements[i].VisualColumn - 1),
						direction, mode);
					if (pos >= 0)
						return pos;
				}
				// if we've found nothing, and the last element doesn't handle line borders,
				// return the line end as caret stop
				if ((allowVirtualSpace || !elements[elements.Count - 1].HandlesLineBorders) && HasImplicitStopAtLineEnd(mode)) {
					if (visualColumn < this.VisualLength)
						return this.VisualLength;
					else if (allowVirtualSpace)
						return visualColumn + 1;
				}
			}
			// we've found nothing, return -1 and let the caret search continue in the next line
			return -1;
		}

19 Source : SingleCharacterElementGenerator.cs
with MIT License
from Abdesol

public override TextEmbeddedObjectMetrics Format(double remainingParagraphWidth)
			{
				double width = Math.Min(0, element.text.WidthIncludingTrailingWhitespace - 1);
				return new TextEmbeddedObjectMetrics(width, element.text.Height, element.text.Baseline);
			}

19 Source : Rope.cs
with MIT License
from Abdesol

public int IndexOf(T item, int startIndex, int count)
		{
			VerifyRange(startIndex, count);

			while (count > 0) {
				var entry = FindNodeUsingCache(startIndex).PeekOrDefault();
				T[] contents = entry.node.contents;
				int startWithinNode = startIndex - entry.nodeStartIndex;
				int nodeLength = Math.Min(entry.node.length, startWithinNode + count);
				int r = Array.IndexOf(contents, item, startWithinNode, nodeLength - startWithinNode);
				if (r >= 0)
					return entry.nodeStartIndex + r;
				count -= nodeLength - startWithinNode;
				startIndex = entry.nodeStartIndex + nodeLength;
			}
			return -1;
		}

19 Source : CharRope.cs
with MIT License
from Abdesol

public static int IndexOfAny(this Rope<char> rope, char[] anyOf, int startIndex, int length)
		{
			if (rope == null)
				throw new ArgumentNullException("rope");
			if (anyOf == null)
				throw new ArgumentNullException("anyOf");
			rope.VerifyRange(startIndex, length);

			while (length > 0) {
				var entry = rope.FindNodeUsingCache(startIndex).PeekOrDefault();
				char[] contents = entry.node.contents;
				int startWithinNode = startIndex - entry.nodeStartIndex;
				int nodeLength = Math.Min(entry.node.length, startWithinNode + length);
				for (int i = startIndex - entry.nodeStartIndex; i < nodeLength; i++) {
					char element = contents[i];
					foreach (char needle in anyOf) {
						if (element == needle)
							return entry.nodeStartIndex + i;
					}
				}
				length -= nodeLength - startWithinNode;
				startIndex = entry.nodeStartIndex + nodeLength;
			}
			return -1;
		}

19 Source : SelectionMouseHandler.cs
with MIT License
from Abdesol

void ExtendSelectionToMouse(MouseEventArgs e)
		{
			TextViewPosition oldPosition = textArea.Caret.Position;
			if (mode == MouseSelectionMode.Normal || mode == MouseSelectionMode.Rectangular) {
				SetCaretOffsetToMousePosition(e);
				if (mode == MouseSelectionMode.Normal && textArea.Selection is RectangleSelection)
					textArea.Selection = new SimpleSelection(textArea, oldPosition, textArea.Caret.Position);
				else if (mode == MouseSelectionMode.Rectangular && !(textArea.Selection is RectangleSelection))
					textArea.Selection = new RectangleSelection(textArea, oldPosition, textArea.Caret.Position);
				else
					textArea.Selection = textArea.Selection.StartSelectionOrSetEndpoint(oldPosition, textArea.Caret.Position);
			} else if (mode == MouseSelectionMode.WholeWord || mode == MouseSelectionMode.WholeLine) {
				var newWord = (mode == MouseSelectionMode.WholeLine) ? GetLineAtMousePosition(e) : GetWordAtMousePosition(e);
				if (newWord != SimpleSegment.Invalid) {
					textArea.Selection = Selection.Create(textArea,
														  Math.Min(newWord.Offset, startWord.Offset),
														  Math.Max(newWord.EndOffset, startWord.EndOffset));
					// moves caret to start or end of selection
					if (newWord.Offset < startWord.Offset)
						textArea.Caret.Offset = newWord.Offset;
					else
						textArea.Caret.Offset = Math.Max(newWord.EndOffset, startWord.EndOffset);
				}
			}
			textArea.Caret.BringCaretToView(5.0);
		}

19 Source : SliceStream.cs
with MIT License
from abdullin

public override long Seek(long offset, SeekOrigin origin)
		{
			if (!m_slice.HasValue) StreamIsClosed();
			if (offset > int.MaxValue) throw new ArgumentOutOfRangeException("offset");

			switch (origin)
			{
				case SeekOrigin.Begin:
					{
						break;
					}
				case SeekOrigin.Current:
					{
						offset += m_position;
						break;
					}
				case SeekOrigin.End:
					{
						offset = m_slice.Count - offset;
						break;
					}
				default:
					{
						throw new ArgumentException("origin");
					}
			}

			if (offset < 0) throw new IOException("Cannot seek before the beginning of the slice");

			// clip to the slice bounds
			offset = Math.Min(offset, m_slice.Count);

			m_position = (int)offset;

			Contract.Ensures(m_position >= 0 && m_position <= m_slice.Count);

			return offset;

		}

19 Source : SliceStream.cs
with MIT License
from abdullin

public override int Read(byte[] buffer, int offset, int count)
		{
			ValidateBuffer(buffer, offset, count);

			if (!m_slice.HasValue) StreamIsClosed();

			Contract.Ensures(m_position >= 0 && m_position <= m_slice.Count);

			int remaining = Math.Min(m_slice.Count - m_position, count);
			if (remaining <= 0) return 0;

			int pos = m_position;
			int start = m_slice.Offset + pos;

			if (remaining <= 8)
			{ // too small, copy it ourselves
				int n = remaining;
				while (n-- > 0)
				{
					buffer[offset + n] = m_slice.Array[start + n];
				}
			}
			else
			{ // large enough
				Buffer.BlockCopy(m_slice.Array, start, buffer, offset, remaining);
			}

			m_position += remaining;
			Contract.Ensures(m_position >= 0 && m_position <= m_slice.Count);
			return remaining;
		}

19 Source : SingleCharacterElementGenerator.cs
with MIT License
from Abdesol

public override Rect ComputeBoundingBox(bool rightToLeft, bool sideways)
			{
				double width = Math.Min(0, element.text.WidthIncludingTrailingWhitespace - 1);
				return new Rect(0, 0, width, element.text.Height);
			}

19 Source : HololensLaserPointerDetection.cs
with Apache License 2.0
from abist-co-ltd

private Mat getROI(Mat img)
        {
            int w = img.width();
            int h = img.height();
            int ROIwidth = Math.Max(0, Math.Min(w, ((int) Math.Round(w * detectionArea.x * 0.5 )) * 2));
            int ROIheight = Math.Max(0, Math.Min(h, ((int)Math.Round(h * detectionArea.y * 0.5)) * 2));
            Rect ROI = new Rect((w - ROIwidth) / 2, (h - ROIheight) / 2, ROIwidth, ROIheight);

            return new Mat(img, ROI);
        }

19 Source : P2PManager.cs
with MIT License
from absurd-joy

public void GetRemoteHeadTransform(Transform headTransform)
		{
			bool hasNewTransform = false;

			Packet packet;
			while ((packet = Net.ReadPacket()) != null)
			{
				if (packet.Size != PACKET_SIZE)
				{
					Debug.Log("Invalid packet size: " + packet.Size);
					continue;
				}

				packet.ReadBytes(receiveTransformBuffer);

				if (receiveTransformBuffer[0] != PACKET_FORMAT)
				{
					Debug.Log("Invalid packet type: " + packet.Size);
					continue;
				}
				hasNewTransform = true;
			}

			if (hasNewTransform)
			{
				receivedPositionPrior = receivedPosition;
				receivedPosition.x = BitConverter.ToSingle(receiveTransformBuffer, 1);
				receivedPosition.y = BitConverter.ToSingle(receiveTransformBuffer, 5);
				receivedPosition.z = BitConverter.ToSingle(receiveTransformBuffer, 9);

				receivedRotationPrior = receivedRotation;
				receivedRotation.x = BitConverter.ToSingle(receiveTransformBuffer, 13);
				receivedRotation.y = BitConverter.ToSingle(receiveTransformBuffer, 17) * -1.0f;
				receivedRotation.z = BitConverter.ToSingle(receiveTransformBuffer, 21);
				receivedRotation.w = BitConverter.ToSingle(receiveTransformBuffer, 25) * -1.0f;

				receivedTime = Time.time;
			}

			// since we're receiving updates at a slower rate than we render,
			// interpolate to make the motion look smoother
			float completed = Math.Min(Time.time - receivedTime, UPDATE_DELAY) / UPDATE_DELAY;
			headTransform.localPosition =
				Vector3.Lerp(receivedPositionPrior, receivedPosition, completed);
			headTransform.localRotation =
				Quaternion.Slerp(receivedRotationPrior, receivedRotation, completed);
		}

19 Source : BoxAnnotation3D.cs
with MIT License
from ABTSoftware

void inverseTransform()
		{
			var xCoordinateCalculator = this.RootSceneEnreplacedy.Viewport3D.ParentSurface.XAxis.GetCurrentCoordinateCalculator();
			var yCoordinateCalculator = this.RootSceneEnreplacedy.Viewport3D.ParentSurface.YAxis.GetCurrentCoordinateCalculator();
			var zCoordinateCalculator = this.RootSceneEnreplacedy.Viewport3D.ParentSurface.ZAxis.GetCurrentCoordinateCalculator();

			var worldCenter = getWorldCenter();

			var rangeXStart = xCoordinateCalculator.GetDataValue(_topLeft.x + worldCenter.x);
			var rangeXEnd = xCoordinateCalculator.GetDataValue(_bottomRight.x + worldCenter.x);

			RangeX = new DoubleRange(Math.Min(rangeXStart, rangeXEnd), Math.Max(rangeXStart, rangeXEnd));

			var rangeYStart = yCoordinateCalculator.GetDataValue(_topLeft.y + worldCenter.y);
			var rangeYEnd = yCoordinateCalculator.GetDataValue(_bottomRight.y + worldCenter.y);

			RangeY = new DoubleRange(Math.Min(rangeYStart, rangeYEnd), Math.Max(rangeYStart, rangeYEnd));

			var rangeZStart = zCoordinateCalculator.GetDataValue(_topLeft.z + worldCenter.z);
			var rangeZEnd = zCoordinateCalculator.GetDataValue(_bottomRight.z + worldCenter.z);

			RangeZ = new DoubleRange(Math.Min(rangeZStart, rangeZEnd), Math.Max(rangeZStart, rangeZEnd));

			worldCenter.Dispose();
		}

19 Source : Spell.cs
with GNU Affero General Public License v3.0
from ACEmulator

public List<uint> TryBurnComponents(Player player)
        {
            var consumed = new List<uint>();

            // the base rate for each component is defined per-spell
            var baseRate = ComponentLoss;

            // get magic skill mod
            var magicSkill = GetMagicSkill();
            var playerSkill = player.GetCreatureSkill(magicSkill);
            var skillMod = Math.Min(1.0f, (float)Power / playerSkill.Current);
            //Console.WriteLine($"TryBurnComponents.SkillMod: {skillMod}");

            //DebugComponents();

            foreach (var component in Formula.CurrentFormula)
            {
                if (!SpellFormula.SpellComponentsTable.SpellComponents.TryGetValue(component, out var spellComponent))
                {
                    Console.WriteLine($"Spell.TryBurnComponents(): Couldn't find SpellComponent {component}");
                    continue;
                }

                // component burn rate = spell base rate * component destruction modifier * skillMod?
                var burnRate = baseRate * spellComponent.CDM * skillMod;

                // TODO: curve?
                var rng = ThreadSafeRandom.Next(0.0f, 1.0f);
                if (rng < burnRate)
                    consumed.Add(component);
            }
            return consumed;
        }

19 Source : DamageEvent.cs
with GNU Affero General Public License v3.0
from ACEmulator

private float DoCalculateDamage(Creature attacker, Creature defender, WorldObject damageSource)
        {
            var playerAttacker = attacker as Player;
            var playerDefender = defender as Player;

            var pkBattle = playerAttacker != null && playerDefender != null;

            Attacker = attacker;
            Defender = defender;

            CombatType = damageSource.ProjectileSource == null ? CombatType.Melee : CombatType.Missile;

            DamageSource = damageSource;

            Weapon = damageSource.ProjectileSource == null ? attacker.GetEquippedMeleeWeapon() : (damageSource.ProjectileLauncher ?? damageSource.ProjectileAmmo);

            AttackType = attacker.AttackType;
            AttackHeight = attacker.AttackHeight ?? AttackHeight.Medium;

            // check lifestone protection
            if (playerDefender != null && playerDefender.UnderLifestoneProtection)
            {
                LifestoneProtection = true;
                playerDefender.HandleLifestoneProtection();
                return 0.0f;
            }

            if (defender.Invincible)
                return 0.0f;

            // overpower
            if (attacker.Overpower != null)
                Overpower = Creature.GetOverpower(attacker, defender);

            // evasion chance
            if (!Overpower)
            {
                EvasionChance = GetEvadeChance(attacker, defender);
                if (EvasionChance > ThreadSafeRandom.Next(0.0f, 1.0f))
                {
                    Evaded = true;
                    return 0.0f;
                }
            }

            // get base damage
            if (playerAttacker != null)
                GetBaseDamage(playerAttacker);
            else
                GetBaseDamage(attacker, AttackMotion ?? MotionCommand.Invalid, AttackHook);

            if (DamageType == DamageType.Undef && !AllowDamageTypeUndef.Contains(damageSource.WeenieClreplacedId))
            {
                log.Error($"DamageEvent.DoCalculateDamage({attacker?.Name} ({attacker?.Guid}), {defender?.Name} ({defender?.Guid}), {damageSource?.Name} ({damageSource?.Guid})) - DamageType == DamageType.Undef");
                GeneralFailure = true;
            }

            if (GeneralFailure) return 0.0f;

            // get damage modifiers
            PowerMod = attacker.GetPowerMod(Weapon);
            AttributeMod = attacker.GetAttributeMod(Weapon);
            SlayerMod = WorldObject.GetWeaponCreatureSlayerModifier(Weapon, attacker, defender);

            // ratings
            DamageRatingBaseMod = Creature.GetPositiveRatingMod(attacker.GetDamageRating());
            RecklessnessMod = Creature.GetRecklessnessMod(attacker, defender);
            SneakAttackMod = attacker.GetSneakAttackMod(defender);
            HeritageMod = attacker.GetHeritageBonus(Weapon) ? 1.05f : 1.0f;

            DamageRatingMod = Creature.AdditiveCombine(DamageRatingBaseMod, RecklessnessMod, SneakAttackMod, HeritageMod);

            if (pkBattle)
            {
                PkDamageMod = Creature.GetPositiveRatingMod(attacker.GetPKDamageRating());
                DamageRatingMod = Creature.AdditiveCombine(DamageRatingMod, PkDamageMod);
            }

            // damage before mitigation
            DamageBeforeMitigation = BaseDamage * AttributeMod * PowerMod * SlayerMod * DamageRatingMod;

            // critical hit?
            var attackSkill = attacker.GetCreatureSkill(attacker.GetCurrentWeaponSkill());
            CriticalChance = WorldObject.GetWeaponCriticalChance(Weapon, attacker, attackSkill, defender);

            // https://asheron.fandom.com/wiki/Announcements_-_2002/08_-_Atonement
            // It should be noted that any time a character is logging off, PK or not, all physical attacks against them become automatically critical.
            // (Note that spells do not share this behavior.) We hope this will stress the need to log off in a safe place.

            if (playerDefender != null && (playerDefender.IsLoggingOut || playerDefender.PKLogout))
                CriticalChance = 1.0f;

            if (CriticalChance > ThreadSafeRandom.Next(0.0f, 1.0f))
            {
                if (playerDefender != null && playerDefender.AugmentationCriticalDefense > 0)
                {
                    var criticalDefenseMod = playerAttacker != null ? 0.05f : 0.25f;
                    var criticalDefenseChance = playerDefender.AugmentationCriticalDefense * criticalDefenseMod;

                    if (criticalDefenseChance > ThreadSafeRandom.Next(0.0f, 1.0f))
                        CriticalDefended = true;
                }

                if (!CriticalDefended)
                {
                    IsCritical = true;

                    // verify: CriticalMultiplier only applied to the additional crit damage,
                    // whereas CD/CDR applied to the total damage (base damage + additional crit damage)
                    CriticalDamageMod = 1.0f + WorldObject.GetWeaponCritDamageMod(Weapon, attacker, attackSkill, defender);

                    CriticalDamageRatingMod = Creature.GetPositiveRatingMod(attacker.GetCritDamageRating());

                    // recklessness excluded from crits
                    RecklessnessMod = 1.0f;
                    DamageRatingMod = Creature.AdditiveCombine(DamageRatingBaseMod, CriticalDamageRatingMod, SneakAttackMod, HeritageMod);

                    if (pkBattle)
                        DamageRatingMod = Creature.AdditiveCombine(DamageRatingMod, PkDamageMod);

                    DamageBeforeMitigation = BaseDamageMod.MaxDamage * AttributeMod * PowerMod * SlayerMod * DamageRatingMod * CriticalDamageMod;
                }
            }

            // armor rending and cleaving
            var armorRendingMod = 1.0f;
            if (Weapon != null && Weapon.HasImbuedEffect(ImbuedEffectType.ArmorRending))
                armorRendingMod = WorldObject.GetArmorRendingMod(attackSkill);

            var armorCleavingMod = attacker.GetArmorCleavingMod(Weapon);

            var ignoreArmorMod = Math.Min(armorRendingMod, armorCleavingMod);

            // get body part / armor pieces / armor modifier
            if (playerDefender != null)
            {
                // select random body part @ current attack height
                GetBodyPart(AttackHeight);

                // get player armor pieces
                Armor = attacker.GetArmorLayers(playerDefender, BodyPart);

                // get armor modifiers
                ArmorMod = attacker.GetArmorMod(playerDefender, DamageType, Armor, Weapon, ignoreArmorMod);
            }
            else
            {
                // determine height quadrant
                Quadrant = GetQuadrant(Defender, Attacker, AttackHeight, DamageSource);

                // select random body part @ current attack height
                GetBodyPart(Defender, Quadrant);
                if (Evaded)
                    return 0.0f;

                Armor = CreaturePart.GetArmorLayers(PropertiesBodyPart.Key);

                // get target armor
                ArmorMod = CreaturePart.GetArmorMod(DamageType, Armor, Attacker, Weapon, ignoreArmorMod);
            }

            if (Weapon != null && Weapon.HasImbuedEffect(ImbuedEffectType.IgnoreAllArmor))
                ArmorMod = 1.0f;

            // get resistance modifiers
            WeaponResistanceMod = WorldObject.GetWeaponResistanceModifier(Weapon, attacker, attackSkill, DamageType);

            if (playerDefender != null)
            {
                ResistanceMod = playerDefender.GetResistanceMod(DamageType, Attacker, Weapon, WeaponResistanceMod);
            }
            else
            {
                var resistanceType = Creature.GetResistanceType(DamageType);
                ResistanceMod = (float)Math.Max(0.0f, defender.GetResistanceMod(resistanceType, Attacker, Weapon, WeaponResistanceMod));
            }

            // damage resistance rating
            DamageResistanceRatingMod = DamageResistanceRatingBaseMod = defender.GetDamageResistRatingMod(CombatType);

            if (IsCritical)
            {
                CriticalDamageResistanceRatingMod = Creature.GetNegativeRatingMod(defender.GetCritDamageResistRating());

                DamageResistanceRatingMod = Creature.AdditiveCombine(DamageResistanceRatingBaseMod, CriticalDamageResistanceRatingMod);
            }

            if (pkBattle)
            {
                PkDamageResistanceMod = Creature.GetNegativeRatingMod(defender.GetPKDamageResistRating());

                DamageResistanceRatingMod = Creature.AdditiveCombine(DamageResistanceRatingMod, PkDamageResistanceMod);
            }

            // get shield modifier
            ShieldMod = defender.GetShieldMod(attacker, DamageType, Weapon);

            // calculate final output damage
            Damage = DamageBeforeMitigation * ArmorMod * ShieldMod * ResistanceMod * DamageResistanceRatingMod;

            DamageMitigated = DamageBeforeMitigation - Damage;

            return Damage;
        }

19 Source : Proficiency.cs
with GNU Affero General Public License v3.0
from ACEmulator

public static void OnSuccessUse(Player player, CreatureSkill skill, uint difficulty)
        {
            //Console.WriteLine($"Proficiency.OnSuccessUse({player.Name}, {skill.Skill}, targetDiff: {difficulty})");

            // TODO: this formula still probably needs some work to match up with retail truly...

            // possible todo: does this only apply to players?
            // ie., can monsters still level up from skill usage, or killing players?
            // it was possible on release, but i think they might have removed that feature?

            if (player.IsOlthoiPlayer)
                return;

            // ensure skill is at least trained
            if (skill.AdvancementClreplaced < SkillAdvancementClreplaced.Trained)
                return;

            var last_difficulty = skill.PropertiesSkill.ResistanceAtLastCheck;
            var last_used_time = skill.PropertiesSkill.LastUsedTime;

            var currentTime = Time.GetUnixTime();

            var timeDiff = currentTime - last_used_time;

            if (timeDiff < 0)
            {
                // can happen if server clock is rewound back in time
                log.Warn($"Proficiency.OnSuccessUse({player.Name}, {skill.Skill}, {difficulty}) - timeDiff: {timeDiff}");
                skill.PropertiesSkill.LastUsedTime = currentTime;       // update to prevent log spam
                return;
            }

            var difficulty_check = difficulty > last_difficulty;
            var time_check = timeDiff >= FullTime.TotalSeconds;

            if (difficulty_check || time_check)
            {
                // todo: not independent variables?
                // always scale if timeDiff < FullTime?
                var timeScale = 1.0f;
                if (!time_check)
                {
                    // 10 mins elapsed from 15 min FullTime:
                    // 0.66f timeScale
                    timeScale = (float)(timeDiff / FullTime.TotalSeconds);

                    // any rng involved?
                }

                skill.PropertiesSkill.ResistanceAtLastCheck = difficulty;
                skill.PropertiesSkill.LastUsedTime = currentTime;

                player.ChangesDetected = true;

                if (player.IsMaxLevel) return;

                var pp = (uint)Math.Round(difficulty * timeScale);
                var totalXPGranted = (long)Math.Round(pp * 1.1f);   // give additional 10% of proficiency XP to unreplacedigned XP

                if (totalXPGranted > 10000)
                {
                    log.Warn($"Proficiency.OnSuccessUse({player.Name}, {skill.Skill}, {difficulty}) - totalXPGranted: {totalXPGranted:N0}");
                }

                var maxLevel = Player.GetMaxLevel();
                var remainingXP = player.GetRemainingXP(maxLevel).Value;

                if (totalXPGranted > remainingXP)
                {
                    // checks and balances:
                    // total xp = pp * 1.1
                    // pp = total xp / 1.1

                    totalXPGranted = remainingXP;
                    pp = (uint)Math.Round(totalXPGranted / 1.1f);
                }

                // if skill is maxed out, but player is below MaxLevel,
                // not sure if retail granted 0%, 10%, or 110% of the pp to TotalExperience here
                // since pp is such a miniscule system at the higher levels,
                // going to just naturally add it to TotalXP for now..

                pp = Math.Min(pp, skill.ExperienceLeft);

                //Console.WriteLine($"Earned {pp} PP ({skill.Skill})");

                // send CP to player as unreplacedigned XP
                player.GrantXP(totalXPGranted, XpType.Proficiency, ShareType.None);

                // send PP to player as skill XP, which gets spent from the CP sent
                if (pp > 0)
                {
                    player.HandleActionRaiseSkill(skill.Skill, pp);
                }
            }
        }

19 Source : LootGenerationFactory_Clothing.cs
with GNU Affero General Public License v3.0
from ACEmulator

private static void MutateValue_Armor(WorldObject wo)
        {
            var bulkMod = wo.BulkMod ?? 1.0f;
            var sizeMod = wo.SizeMod ?? 1.0f;

            var armorLevel = wo.ArmorLevel ?? 0;

            // from the py16 mutation scripts
            //wo.Value += (int)(armorLevel * armorLevel / 10.0f * bulkMod * sizeMod);

            // still probably not how retail did it
            // modified for armor values to match closer to retail pcaps
            var minRng = (float)Math.Min(bulkMod, sizeMod);
            var maxRng = (float)Math.Max(bulkMod, sizeMod);

            var rng = ThreadSafeRandom.Next(minRng, maxRng);

            wo.Value += (int)(armorLevel * armorLevel / 10.0f * rng);
        }

19 Source : AllegianceManager.cs
with GNU Affero General Public License v3.0
from ACEmulator

private static void DoPreplacedXP(AllegianceNode vreplacedalNode, ulong amount, bool direct)
        {
            // http://asheron.wikia.com/wiki/Allegiance_Experience

            // Pre-patch:
            // Vreplacedal-to-patron preplaced-up has no effective cap, but patron-to-grandpatron preplaced-up caps with an effective Loyalty of 175.
            // If you're sworn for 10 days to the same patron, the base Loyalty required to maximize the preplaced-up from your vreplacedal through you to your patron is only 88.
            // Take into account level 7 enchantments, and you can see how there's practically no need to spend XP on the skill, due to the ease in reaching the cap.
            // Leadership is arguably worse off. In theory, you need to train Leadership and spend XP on it in order to get maximum results.
            // However, effective Leadership is multiplied by two factors: how many vreplacedals you have, and how long they have been sworn to you, with the emphasis on the number of vreplacedals you have.
            // The effect of Leadership on preplaced-up caps at around 165 effective Leadership, or 83 base Leadership before the modifier.
            // The end result of this is that if you have two active vreplacedals and you can get 10 mules sworn underneath you for an average of 5 in-game days,
            // you never need to raise your Leadership beyond 83. Again, take into account level 7 enchantments and you can see why few people even bother training the skill. It's just too easy to reach the cap. 

            // Post-patch:
            // - Leadership and Loyalty are not based on Self attribute
            // - Effective Loyalty is still modified by the time you have spent sworn to your patron
            // - Effective Leadership is still modified by number of vreplacedals and average time that they have been sworn to you,
            //   but the emphasis is on the "time sworn" side and not on the "number of vreplacedals" side. In fact, the vreplacedals
            //   required to achieve the maximum benefit has been decreased from 12 to 4. This is to reduce the incentive of having non-playing vreplacedals.
            // - For both Loyalty and Leadership, the time sworn modifier will now be a factor of both in-game time and real time.
            // - Most importantly, Leadership and Loyalty no longer "cap"

            // XP preplaced-up:
            // - New minimums and maximums
            // - Vreplacedal-to-patron preplaced-up will have a minimum of 25% of earned XP, and a maximum of 90% of earned XP.
            //   Under the old system, the minimum was about 9% of earned XP, and the effective maximum was somewhere near 44% of earned XP.
            // - Patron-to-grandpatron preplaced-up will have a minimum of 0% of XP preplaceded-up by the patron's vreplacedal, and a maximum of 10% of preplaceded-up XP.
            //   Under the old system, the minimum was about 30% and the maximum was about 94%.

            // Original system: up to January 12, 2004
            // Follow-up: all XP instead of just kill XP: October 2009

            // Formulas:
            // http://asheron.wikia.com/wiki/XP_Preplacedup

            // Thanks for Xerxes of Thistledown, who verified accuracy over four months of testing and research!

            // Generated % - Percentage of XP preplaceded to the patron through the vreplacedal's earned XP (hunting and most quests).
            // Received % - Percentage of XP that patron will receive from his vreplacedal's Generated XP.
            // Preplacedup % -  Percentage of XP actually received by patron from vreplacedal's earned XP (hunting and most quests).

            // Generated % = 50.0 + 22.5 * (loyalty / 291) * (1.0 + (RT/730) * (IG/720))
            // Received % = 50.0 + 22.5 * (leadership / 291) * (1.0 + V * (RT2/730) * (IG2/720))
            // Preplacedup % = Generated% * Received% / 100.0

            // Where:
            // Loyalty = Buffed Loyalty (291 max)
            // Leadership = Buffed Leadership (291 max)
            // RT = actual real time sworn to patron in days (730 max)
            // IG = actual in-game time sworn to patron in hours (720 max)
            // RT2 = average real time sworn to patron for all vreplacedals in days (730 max)
            // IG2 = average in-game time sworn to patron for all vreplacedals in hours (720 max)
            // V = vreplacedal factor(1 = 0.25, 2 = 0.50, 3 = 0.75, 4 + = 1.00) (1.0 max)

            var patronNode = vreplacedalNode.Patron;
            if (patronNode == null)
                return;

            var vreplacedal = vreplacedalNode.Player;
            var patron = patronNode.Player;

            if (!vreplacedal.ExistedBeforeAllegianceXpChanges)
                return;

            var loyalty = Math.Min(vreplacedal.GetCurrentLoyalty(), SkillCap);
            var leadership = Math.Min(patron.GetCurrentLeadership(), SkillCap);

            var timeReal = Math.Min(RealCap, RealCap);
            var timeGame = Math.Min(GameCap, GameCap);

            var timeRealAvg = Math.Min(RealCap, RealCap);
            var timeGameAvg = Math.Min(GameCap, GameCap);

            var vreplacedalFactor = Math.Min(0.25f * patronNode.TotalVreplacedals, 1.0f);

            var factor1 = direct ? 50.0f : 16.0f;
            var factor2 = direct ? 22.5f : 8.0f;

            var generated = (factor1 + factor2 * (loyalty / SkillCap) * (1.0f + (timeReal / RealCap) * (timeGame / GameCap))) * 0.01f;
            var received = (factor1 + factor2 * (leadership / SkillCap) * (1.0f + vreplacedalFactor * (timeRealAvg / RealCap) * (timeGameAvg / GameCap))) * 0.01f;
            var preplacedup = generated * received;

            var generatedAmount = (uint)(amount * generated);
            var preplacedupAmount = (uint)(amount * preplacedup);

            /*Console.WriteLine("---");
            Console.WriteLine("AllegianceManager.PreplacedXP(" + amount + ")");
            Console.WriteLine("Vreplacedal: " + vreplacedal.Name);
            Console.WriteLine("Patron: " + patron.Name);

            Console.WriteLine("Generated: " + Math.Round(generated * 100, 2) + "%");
            Console.WriteLine("Received: " + Math.Round(received * 100, 2) + "%");
            Console.WriteLine("Preplacedup: " + Math.Round(preplacedup * 100, 2) + "%");

            Console.WriteLine("Generated amount: " + generatedAmount);
            Console.WriteLine("Preplacedup amount: " + preplacedupAmount);*/

            if (preplacedupAmount > 0)
            {
                //vreplacedal.CPreplacedhed += generatedAmount;
                //patron.CPCached += preplacedupAmount;
                //patron.CPPoolToUnload += preplacedupAmount;

                vreplacedal.AllegianceXPGenerated += generatedAmount;
                patron.AllegianceXPCached += preplacedupAmount;

                var onlinePatron = PlayerManager.GetOnlinePlayer(patron.Guid);
                if (onlinePatron != null)
                    onlinePatron.AddAllegianceXP();

                // call recursively
                DoPreplacedXP(patronNode, preplacedupAmount, false);
            }
        }

19 Source : LandblockStruct.cs
with GNU Affero General Public License v3.0
from ACEmulator

public void TransAdjust()
        {
            // refactor me..
            if (TransDir == LandDefs.Direction.North || TransDir == LandDefs.Direction.NorthWest || TransDir == LandDefs.Direction.NorthEast)
            {
                for (var i = 1; i < SidePolyCount; i += 2)
                {
                    var v0 = VertexArray.Vertices[((i - 1) * SideVertexCount) + SidePolyCount];
                    var v1 = VertexArray.Vertices[((i + 1) * SideVertexCount) + SidePolyCount];
                    var v2 = VertexArray.Vertices[(i * SideVertexCount) + SidePolyCount];

                    v2.Origin.Z = (v0.Origin.Z + v1.Origin.Z) / 2;
                }
            }
            if (TransDir == LandDefs.Direction.West || TransDir == LandDefs.Direction.NorthWest || TransDir == LandDefs.Direction.SouthWest)
            {
                for (var i = 1; i < SidePolyCount; i += 2)
                {
                    var v0 = VertexArray.Vertices[i - 1];
                    var v1 = VertexArray.Vertices[i + 1];
                    var v2 = VertexArray.Vertices[i];

                    v2.Origin.Z = (v0.Origin.Z + v1.Origin.Z) / 2;
                }
            }
            if (TransDir == LandDefs.Direction.South || TransDir == LandDefs.Direction.SouthWest || TransDir == LandDefs.Direction.SouthEast)
            {
                for (var i = 1; i < SidePolyCount; i += 2)
                {
                    var v0 = VertexArray.Vertices[(i - 1) * SideVertexCount];
                    var v1 = VertexArray.Vertices[(i + 1) * SideVertexCount];
                    var v2 = VertexArray.Vertices[i * SideVertexCount];

                    v2.Origin.Z = (v0.Origin.Z + v1.Origin.Z) / 2;
                }
            }
            if (TransDir == LandDefs.Direction.East || TransDir == LandDefs.Direction.NorthEast || TransDir == LandDefs.Direction.SouthEast)
            {
                for (var i = 1; i < SidePolyCount; i += 2)
                {
                    var v0 = VertexArray.Vertices[SideVertexCount * SidePolyCount + i - 1];
                    var v1 = VertexArray.Vertices[SideVertexCount * SidePolyCount + i + 1];
                    var v2 = VertexArray.Vertices[SideVertexCount * SidePolyCount + i];

                    v2.Origin.Z = (v0.Origin.Z + v1.Origin.Z) / 2;
                }
            }

            if (SideCellCount != LandDefs.BlockSide / 2)
                return;

            if (TransDir == LandDefs.Direction.North)
            {
                for (int i = 1, j = 4; i < SidePolyCount; i += 2, j += 4)
                {
                    var vertex = VertexArray.Vertices[i * SideVertexCount];

                    var height0 = LandDefs.LandHeightTable[Height[(j - 1) * SideVertexCount]];
                    var height1 = LandDefs.LandHeightTable[Height[j * SideVertexCount]];
                    var height2 = LandDefs.LandHeightTable[Height[(j - 3) * SideVertexCount]];
                    var height3 = LandDefs.LandHeightTable[Height[(j - 4) * SideVertexCount]];

                    vertex.Origin.Z = Math.Min(vertex.Origin.Z, height2 * 2 - height3);
                    vertex.Origin.Z = Math.Min(vertex.Origin.Z, height0 * 2 - height1);
                }
            }

            if (TransDir == LandDefs.Direction.South)
            {
                for (int i = 1, j = 4; i < SidePolyCount; i += 2, j += 4)
                {
                    var vertex = VertexArray.Vertices[i * SideVertexCount + SidePolyCount];

                    var height0 = LandDefs.LandHeightTable[Height[(j - 1) * SideVertexCount + SideVertexCount - 1]];
                    var height1 = LandDefs.LandHeightTable[Height[j * SideVertexCount + SideVertexCount - 1]];
                    var height2 = LandDefs.LandHeightTable[Height[(j - 3) * SideVertexCount + SideVertexCount - 1]];
                    var height3 = LandDefs.LandHeightTable[Height[(j - 4) * SideVertexCount + SideVertexCount - 1]];

                    vertex.Origin.Z = Math.Min(vertex.Origin.Z, height2 * 2 - height3);
                    vertex.Origin.Z = Math.Min(vertex.Origin.Z, height0 * 2 - height1);
                }
            }

            if (TransDir == LandDefs.Direction.East)
            {
                for (int i = 1; i < SidePolyCount; i += 2)
                {
                    var vertex = VertexArray.Vertices[i];

                    var height0 = LandDefs.LandHeightTable[Height[i * 2 + 1]];
                    var height1 = LandDefs.LandHeightTable[Height[i * 2 + 2]];
                    var height2 = LandDefs.LandHeightTable[Height[i * 2 - 1]];
                    var height3 = LandDefs.LandHeightTable[Height[i * 2 - 2]];

                    vertex.Origin.Z = Math.Min(vertex.Origin.Z, height2 * 2 - height3);
                    vertex.Origin.Z = Math.Min(vertex.Origin.Z, height0 * 2 - height1);
                }
            }

            if (TransDir == LandDefs.Direction.West)
            {
                for (int i = 1; i < SidePolyCount; i += 2)
                {
                    var vertex = VertexArray.Vertices[i + SideVertexCount * SideVertexCount];

                    var height0 = LandDefs.LandHeightTable[Height[SideVertexCount * (SideVertexCount - 1) + i * 2 + 1]];
                    var height1 = LandDefs.LandHeightTable[Height[SideVertexCount * (SideVertexCount - 1) + i * 2 + 2]];
                    var height2 = LandDefs.LandHeightTable[Height[SideVertexCount * (SideVertexCount - 1) + i * 2 - 1]];
                    var height3 = LandDefs.LandHeightTable[Height[SideVertexCount * (SideVertexCount - 1) + i * 2 - 2]];

                    vertex.Origin.Z = Math.Min(vertex.Origin.Z, height2 * 2 - height3);
                    vertex.Origin.Z = Math.Min(vertex.Origin.Z, height0 * 2 - height1);
                }
            }
        }

19 Source : AllegianceData.cs
with GNU Affero General Public License v3.0
from ACEmulator

public static void Write(this BinaryWriter writer, AllegianceData data)
        {
            // ObjectID - characterID - Character ID
            // uint - cpCached - XP gained while logged off
            // uint - cpreplacedhed - Total allegiance XP contribution
            // uint - bitfield - AllegianceIndex
            // Gender - gender - The gender of the character (for determining replacedle)
            // HeritageGroup - hg - The heritage of the character (for determining replacedle)
            // ushort - rank - The numerical rank (1 is lowest).

            // Choose valid sections by masking against bitfield
            // uint - level

            // ushort - loyalty - Character loyalty
            // ushort - leadership - Character leadership

            // Choose based on testing bitfield == 0x4 (HasAllegianceAge)
            // True:
            // uint - timeOnline
            // uint - allegianceAge
            // False: (Not found in later retail pcaps. Probably deprecated.)
            // ulong - uTimeOnline

            // string - name

            uint characterID = 0;
            uint cpCached = 0;
            uint cpreplacedhed = 0;
            var bitfield = AllegianceIndex.HasAllegianceAge | AllegianceIndex.HasPackedLevel;
            var gender = Gender.Female;
            var hg = HeritageGroup.Aluvian;
            ushort rank = 0;
            uint level = 0;
            ushort loyalty = 0;
            ushort leadership = 0;
            ulong uTimeOnline = 0;
            uint timeOnline = 0;
            uint allegianceAge = 0;
            var name = "";

            if (data.Node != null)
            {
                var node = data.Node;
                var playerGuid = node.PlayerGuid;
                var player = PlayerManager.FindByGuid(playerGuid, out var playerIsOnline);
                
                characterID = player.Guid.Full;
                cpCached = (uint)Math.Min(player.AllegianceXPCached, uint.MaxValue);
                cpreplacedhed = (uint)Math.Min(player.AllegianceXPGenerated, uint.MaxValue);

                if (playerIsOnline)
                    bitfield |= AllegianceIndex.LoggedIn;

                if (!node.IsMonarch && node.Player.ExistedBeforeAllegianceXpChanges)
                    bitfield |= AllegianceIndex.MayPreplacedupExperience;

                gender = (Gender)player.Gender;
                hg = (HeritageGroup)player.Heritage;
                rank = (ushort)node.Rank;
                level = (uint)player.Level;
                loyalty = (ushort)player.GetCurrentLoyalty();
                leadership = (ushort)player.GetCurrentLeadership();
                
                //if (!node.IsMonarch)
                //{
                // TODO: Get/set total time sworn to patron (allegianceAge) and total in-game time since swearing to patron (timeOnline)
                //}

                name = player.Name;
                
            }

            writer.Write(characterID);
            writer.Write(cpCached);
            writer.Write(cpreplacedhed);
            writer.Write((uint)bitfield);
            writer.Write((byte)gender);
            writer.Write((byte)hg);
            writer.Write(rank);

            if (bitfield.HasFlag(AllegianceIndex.HasPackedLevel))
                writer.Write(level);

            writer.Write(loyalty);
            writer.Write(leadership);

            if (bitfield.HasFlag(AllegianceIndex.HasAllegianceAge))
            {
                writer.Write(timeOnline);
                writer.Write(allegianceAge);
            }
            else
                writer.Write(uTimeOnline);

            writer.WriteString16L(name);
        }

19 Source : Cloak.cs
with GNU Affero General Public License v3.0
from ACEmulator

public static bool RollProc(WorldObject cloak, float damage_percent)
        {
            // TODO: find retail formula

            var currentTime = Time.GetUnixTime();

            if (currentTime - cloak.UseTimestamp < MinDelay)
                return false;

            var itemLevel = cloak.ItemLevel ?? 0;

            if (itemLevel < 1) return false;

            var maxProcBase = MaxProcBase;

            if (HasDamageProc(cloak))
            {
                maxProcBase = MaxProcBase200;
                damage_percent *= TwoThirds;
            }

            var maxProcRate = maxProcBase + (itemLevel - 1) * 0.0125f;

            var chance = Math.Min(damage_percent, maxProcRate);

            var rng = ThreadSafeRandom.Next(0.0f, 1.0f);

            if (rng < chance)
            {
                cloak.UseTimestamp = currentTime;
                return true;
            }
            else
                return false;
        }

19 Source : HouseManager.cs
with GNU Affero General Public License v3.0
from ACEmulator

private static void PayRent(PlayerHouse playerHouse)
        {
            // load the most up-to-date copy of the house data
            GetHouse(playerHouse.House.Guid.Full, (house) =>
            {
                playerHouse.House = house;

                var isPaid = IsRentPaid(playerHouse) || playerHouse.House.HouseStatus <= HouseStatus.InActive;

                if (!isPaid)
                {
                    var houseData = GetHouseData(playerHouse.House);

                    foreach (var renreplacedem in houseData.Rent)
                    {
                        if (renreplacedem.Paid < renreplacedem.Num)
                        {
                            var amountLeftToPay = renreplacedem.Num - renreplacedem.Paid;

                            while (amountLeftToPay > 0)
                            {
                                var payment = WorldObjectFactory.CreateNewWorldObject(renreplacedem.WeenieID);

                                if (payment == null)
                                {
                                    log.Error($"[HOUSE] HouseManager.PayRent({house.Guid}): couldn't create payment for WCID {renreplacedem.WeenieID}");
                                    return;
                                }

                                payment.SetStackSize(Math.Min(amountLeftToPay, payment.MaxStackSize ?? 1));

                                if (!house.SlumLord.TryAddToInventory(payment))
                                {
                                    log.Error($"[HOUSE] HouseManager.PayRent({house.Guid}): couldn't place {payment.Name} (0x{payment.Guid}) in SlumLord's Inventory");
                                    return;
                                }

                                amountLeftToPay -= (payment.StackSize ?? 1);
                            }
                        }
                    }

                    house.SlumLord.MergeAllStackables();

                    house.SlumLord.SaveBiotaToDatabase();

                    var onlinePlayer = PlayerManager.GetOnlinePlayer(playerHouse.PlayerGuid);
                    if (onlinePlayer != null)
                    {
                        var actionChain = new ActionChain();
                        actionChain.AddDelaySeconds(3.0f);   // wait for slumlord inventory biotas above to save
                        actionChain.AddAction(onlinePlayer, onlinePlayer.HandleActionQueryHouse);
                        actionChain.EnqueueChain();
                    }
                }
            });
        }

19 Source : HouseData.cs
with GNU Affero General Public License v3.0
from ACEmulator

public void SetPaidItems(SlumLord slumlord)
        {
            foreach (var item in slumlord.Inventory.Values)
            {
                var wcid = item.WeenieClreplacedId;
                var value = item.StackSize ?? 1;
                if (item.WeenieClreplacedName.StartsWith("tradenote"))
                {
                    wcid = 273;
                    value = item.Value.Value;
                }
                var renreplacedem = Rent.FirstOrDefault(i => i.WeenieID == wcid);
                if (renreplacedem == null)
                {
                    Console.WriteLine($"HouseData.SetPaidItems({slumlord.Name}): couldn't find rent item {item.WeenieClreplacedId}");
                    continue;
                }
                renreplacedem.Paid = Math.Min(renreplacedem.Num, renreplacedem.Paid + value);
            }
        }

19 Source : PartArray.cs
with GNU Affero General Public License v3.0
from ACEmulator

public void UpdateParts(AFrame frame)
        {
            var curFrame = Sequence.GetCurrAnimFrame();
            if (curFrame == null)
            {
                if (Parts.Count == 1)
                    Parts[0].Pos = Owner.Position;
                return;
            }
            var numParts = Math.Min(NumParts, curFrame.Frames.Count);
            for (var i = 0; i < numParts; i++)
                Parts[i].Pos.Frame.Combine(frame, new AFrame(curFrame.Frames[i]), Scale);
        }

19 Source : Trajectory2.cs
with GNU Affero General Public License v3.0
from ACEmulator

public static Vector3 CalculateTrajectory(Vector3 startPos, Vector3 endPos, Vector3 targetVelocity, float speed, bool gravity)
        {
            var targetOffset = endPos - startPos;

            Vector3 result;
            float t = 0.0f;

            if (targetVelocity == Vector3.Zero)
            {
                var targetDist = targetOffset.Length();

                t = targetDist / speed;
                result = targetOffset / t;
            }
            else
            {
                var p0 = targetOffset;
                var p1 = Vector3.Zero;

                var v0 = targetVelocity;
                if (Vec.NormalizeCheckSmall(ref v0))
                    v0 = Vector3.Zero;

                var s1 = speed;

                var a = (v0.X * v0.X) + (v0.Y * v0.Y) - (s1 * s1);
                var b = 2 * ((p0.X * v0.X) + (p0.Y * v0.Y) - (p1.X * v0.X) - (p1.Y * v0.Y));
                var c = (p0.X * p0.X) + (p0.Y * p0.Y) + (p1.X * p1.X) + (p1.Y * p1.Y) - (2 * p1.X * p0.X) - (2 * p1.Y * p0.Y);

                var t0 = Math.Sqrt((b * b) - (4 * a * c));
                var t1 = (-b + t0) / (2 * a);
                var t2 = (-b - t0) / (2 * a);

                if (t1 < 0)
                    t1 = float.MaxValue;
                if (t2 < 0)
                    t2 = float.MaxValue;

                t = (float)Math.Min(t1, t2);

                if (t >= 100)
                    return CalculateTrajectory(startPos, endPos, Vector3.Zero, speed, gravity);

                var s0 = targetVelocity.Length();

                result = (p0 + t * s0 * v0) / t;
            }

            if (gravity)
                result.Z -= PhysicsGlobals.Gravity * t * 0.5f;

            return result;
        }

19 Source : AttributeTransferDevice.cs
with GNU Affero General Public License v3.0
from ACEmulator

public void ActOnUse(WorldObject activator, bool confirmed)
        {
            var player = activator as Player;
            if (player == null) return;

            if (TransferFromAttribute == PropertyAttribute.Undef || TransferToAttribute == PropertyAttribute.Undef)
                return;

            var device = player.FindObject(Guid.Full, Player.SearchLocations.MyInventory);
            if (device == null) return;

            var fromAttr = player.Attributes[TransferFromAttribute];
            var toAttr = player.Attributes[TransferToAttribute];

            if (fromAttr.StartingValue <= 10)
            {
                player.Session.Network.EnqueueSend(new GameMessageSystemChat($"Your innate {TransferFromAttribute} must be above 10 to use the {Name}.", ChatMessageType.Broadcast));
                return;
            }

            if (toAttr.StartingValue >= 100)
            {
                player.Session.Network.EnqueueSend(new GameMessageSystemChat($"Your innate {TransferToAttribute} must be below 100 to use the {Name}.", ChatMessageType.Broadcast));
                return;
            }

            if (!confirmed)
            {
                if (!player.ConfirmationManager.EnqueueSend(new Confirmation_AlterAttribute(player.Guid, Guid), $"This action will transfer 10 points from your {fromAttr.Attribute} to your {toAttr.Attribute}."))
                    player.SendWeenieError(WeenieError.ConfirmationInProgress);
                return;
            }

            var fromAmount = Math.Min(10, fromAttr.StartingValue - 10);
            var toAmount = Math.Min(100 - toAttr.StartingValue, 10);

            var amount = Math.Min(fromAmount, toAmount);

            fromAttr.StartingValue -= amount;
            toAttr.StartingValue += amount;

            var updateFrom = new GameMessagePrivateUpdateAttribute(player, fromAttr);
            var updateTo = new GameMessagePrivateUpdateAttribute(player, toAttr);

            var msgFrom = new GameMessageSystemChat($"Your base {TransferFromAttribute} is now {fromAttr.Base}!", ChatMessageType.Broadcast);
            var msgTo = new GameMessageSystemChat($"Your base {TransferToAttribute} is now {toAttr.Base}!", ChatMessageType.Broadcast);

            var sound = new GameMessageSound(player.Guid, Sound.RaiseTrait);

            player.Session.Network.EnqueueSend(updateFrom, updateTo, msgFrom, msgTo, sound);

            player.SaveBiotaToDatabase();

            player.TryConsumeFromInventoryWithNetworking(this, 1);
        }

19 Source : Container.cs
with GNU Affero General Public License v3.0
from ACEmulator

public void MergeAllStackables()
        {
            var inventory = Inventory.Values.ToList();

            for (int i = inventory.Count - 1; i > 0; i--)
            {
                var sourceItem = inventory[i];

                if (sourceItem.MaxStackSize == null || sourceItem.MaxStackSize <= 1)
                    continue;

                for (int j = 0; j < i; j++)
                {
                    var destinationItem = inventory[j];

                    if (destinationItem.WeenieClreplacedId != sourceItem.WeenieClreplacedId || destinationItem.StackSize == destinationItem.MaxStackSize)
                        continue;

                    var amount = Math.Min(sourceItem.StackSize ?? 0, (destinationItem.MaxStackSize - destinationItem.StackSize) ?? 0);

                    sourceItem.SetStackSize(sourceItem.StackSize - amount);

                    destinationItem.SetStackSize(destinationItem.StackSize + amount);

                    if (sourceItem.StackSize == 0)
                    {
                        TryRemoveFromInventory(sourceItem.Guid);
                        if (!sourceItem.IsDestroyed)
                            sourceItem.Destroy();
                        break;
                    }
                }
            }
        }

19 Source : Corpse.cs
with GNU Affero General Public License v3.0
from ACEmulator

public void TryGenerateRare(DamageHistoryInfo killer)
        {
            var killerPlayer = killer.TryGetAttacker() as Player;
            var timestamp = (int)Time.GetUnixTime();
            var luck = 0;
            var secondChanceGranted = false;

            var realTimeRares = PropertyManager.GetBool("rares_real_time").Item;
            var realTimeRaresAlt = PropertyManager.GetBool("rares_real_time_v2").Item;
            if (realTimeRares && killerPlayer != null)
            {
                if (killerPlayer.RaresLoginTimestamp.HasValue)
                {
                    // http://acpedia.org/wiki/Announcements_-_2010/04_-_Shedding_Skin#Rares_Update

                    // Real Time Rares work the same as they always have. It rolls a number between 1 second and 2 months worth of seconds. When that number is up you get an additional chance of finding a rare on any valid rare kill.
                    // That additional chance is very high. You can still only find one rare on any given kill but it's possible to find a normal rare when your Real Time Rare timer is up but you haven't found one yet.

                    var now = Time.GetDateTimeFromTimestamp(timestamp);
                    var playerLastRareFound = Time.GetDateTimeFromTimestamp(killerPlayer.RaresLoginTimestamp.Value);

                    if (now >= playerLastRareFound)
                        secondChanceGranted = true;
                }
                else
                    killerPlayer.RaresLoginTimestamp = (int)Time.GetFutureUnixTime(ThreadSafeRandom.Next(1, (int)PropertyManager.GetLong("rares_max_seconds_between").Item));
            }
            else if (realTimeRaresAlt && killerPlayer != null)
            {
                if (killerPlayer.RaresLoginTimestamp.HasValue)
                {
                    // This version of the system is based on interpretation of the following way the system was originally described. The one above is how it was stated to *really* works as detailed in a dev chat from 2010.

                    // http://acpedia.org/wiki/Rare#Real_Time_Rares

                    // Also there is a real time rare timer for each character, this timer starts the first time you kill a rare eligible creature. A character such as a mule that has never killed anything will not have an active timer.
                    // It works by looking at the real time that has elapsed since the last rare was found, it increases as the time gets closer to two months (real life time) at which point it is a 100% chance.
                    // People have found that for characters that don't normally hunt, it's best to take them out at at the 30 day mark and a rare will drop after a few kills (although it sometimes can take longer since it's still a % chance at the 30 day mark).

                    var now = Time.GetDateTimeFromTimestamp(timestamp);
                    var playerLastRareFound = Time.GetDateTimeFromTimestamp(killerPlayer.RaresLoginTimestamp.Value);
                    var timeBetweenRareSighting = now - playerLastRareFound;
                    var daysSinceRareSighting = timeBetweenRareSighting.TotalDays;

                    var maxDaysSinceLastRareFound = (int)PropertyManager.GetLong("rares_max_days_between").Item; // 30? 45? 60?
                    var chancesModifier = Math.Round(daysSinceRareSighting / maxDaysSinceLastRareFound, 2, MidpointRounding.ToZero);
                    var chancesModifierAdjusted = Math.Min(chancesModifier, 1.0f);

                    var t1_chance = 2500;
                    luck = (int)Math.Round(t1_chance * chancesModifierAdjusted, 0, MidpointRounding.ToZero);
                }
                else
                    killerPlayer.RaresLoginTimestamp = timestamp;
            }

            var wo = LootGenerationFactory.TryCreateRare(luck);

            if (secondChanceGranted && wo == null)
            {
                luck = 2490;
                wo = LootGenerationFactory.TryCreateRare(luck);
            }

            if (wo == null)
                return;

            if (!wo.IconUnderlayId.HasValue || wo.IconUnderlayId.Value != 0x6005B0C) // ensure icon underlay exists for rare (loot profiles use this)
                wo.IconUnderlayId = 0x6005B0C;

            var tier = LootGenerationFactory.GetRareTier(wo.WeenieClreplacedId);
            LootGenerationFactory.RareChances.TryGetValue(tier, out var chance);

            log.Debug($"[LOOT][RARE] {Name} ({Guid}) generated rare {wo.Name} ({wo.Guid}) for {killer.Name} ({killer.Guid})");
            log.Debug($"[LOOT][RARE] Tier {tier} -- 1 / {chance:N0} chance -- {luck:N0} luck");

            if (TryAddToInventory(wo))
            {
                rareGenerated = wo;
                killerName = killer.Name.TrimStart('+');
                CorpseGeneratedRare = true;
                LongDesc += " This corpse generated a rare item!";
                TimeToRot = 900;  // guesstimated 15 mins from hells

                if (killerPlayer != null)
                {
                    if (realTimeRares)
                        killerPlayer.RaresLoginTimestamp = (int)Time.GetFutureUnixTime(ThreadSafeRandom.Next(1, (int)PropertyManager.GetLong("rares_max_seconds_between").Item));
                    else
                        killerPlayer.RaresLoginTimestamp = timestamp;
                    switch (tier)
                    {
                        case 1:
                            killerPlayer.RaresTierOne++;
                            killerPlayer.RaresTierOneLogin = timestamp;
                            break;
                        case 2:
                            killerPlayer.RaresTierTwo++;
                            killerPlayer.RaresTierTwoLogin = timestamp;
                            break;
                        case 3:
                            killerPlayer.RaresTierThree++;
                            killerPlayer.RaresTierThreeLogin = timestamp;
                            break;
                        case 4:
                            killerPlayer.RaresTierFour++;
                            killerPlayer.RaresTierFourLogin = timestamp;
                            break;
                        case 5:
                            killerPlayer.RaresTierFive++;
                            killerPlayer.RaresTierFiveLogin = timestamp;
                            break;
                        case 6:
                            killerPlayer.RaresTierSix++;
                            killerPlayer.RaresTierSixLogin = timestamp;
                            break;
                        //case 7:
                        //    killerPlayer.RaresTierSeven++;
                        //    killerPlayer.RaresTierSevenLogin = timestamp;
                        //    break;
                    }
                }
            }
            else
                log.Error($"[RARE] failed to add to corpse inventory");
        }

19 Source : Creature.cs
with GNU Affero General Public License v3.0
from ACEmulator

public void GenerateNewFace()
        {
            var cg = DatManager.PortalDat.CharGen;

            if (!Heritage.HasValue)
            {
                if (!string.IsNullOrEmpty(HeritageGroupName) && Enum.TryParse(HeritageGroupName.Replace("'", ""), true, out HeritageGroup heritage))
                    Heritage = (int)heritage;
            }

            if (!Gender.HasValue)
            {
                if (!string.IsNullOrEmpty(Sex) && Enum.TryParse(Sex, true, out Gender gender))
                    Gender = (int)gender;
            }

            if (!Heritage.HasValue || !Gender.HasValue)
            {
#if DEBUG
                //if (!(NpcLooksLikeObject ?? false))
                    //log.Debug($"Creature.GenerateNewFace: {Name} (0x{Guid}) - wcid {WeenieClreplacedId} - Heritage: {Heritage} | HeritageGroupName: {HeritageGroupName} | Gender: {Gender} | Sex: {Sex} - Data missing or unparsable, Cannot randomize face.");
#endif
                return;
            }

            if (!cg.HeritageGroups.TryGetValue((uint)Heritage, out var heritageGroup) || !heritageGroup.Genders.TryGetValue((int)Gender, out var sex))
            {
#if DEBUG
                log.Debug($"Creature.GenerateNewFace: {Name} (0x{Guid}) - wcid {WeenieClreplacedId} - Heritage: {Heritage} | HeritageGroupName: {HeritageGroupName} | Gender: {Gender} | Sex: {Sex} - Data invalid, Cannot randomize face.");
#endif
                return;
            }

            PaletteBaseId = sex.BasePalette;

            var appearance = new Appearance
            {
                HairStyle = 1,
                HairColor = 1,
                HairHue = 1,

                EyeColor = 1,
                Eyes = 1,

                Mouth = 1,
                Nose = 1,

                SkinHue = 1
            };

            // Get the hair first, because we need to know if you're bald, and that's the name of that tune!
            if (sex.HairStyleList.Count > 1)
            {
                if (PropertyManager.GetBool("npc_hairstyle_fullrange").Item)
                    appearance.HairStyle = (uint)ThreadSafeRandom.Next(0, sex.HairStyleList.Count - 1);
                else
                    appearance.HairStyle = (uint)ThreadSafeRandom.Next(0, Math.Min(sex.HairStyleList.Count - 1, 8)); // retail range data compiled by OptimShi
            }
            else
                appearance.HairStyle = 0;

            if (sex.HairStyleList.Count < appearance.HairStyle)
            {
                log.Warn($"Creature.GenerateNewFace: {Name} (0x{Guid}) - wcid {WeenieClreplacedId} - HairStyle = {appearance.HairStyle} | HairStyleList.Count = {sex.HairStyleList.Count} - Data invalid, Cannot randomize face.");
                return;
            }

            var hairstyle = sex.HairStyleList[Convert.ToInt32(appearance.HairStyle)];

            appearance.HairColor = (uint)ThreadSafeRandom.Next(0, sex.HairColorList.Count - 1);
            appearance.HairHue = ThreadSafeRandom.Next(0.0f, 1.0f);

            appearance.EyeColor = (uint)ThreadSafeRandom.Next(0, sex.EyeColorList.Count - 1);
            appearance.Eyes = (uint)ThreadSafeRandom.Next(0, sex.EyeStripList.Count - 1);

            appearance.Mouth = (uint)ThreadSafeRandom.Next(0, sex.MouthStripList.Count - 1);

            appearance.Nose = (uint)ThreadSafeRandom.Next(0, sex.NoseStripList.Count - 1);

            appearance.SkinHue = ThreadSafeRandom.Next(0.0f, 1.0f);

            //// Certain races (Undead, Tumeroks, Others?) have multiple body styles available. This is controlled via the "hair style".
            ////if (hairstyle.AlternateSetup > 0)
            ////    character.SetupTableId = hairstyle.AlternateSetup;

            if (!EyesTextureDID.HasValue)
                EyesTextureDID = sex.GetEyeTexture(appearance.Eyes, hairstyle.Bald);
            if (!DefaultEyesTextureDID.HasValue)
                DefaultEyesTextureDID = sex.GetDefaultEyeTexture(appearance.Eyes, hairstyle.Bald);
            if (!NoseTextureDID.HasValue)
                NoseTextureDID = sex.GetNoseTexture(appearance.Nose);
            if (!DefaultNoseTextureDID.HasValue)
                DefaultNoseTextureDID = sex.GetDefaultNoseTexture(appearance.Nose);
            if (!MouthTextureDID.HasValue)
                MouthTextureDID = sex.GetMouthTexture(appearance.Mouth);
            if (!DefaultMouthTextureDID.HasValue)
                DefaultMouthTextureDID = sex.GetDefaultMouthTexture(appearance.Mouth);
            if (!HeadObjectDID.HasValue)
                HeadObjectDID = sex.GetHeadObject(appearance.HairStyle);

            // Skin is stored as PaletteSet (list of Palettes), so we need to read in the set to get the specific palette
            var skinPalSet = DatManager.PortalDat.ReadFromDat<PaletteSet>(sex.SkinPalSet);
            if (!SkinPaletteDID.HasValue)
                SkinPaletteDID = skinPalSet.GetPaletteID(appearance.SkinHue);

            // Hair is stored as PaletteSet (list of Palettes), so we need to read in the set to get the specific palette
            var hairPalSet = DatManager.PortalDat.ReadFromDat<PaletteSet>(sex.HairColorList[Convert.ToInt32(appearance.HairColor)]);
            if (!HairPaletteDID.HasValue)
                HairPaletteDID = hairPalSet.GetPaletteID(appearance.HairHue);

            // Eye Color
            if (!EyesPaletteDID.HasValue)
                EyesPaletteDID = sex.EyeColorList[Convert.ToInt32(appearance.EyeColor)];
        }

See More Examples