Beispiel #1
0
        public ColorUpdateResponse Update([FromBody] ColorUpdateRequest request)
        {
            ColorUpdateResponse response = new ColorUpdateResponse();

            if (request.Id == 0 || request.Id < 0)
            {
                response.Status = -1;
                return(response);
            }

            ColorEntity entity = colorRepository.GetById(request.Id);

            if (entity == null)
            {
                response.Status = 404;
                return(response);
            }

            colorRepository.Update(colorConvertor.toEntity(request, entity));

            metaColorProvider.Reload();

            response.Status = 1;
            return(response);
        }
        /// <summary>
        /// 将entity转换为vo
        /// </summary>
        public ColorExtendedVo toExtendedVo(ColorEntity entity)
        {
            ColorExtendedVo vo = new ColorExtendedVo();

            CopyToVo(vo, entity);

            return(vo);
        }
 /// <summary>
 /// 将entity转换为vo。不包括来自元数据的属性
 /// </summary>
 private void CopyToVo(ColorVo vo, ColorEntity entity)
 {
     vo.Id             = entity.Id;
     vo.ColorId        = entity.ColorId;
     vo.ColorName      = entity.ColorName;
     vo.DataStatus     = entity.DataStatus;
     vo.CreateTime     = entity.CreateTime;
     vo.LastUpdateTime = entity.LastUpdateTime;
 }
Beispiel #4
0
 public static ColorModel ToDto(ColorEntity entity)
 {
     return(new ColorModel
     {
         ClrID = entity.ClrID,
         ClrName = entity.ClrName,
         ClrEnabled = entity.ClrEnabled,
     });
 }
        /// <summary>
        /// 将entity转换为vo
        /// </summary>
        public ColorBasicVo toBasicVo(ColorEntity entity)
        {
            ColorBasicVo vo = new ColorBasicVo();

            CopyToVo(vo, entity);


            return(vo);
        }
Beispiel #6
0
        public bool InsertColor(ColorEntity color)
        {
            string sql = @"sp_color_INSERT";

            object[] obj = { "@ClrName", color.ClrName };
            using (TransactionScope ts = new TransactionScope())
            {
                try { Db.Insert(sql, obj); ts.Complete(); return(true); }
                catch { return(false); }
            }
        }
Beispiel #7
0
        public bool UpdateColor(ColorEntity color)
        {
            string sql = @"[sp_color_UPDATE]";

            object[] obj = { "@ClrID", color.ClrID, "@ClrName", color.ClrName };
            using (TransactionScope ts = new TransactionScope())
            {
                try { Db.Update(sql, obj); ts.Complete(); return(true); }
                catch { return(false); }
            }
        }
Beispiel #8
0
        /// <summary>
        /// 新增实体
        /// </summary>
        public void Create(ColorEntity entity)
        {
            string sql = @"
insert into color(color_id, color_name, data_status, create_time, last_update_time)
values(@ColorId, @ColorName, @DataStatus, @CreateTime, @LastUpdateTime);";

            using (var mysqlConn = connectionProvider.GetConnection())
            {
                mysqlConn.Execute(sql, entity);
            }
        }
Beispiel #9
0
        public async Task <ColorEntity> GetByIdAsync(long id)
        {
            var result = await _IRepository.GetById(id);

            var ColorEntity = new ColorEntity();

            ColorEntity.Id        = result.Id;
            ColorEntity.ColorName = result.ColorName;

            return(ColorEntity);
        }
Beispiel #10
0
        public static Color ToModel(this ColorEntity color)
        {
            Guard.AgainstNullArgument(color, nameof(color));

            return(new Color
            {
                Id = color.ColourId,
                Name = color.Name,
                IsEnabled = color.IsEnabled
            });
        }
Beispiel #11
0
 private void Awake()
 {
     realm       = Realm.GetInstance();
     squareColor = realm.Find <ColorEntity>("square");
     if (squareColor == null)
     {
         squareColor = new ColorEntity("square");
         realm.Write(() => {
             realm.Add(squareColor);
         });
     }
     SetColor();
 }
        public ColorEntity toEntity(ColorCreateRequest request)
        {
            ColorEntity entity = new ColorEntity();

            var item = request.Item;

            entity.ColorId        = item.ColorId;
            entity.ColorName      = item.ColorName;
            entity.DataStatus     = 1;
            entity.CreateTime     = TimeConvertor.FromMilliTicks(TimeConvertor.ToMilliTicks(DateTime.Now));
            entity.LastUpdateTime = TimeConvertor.FromMilliTicks(TimeConvertor.ToMilliTicks(DateTime.Now));

            return(entity);
        }
Beispiel #13
0
        public async Task <bool> AddAsync(ColorEntity color)
        {
            try
            {
                var obj = new ColorEntity();
                obj.ColorName = color.ColorName;
                var result = await _IRepository.Add(obj);

                return(result);
            }
            catch (Exception ex)
            {
                return(false);
            }
        }
Beispiel #14
0
        public async Task <bool> UpdateAsync(ColorEntity color)
        {
            try
            {
                var obj = new ColorEntity();
                obj.Id        = ColorEntity.Id;
                obj.ColorName = ColorEntity.ColorName;
                var result = await _IRepository.Update(obj);

                return(result);
            }
            catch (Exception)
            {
                return(false);
            }
        }
Beispiel #15
0
        public void ToModel_ValidColor_ReturnsExpectedEntity()
        {
            // Arrange
            var sut = new ColorEntity
            {
                ColourId  = 123,
                Name      = "red",
                IsEnabled = true
            };

            // Act
            var result = sut.ToModel();

            // Assert
            Assert.Equal(123, result.Id);
            Assert.Equal("red", result.Name);
            Assert.True(result.IsEnabled);
        }
        public static void Initialize(AssecorTaskDbContext context)
        {
            if (context.Colors.Any())
            {
                return;
            }

            for (int i = 0; i < Colors.Length; i++)
            {
                var color = new ColorEntity
                {
                    Color = Colors[i]
                };

                context.Colors.Add(color);
            }

            context.SaveChanges();
        }
Beispiel #17
0
        /// <summary>
        /// 更新实体
        /// </summary>
        public void Update(ColorEntity entity)
        {
            string sql = @"
update color
set 
  color_id = @ColorId,
  color_name = @ColorName,
  data_status = @DataStatus,
  create_time = @CreateTime,
  last_update_time = @LastUpdateTime,
  id = id
where
  id = @Id;";

            using (var mysqlConn = connectionProvider.GetConnection())
            {
                mysqlConn.Execute(sql, entity);
            }
        }
        public List <ColorEntity> getBitmapByAllPixel(Bitmap Image)
        {
            Color curColor;
            var   BitmapColorList = new List <ColorEntity>();

            for (int i = 1; i < Image.Width - 1; i++)
            {
                for (int j = 1; j < Image.Height - 1; j++)
                {
                    curColor = Image.GetPixel(i, j); //orj ilgili pixceldeki rengi alınır ve aşağıdaki sabit förmül ile set edilir. Asagıda yapılan r g b renklerine göre belli bir resim set edilir. eğer 120 den büyükse bu sayı threshold alırken ortalama renk kabul ediliyor. resmi full yapar değilse renkleri sıfırlar yani beyaz yapar.

                    var EntityColor = new ColorEntity();
                    EntityColor.Height       = j;
                    EntityColor.Weight       = i;
                    EntityColor.ColorByPixel = curColor;
                    BitmapColorList.Add(EntityColor);
                }
            }
            return(BitmapColorList);
        }
        public static MvcHtmlString ColorTextbox(this HtmlHelper helper, ValueLine valueLine)
        {
            HtmlStringBuilder sb = new HtmlStringBuilder();

            using (sb.SurroundLine(new HtmlTag("div").Class("input-group")))
            {
                valueLine.ValueHtmlProps.AddCssClass("form-control");

                ColorEntity color = (ColorEntity)valueLine.UntypedValue;

                sb.AddLine(helper.TextBox(valueLine.Prefix, color == null ? "" : color.RGBHex(), valueLine.ValueHtmlProps));

                sb.AddLine(new HtmlTag("span").Class("input-group-addon").InnerHtml(new HtmlTag("i")));
            }

            sb.AddLine(new HtmlTag("script").InnerHtml(MvcHtmlString.Create(
                                                           @" $(function(){
        $('#" + valueLine.Prefix + @"').parent().colorpicker()" + (valueLine.ReadOnly ? ".colorpicker('disable')" : null) + @";
   });")));

            return(sb.ToHtml());
        }
Beispiel #20
0
        public ColorItemResponse Item([FromBody] ColorItemRequest request)
        {
            ColorItemResponse response = new ColorItemResponse();

            if (request.Id <= 0)
            {
                response.Status = -1;
                return(response);
            }

            ColorEntity entity = colorRepository.GetById(request.Id);

            if (entity == null)
            {
                response.Status = 404;
                return(response);
            }

            response.Item = colorConvertor.toExtendedVo(entity);

            response.Status = 1;
            return(response);
        }
Beispiel #21
0
        private static void Main(string[] args)
        {
            const string colorNamesUrl =
                "https://raw.githubusercontent.com/meodai/color-names/master/src/colornames.csv";

            var sw = Stopwatch.StartNew();
            // int curStep = 0;

            var options = new ProgressBarOptions
            {
                ForegroundColor   = ConsoleColor.Yellow,
                BackgroundColor   = ConsoleColor.DarkYellow,
                ProgressCharacter = '─'
            };

            childOptions = new ProgressBarOptions
            {
                ForegroundColor      = ConsoleColor.Green,
                BackgroundColor      = ConsoleColor.DarkGreen,
                ProgressCharacter    = '─',
                CollapseWhenFinished = false
            };

            using (var progress = new ProgressBar(STEPS, string.Empty, options))
            {
                progress.Message = "Downloading content!";
                string csvContents;

                using (var wc = new WebClient())
                    using (var child = progress.Spawn((int)wc.GetBytes(colorNamesUrl), "bytes downloaded", childOptions))
                    {
                        wc.DownloadProgressChanged += (sender, e) => WcOnDownloadProgressChanged(sender, e, child);
                        csvContents = wc.DownloadString(colorNamesUrl);
                    }

                var lines = csvContents.GetLines();
                progress.MaxTicks = lines.Length + STEPS - 2;

                progress.Message = "Parsing entities!";
                List <ColorEntity> entities;

                using (var child = progress.Spawn(lines.Length, "lines parsed", childOptions))
                    entities = lines.Skip(1).Select(line =>
                    {
                        var split  = line.Split(',');
                        var entity = new ColorEntity {
                            Name = split[0], Hex = split[1]
                        };

                        child.Tick();

                        return(entity);
                    })
                               .ToList();

                string folder = Path.Combine(Environment.CurrentDirectory, "Generated");

                if (!Directory.Exists(folder))
                {
                    Directory.CreateDirectory(folder);
                }

                string generatedFile_ColorNames = Path.Combine(folder, "ColorNames.cs");
                string generatedFile_NamedColor = Path.Combine(folder, "NamedColor.cs");
                string generatedJSONFile        = Path.Combine(folder, "ColorNames.json");

#if !TEST
                progress.Message = "Saving ColorNames class!";

                Task.Factory.StartNew(() =>
                {
                    string contents_colorNames = CreateClass_ColorNames(entities, progress);
                    File.WriteAllText(generatedFile_ColorNames, contents_colorNames);
                });

                progress.Message = "Saving NamedColor class!";

                Task.Factory.StartNew(() =>
                {
                    string contents_namedColor = CreateClass_NamedColor(entities, progress);
                    File.WriteAllText(generatedFile_NamedColor, contents_namedColor);
                });

                progress.Message = "Generating dictionary!";

                Dictionary <Lib.ColorNames, ColorEntity> dict;
                Dictionary <string, Lib.ColorNames>      enumDict;
                Array enumArr = Enum.GetValues(typeof(Lib.ColorNames));

                using (var child = progress.Spawn(enumArr.Length, "enum items added to parse", childOptions))
                {
                    enumDict = enumArr
                               .Cast <Lib.ColorNames>()
                               .Select((x, i) => new { Item = x, Index = i })
                               .ToDictionary(t =>
                    {
                        child.Tick();

                        return(t.Item.ToString());
                    }, t => t.Item);
                }

                using (var child = progress.Spawn(enumArr.Length, "entities parsed", childOptions))
                {
                    dict = entities
                           .Select((x, i) => new { Item = x, Index = i })
                           .ToDictionary(t =>
                    {
                        child.Tick();

                        return(enumDict[t.Item.Name.SanitizeEnum()]);
                    }, t => t.Item);
                }

                string jsonContents = JsonConvert.SerializeObject(dict, Formatting.Indented);

                progress.Message = "Converting json!";
                File.WriteAllText(generatedJSONFile, jsonContents);

                sw.Stop();
                progress.Message = $"Converted successfully in {sw.ElapsedMilliseconds / 1000.0:F2} s!";
#else
                // Console.WriteLine("Saving NamedColor class!");
                string contents_namedColor = CreateClass_NamedColor(entities);
                Console.WriteLine(contents_namedColor);
#endif
            }

            Console.ReadLine();
        }
        public int getThresholdValuewithThreadDemo(Bitmap orjImage)
        {
            Bitmap newBitmap = new Bitmap(orjImage.Width, orjImage.Height); // Resmin Ortalamasını Aldıktak sonra set edilecek resim


            Color curColor;
            var   orjBitmapColorList = new List <ColorEntity>();

            for (int i = 1; i < newBitmap.Width - 1; i++)
            {
                for (int j = 1; j < newBitmap.Height - 1; j++)
                {
                    curColor = orjImage.GetPixel(i, j); //orj ilgili pixceldeki rengi alınır ve aşağıdaki sabit förmül ile set edilir. Asagıda yapılan r g b renklerine göre belli bir resim set edilir. eğer 120 den büyükse bu sayı threshold alırken ortalama renk kabul ediliyor. resmi full yapar değilse renkleri sıfırlar yani beyaz yapar.

                    var EntityColor = new ColorEntity();
                    EntityColor.Height       = j;
                    EntityColor.Weight       = i;
                    EntityColor.ColorByPixel = curColor;
                    orjBitmapColorList.Add(EntityColor);
                }
            }

            var ThresholdList = new List <int>();


            int ThreadsCount = Process.GetCurrentProcess().Threads.Count; // Sistemde Kaç çekirdek varsa

            ThreadsCount = 4;

            int height = 42;
            int weight = 42;
            int startH = 42;
            int startW = 42;


            if (ThreadsCount > 0)
            {
                var ThreadList = new List <Thread>();

                var tidH = orjImage.Height / ThreadsCount;
                var tidW = orjImage.Width / ThreadsCount;

                for (var ThreadByCount = 0; ThreadByCount < ThreadsCount; ThreadByCount++) // Çekirdek sayısı kadar Thread Oluştur.
                {
                    height = tidH * (ThreadByCount + 1);
                    weight = tidW * (ThreadByCount + 1);
                    startH = (ThreadByCount == 0) ? 1 : tidH * (ThreadByCount);
                    startW = (ThreadByCount == 0) ? 1 : tidW * (ThreadByCount);
                    Thread thread = new Thread(delegate()
                    {
                        int ThreadAvarega = ThredHoldValueCalcature(height, weight, startH, startW, orjBitmapColorList);
                        if (ThreadAvarega > 0)
                        {
                            ThresholdList.Add(ThreadAvarega);
                        }
                    });

                    thread.Name = $"{ThreadByCount}.Thread";
                    //t1.IsBackground = true;
                    ThreadList.Add(thread);
                    Console.WriteLine("Is thread {1} is alive : {0}",
                                      thread.IsAlive, ThreadByCount);
                    thread.Start();
                    Console.WriteLine("Is thread {1} is alive : {0}",
                                      thread.IsAlive, ThreadByCount);
                    //wait for t1 to fimish
                    thread.Join();
                }
            }
            int AveragePixel = 0;

            AveragePixel = (ThresholdList != null && ThresholdList.Count() > 0) ? ThresholdList.Sum() / ThresholdList.Count : 0;
            return(AveragePixel);
        }
        public int getThresholdValuewithThread(Bitmap orjImage)
        {
            Bitmap newBitmap = new Bitmap(orjImage.Width, orjImage.Height); // Resmin Ortalamasını Aldıktak sonra set edilecek resim


            Color curColor;
            var   orjBitmapColorList = new List <ColorEntity>();

            for (int i = 1; i < newBitmap.Width - 1; i++)
            {
                for (int j = 1; j < newBitmap.Height - 1; j++)
                {
                    curColor = orjImage.GetPixel(i, j); //orj ilgili pixceldeki rengi alınır ve aşağıdaki sabit förmül ile set edilir. Asagıda yapılan r g b renklerine göre belli bir resim set edilir. eğer 120 den büyükse bu sayı threshold alırken ortalama renk kabul ediliyor. resmi full yapar değilse renkleri sıfırlar yani beyaz yapar.

                    var EntityColor = new ColorEntity();
                    EntityColor.Height       = j;
                    EntityColor.Weight       = i;
                    EntityColor.ColorByPixel = curColor;
                    orjBitmapColorList.Add(EntityColor);
                }
            }

            var ThresholdList = new List <int>();


            int ThreadsCount = Process.GetCurrentProcess().Threads.Count; // Sistemde Kaç çekirdek varsa

            ThreadsCount = 4;

            if (ThreadsCount > 0)
            {
                var ThreadList = new List <Thread>();


                var tidH = orjImage.Height / ThreadsCount;
                var tidW = orjImage.Width / ThreadsCount;

                for (var ThreadByCount = 0; ThreadByCount < ThreadsCount; ThreadByCount++) // Çekirdek sayısı kadar Thread Oluştur.
                {
                    Thread t1 = new Thread(() =>
                    {
                        int height = tidH * (ThreadByCount + 1);
                        int weight = tidW * (ThreadByCount + 1);
                        int startH = (ThreadByCount == 0) ? 1 : tidH * (ThreadByCount);
                        int startW = (ThreadByCount == 0) ? 1 : tidW * (ThreadByCount);
                        Color newColor;
                        //Thread.Sleep(1000);
                        for (int i = startW; i < weight; i++)
                        {
                            var CheckColoWeightr = orjBitmapColorList.Where(x => x.Weight == i).ToList();


                            for (int j = startH; j < height; j++)
                            {
                                var CheckColor = CheckColoWeightr.Where(x => x.Height == j && x.Weight == i).FirstOrDefault();
                                if (CheckColor != null)
                                {
                                    newColor = CheckColor.ColorByPixel;
                                    ThresholdList.Add((int)(newColor.R * 0.299 + newColor.G * 0.578 + newColor.B * 0.114)); // esik degeri 120 manuel oldu threshold degil.
                                }
                            }
                        }

                        Console.WriteLine($"{ThreadByCount}.Thread run //  I ran for 5 seconds");
                    });
                    t1.Name = $"{ThreadByCount}.Thread";
                    //t1.IsBackground = true;
                    ThreadList.Add(t1);
                    Console.WriteLine("Is thread {1} is alive : {0}",
                                      t1.IsAlive, ThreadByCount);
                    t1.Start();
                    Console.WriteLine("Is thread {1} is alive : {0}",
                                      t1.IsAlive, ThreadByCount);
                    //wait for t1 to fimish
                    t1.Join();
                }

                //if (ThreadList != null && ThreadList.Count > 0)
                //{
                //    foreach (var _ThreadStart in ThreadList)
                //    {
                //        _ThreadStart.Start();
                //        Console.WriteLine("Is thread 1 is alive : {0} thread Name {1} ",
                //                      _ThreadStart.IsAlive,_ThreadStart.Name);
                //        //wait for t1 to fimish
                //        _ThreadStart.Join();
                //    }
                //}
            }
            int AveragePixel = 0;

            AveragePixel = (ThresholdList != null && ThresholdList.Count() > 0) ? ThresholdList.Sum() / ThresholdList.Count : 0;

            return(AveragePixel);
        }
 protected Entity()
 {
     Id    = baseId++;
     Name  = string.Empty;
     Color = ColorEntity.Black;
 }
Beispiel #25
0
        static Mapping()
        {
            MappingRepository <bool> .Mapping     = GetValue(ctx => ParseHtmlBool(ctx.Input));
            MappingRepository <byte> .Mapping     = GetValue(ctx => byte.Parse(ctx.Input));
            MappingRepository <sbyte> .Mapping    = GetValue(ctx => sbyte.Parse(ctx.Input));
            MappingRepository <short> .Mapping    = GetValue(ctx => short.Parse(ctx.Input));
            MappingRepository <ushort> .Mapping   = GetValue(ctx => ushort.Parse(ctx.Input));
            MappingRepository <int> .Mapping      = GetValue(ctx => int.Parse(ctx.Input));
            MappingRepository <uint> .Mapping     = GetValue(ctx => uint.Parse(ctx.Input));
            MappingRepository <long> .Mapping     = GetValue(ctx => long.Parse(ctx.Input));
            MappingRepository <ulong> .Mapping    = GetValue(ctx => ulong.Parse(ctx.Input));
            MappingRepository <float> .Mapping    = GetValue(ctx => ctx.PropertyRoute != null && ReflectionTools.IsPercentage(Reflector.FormatString(ctx.PropertyRoute), CultureInfo.CurrentCulture) ? (float)ReflectionTools.ParsePercentage(ctx.Input, typeof(float), CultureInfo.CurrentCulture) : float.Parse(ctx.Input));
            MappingRepository <double> .Mapping   = GetValue(ctx => ctx.PropertyRoute != null && ReflectionTools.IsPercentage(Reflector.FormatString(ctx.PropertyRoute), CultureInfo.CurrentCulture) ? (double)ReflectionTools.ParsePercentage(ctx.Input, typeof(double), CultureInfo.CurrentCulture) : double.Parse(ctx.Input));
            MappingRepository <decimal> .Mapping  = GetValue(ctx => ctx.PropertyRoute != null && ReflectionTools.IsPercentage(Reflector.FormatString(ctx.PropertyRoute), CultureInfo.CurrentCulture) ? (decimal)ReflectionTools.ParsePercentage(ctx.Input, typeof(decimal), CultureInfo.CurrentCulture) : decimal.Parse(ctx.Input));
            MappingRepository <DateTime> .Mapping = GetValue(ctx => DateTime.Parse(ctx.HasInput ? ctx.Input : ctx.Inputs["Date"] + " " + ctx.Inputs["Time"]).FromUserInterface());
            MappingRepository <Guid> .Mapping     = GetValue(ctx => Guid.Parse(ctx.Input));
            MappingRepository <TimeSpan> .Mapping = GetValue(ctx =>
            {
                var dateFormatAttr = ctx.PropertyRoute.PropertyInfo.GetCustomAttribute <TimeSpanDateFormatAttribute>();
                if (dateFormatAttr != null)
                {
                    return(DateTime.ParseExact(ctx.Input, dateFormatAttr.Format, CultureInfo.CurrentCulture).TimeOfDay);
                }
                else
                {
                    return(TimeSpan.Parse(ctx.Input));
                }
            });
            MappingRepository <SqlHierarchyId> .Mapping = GetValue(ctx => SqlHierarchyId.Parse(ctx.Input));
            MappingRepository <ColorEntity> .Mapping    = GetValue(ctx => ctx.Input.HasText() ? ColorEntity.FromRGBHex(ctx.Input) : null);

            MappingRepository <bool?> .Mapping     = GetValueNullable(ctx => ParseHtmlBool(ctx.Input));
            MappingRepository <byte?> .Mapping     = GetValueNullable(ctx => byte.Parse(ctx.Input));
            MappingRepository <sbyte?> .Mapping    = GetValueNullable(ctx => sbyte.Parse(ctx.Input));
            MappingRepository <short?> .Mapping    = GetValueNullable(ctx => short.Parse(ctx.Input));
            MappingRepository <ushort?> .Mapping   = GetValueNullable(ctx => ushort.Parse(ctx.Input));
            MappingRepository <int?> .Mapping      = GetValueNullable(ctx => int.Parse(ctx.Input));
            MappingRepository <uint?> .Mapping     = GetValueNullable(ctx => uint.Parse(ctx.Input));
            MappingRepository <long?> .Mapping     = GetValueNullable(ctx => long.Parse(ctx.Input));
            MappingRepository <ulong?> .Mapping    = GetValueNullable(ctx => ulong.Parse(ctx.Input));
            MappingRepository <float?> .Mapping    = GetValueNullable(ctx => ctx.PropertyRoute != null && ReflectionTools.IsPercentage(Reflector.FormatString(ctx.PropertyRoute), CultureInfo.CurrentCulture) ? (float)ReflectionTools.ParsePercentage(ctx.Input, typeof(float), CultureInfo.CurrentCulture) : float.Parse(ctx.Input));
            MappingRepository <double?> .Mapping   = GetValueNullable(ctx => ctx.PropertyRoute != null && ReflectionTools.IsPercentage(Reflector.FormatString(ctx.PropertyRoute), CultureInfo.CurrentCulture) ? (double)ReflectionTools.ParsePercentage(ctx.Input, typeof(double), CultureInfo.CurrentCulture) : double.Parse(ctx.Input));
            MappingRepository <decimal?> .Mapping  = GetValueNullable(ctx => ctx.PropertyRoute != null && ReflectionTools.IsPercentage(Reflector.FormatString(ctx.PropertyRoute), CultureInfo.CurrentCulture) ? (decimal)ReflectionTools.ParsePercentage(ctx.Input, typeof(decimal), CultureInfo.CurrentCulture) : decimal.Parse(ctx.Input));
            MappingRepository <DateTime?> .Mapping = GetValue(ctx =>
            {
                var input = ctx.HasInput ? ctx.Input : " ".CombineIfNotEmpty(ctx.Inputs["Date"], ctx.Inputs["Time"]);
                return(input.HasText() ? DateTime.Parse(input).FromUserInterface() : (DateTime?)null);
            });
            MappingRepository <Guid?> .Mapping     = GetValueNullable(ctx => Guid.Parse(ctx.Input));
            MappingRepository <TimeSpan?> .Mapping = GetValue(ctx =>
            {
                if (ctx.Input.IsNullOrEmpty())
                {
                    return((TimeSpan?)null);
                }

                var dateFormatAttr = ctx.PropertyRoute.PropertyInfo.GetCustomAttribute <TimeSpanDateFormatAttribute>();
                if (dateFormatAttr != null)
                {
                    return(DateTime.ParseExact(ctx.Input, dateFormatAttr.Format, CultureInfo.CurrentCulture).TimeOfDay);
                }
                else
                {
                    return(TimeSpan.Parse(ctx.Input));
                }
            });

            MappingRepository <string> .Mapping = StringTrim;
        }
Beispiel #26
0
        private ColorEntity CastRay(RayEntity rayEntity, int depth = 0)
        {
            if (depth > maxDepthReflect)
            {
                return(backgroundColor);
            }

            var intersect = SceneIntersect(rayEntity);

            if (intersect?.Collision == null)
            {
                return(backgroundColor);
            }

            var diffuseLightIntensity  = 0.0f;
            var specularLightIntensity = 0.0f;

            foreach (var light in lights)
            {
                var vectorToLight    = light.Position - intersect.Collision.Point;
                var directionToLight = vectorToLight.Normalize();
                var distanceToLight  = vectorToLight.Length();

                var rayToLight = new RayEntity()
                {
                    Origin = Vector3.Dot(directionToLight, intersect.Collision.Normal) < 0
                        ? intersect.Collision.Point - directionToLight * epsilon
                        : intersect.Collision.Point + directionToLight * epsilon,
                    Direction = directionToLight
                };

                var castRayToLight = SceneIntersect(rayToLight, distanceToLight);

                if (castRayToLight?.Collision == null)
                {
                    diffuseLightIntensity  += (light.Intensity / distanceToLight * distanceToLight) * Math.Max(0.0f, Vector3.Dot(directionToLight, intersect.Collision.Normal));
                    specularLightIntensity += (float)Math.Pow(Math.Max(0.0f, -Vector3.Dot((-directionToLight).Reflect(intersect.Collision.Normal), rayEntity.Direction)), intersect.Essence.Material.Specular) * light.Intensity;
                }
            }

            var reflectColor = new ColorEntity(0.0f, 0.0f, 0.0f);

            if (intersect.Essence.Material.ReflectComponent > 0.0f)
            {
                var reflectDirection = rayEntity.Direction.Reflect(intersect.Collision.Normal).Normalize();
                var reflectionRay    = new RayEntity()
                {
                    Origin = Vector3.Dot(reflectDirection, intersect.Collision.Normal) < 0
                        ? intersect.Collision.Point - intersect.Collision.Normal * epsilon
                        : intersect.Collision.Point + intersect.Collision.Normal * epsilon,
                    Direction = reflectDirection
                };
                reflectColor = CastRay(reflectionRay, depth + 1);
            }

            var result = intersect.Essence.Material.Color * diffuseLightIntensity * intersect.Essence.Material.DiffuseComponent
                         + new ColorEntity(1.0f, 1.0f, 1.0f) * specularLightIntensity * intersect.Essence.Material.SpecularComponent
                         + reflectColor * intersect.Essence.Material.ReflectComponent;

            return(result);
        }