예제 #1
0
        /// <inheritdoc/>
        protected override void OnApply(ImageBase <TPixel> source, Rectangle sourceRectangle)
        {
            int startY = sourceRectangle.Y;
            int endY   = sourceRectangle.Bottom;
            int startX = sourceRectangle.X;
            int endX   = sourceRectangle.Right;
            int radius = this.BrushSize >> 1;
            int levels = this.Levels;

            // Align start/end positions.
            int minX = Math.Max(0, startX);
            int maxX = Math.Min(source.Width, endX);
            int minY = Math.Max(0, startY);
            int maxY = Math.Min(source.Height, endY);

            // Reset offset if necessary.
            if (minX > 0)
            {
                startX = 0;
            }

            using (var targetPixels = new PixelAccessor <TPixel>(source.Width, source.Height))
            {
                source.CopyTo(targetPixels);

                Parallel.For(
                    minY,
                    maxY,
                    this.ParallelOptions,
                    y =>
                {
                    Span <TPixel> sourceRow = source.GetRowSpan(y);
                    Span <TPixel> targetRow = targetPixels.GetRowSpan(y);

                    for (int x = startX; x < endX; x++)
                    {
                        int maxIntensity = 0;
                        int maxIndex     = 0;

                        int[] intensityBin = new int[levels];
                        float[] redBin     = new float[levels];
                        float[] blueBin    = new float[levels];
                        float[] greenBin   = new float[levels];

                        for (int fy = 0; fy <= radius; fy++)
                        {
                            int fyr     = fy - radius;
                            int offsetY = y + fyr;

                            offsetY = offsetY.Clamp(0, maxY);

                            Span <TPixel> sourceOffsetRow = source.GetRowSpan(offsetY);

                            for (int fx = 0; fx <= radius; fx++)
                            {
                                int fxr     = fx - radius;
                                int offsetX = x + fxr;
                                offsetX     = offsetX.Clamp(0, maxX);

                                var vector = sourceOffsetRow[offsetX].ToVector4();

                                float sourceRed   = vector.X;
                                float sourceBlue  = vector.Z;
                                float sourceGreen = vector.Y;

                                int currentIntensity = (int)MathF.Round((sourceBlue + sourceGreen + sourceRed) / 3F * (levels - 1));

                                intensityBin[currentIntensity] += 1;
                                blueBin[currentIntensity]      += sourceBlue;
                                greenBin[currentIntensity]     += sourceGreen;
                                redBin[currentIntensity]       += sourceRed;

                                if (intensityBin[currentIntensity] > maxIntensity)
                                {
                                    maxIntensity = intensityBin[currentIntensity];
                                    maxIndex     = currentIntensity;
                                }
                            }

                            float red   = MathF.Abs(redBin[maxIndex] / maxIntensity);
                            float green = MathF.Abs(greenBin[maxIndex] / maxIntensity);
                            float blue  = MathF.Abs(blueBin[maxIndex] / maxIntensity);

                            ref TPixel pixel = ref targetRow[x];
                            pixel.PackFromVector4(new Vector4(red, green, blue, sourceRow[x].ToVector4().W));
                        }
                    }
                });

                source.SwapPixelsBuffers(targetPixels);
            }
        }
예제 #2
0
 public static float FilterMissPerMilValue(float missPerMil)
 {
     return MathF.Min(missPerMil, MaxMissPerMil);
 }
        private GameStateData ToGameState(IGameSectorLayerService gameSector,
                                          string loginToken)
        {
            var player = gameSector
                         .DataLayer
                         .Players
                         .FirstOrDefault(somePlayer => somePlayer.LoginToken == loginToken);


            //var playerRectangle = new Rectangle(player.CurrentImage.Position.ToVector2().ToPoint(), new Point((int)MathF.Round(player.Stats.Aura * (int)MathF.Round(player.CurrentImage.Width * player.CurrentImage.Scale.X))));
            var playerRectangleWithAura = ImageToRectangleTransformationService.Transform(player.CurrentImage, (int)MathF.Round(player.CurrentImage.Width * player.CurrentImage.Scale.X * player.Stats.Aura));
            var playerRectangle         = ImageToRectangleTransformationService.Transform(player.CurrentImage);

            var playerCanUseDialog = gameSector
                                     .DataLayer
                                     .Layers
                                     .Where(l => l.DataAsEnumerable <IdentifiableCircularLocation>().Any(
                                                location =>
            {
                var radiusAsVector2   = location.Radius.ToVector2();
                var locationRectangle = ImageToRectangleTransformationService.Transform(location.Position,
                                                                                        1f.ToVector2(),
                                                                                        (int)MathF.Round(radiusAsVector2.X),
                                                                                        (int)MathF.Round(radiusAsVector2.Y));
                return(locationRectangle.Intersects(playerRectangle));
            }))
                                     .Any();

            var playerNearEnemies = gameSector
                                    .DataLayer
                                    .Enemies
                                    .Where(enemy => ImageToRectangleTransformationService.Transform(enemy.CurrentImage)
                                           .Intersects(playerRectangleWithAura))
                                    .Any();

            var bankAccountSum = gameSector
                                 .DataLayer
                                 .GetLayersByType <IntBank>()
                                 .SelectMany(l => l.DataAsEnumerable <IntBank>())
                                 .Where(b => b.OwnerName == player.LoginToken)
                                 .Sum(b => b.Amount);


            var unserializedPlayerMetadata = new PlayerMetadataBag()
            {
                MoneyCount      = bankAccountSum,
                Stats           = player.Stats,
                GameSectorTag   = gameSector.Tag,
                ChosenStat      = player.ChosenStat,
                Items           = gameSector.DataLayer.Items.Where(item => item.OwnerName == player.DisplayName).ToList(),
                CurrentDialog   = gameSector.PlayerDialogService.GetDialogNodeByLoginToken(player.LoginToken),
                ServerEventName = playerNearEnemies ? "Enemies" : playerCanUseDialog ? "Dialog" : string.Empty
            };

            var cache = new GameStateData
            {
                Commands   = new List <string>(),
                LoginToken = player.LoginToken
            };

            //pass camera data
            cache.Screen = gameSector.IODataLayer.GetGameStateByLoginToken(loginToken)?.Screen;

            cache.Camera = new CameraData
            {
                Position = player.CurrentImage.Position,
                Rotation = player.CurrentImage.Rotation
            };

            //convert entities to images ( this is poor data, means only data needed )
            cache.Images?.Clear();
            cache.Images = new List <ImageData>();
            cache.Images.AddRange(gameSector
                                  .DataLayer
                                  .Players
                                  .Where(e => Vector2.Distance(
                                             e.CurrentImage.Position.ToVector2(),
                                             player.CurrentImage.Position.ToVector2()) <= DrawingDistance)
                                  .Select(playerInfo => playerInfo.CurrentImage)
                                  .ToList());

            cache.Images.AddRange(gameSector
                                  .DataLayer
                                  .Enemies
                                  .Where(e => Vector2.Distance(
                                             e.CurrentImage.Position.ToVector2(),
                                             player.CurrentImage.Position.ToVector2()) <= DrawingDistance)
                                  .Select(enemy => enemy.CurrentImage).ToList());

            cache.Images.AddRange(gameSector
                                  .DataLayer
                                  .Projectiles
                                  .Where(e => Vector2.Distance(
                                             e.CurrentImage.Position.ToVector2(),
                                             player.CurrentImage.Position.ToVector2()) <= DrawingDistance)
                                  .Select(projectile => projectile.CurrentImage).ToList());

            cache.Images.AddRange(gameSector
                                  .DataLayer
                                  .Items
                                  .Where(e => Vector2.Distance(
                                             e.CurrentImage.Position.ToVector2(),
                                             player.CurrentImage.Position.ToVector2()) <= DrawingDistance && !e.InInventory)
                                  .Select(item => item.CurrentImage).ToList());

            cache.Images.AddRange(gameSector
                                  .DataLayer
                                  .GeneralCharacter
                                  .Where(e => Vector2.Distance(
                                             e.CurrentImage.Position.ToVector2(),
                                             player.CurrentImage.Position.ToVector2()) <= DrawingDistance)
                                  .Select(prop => prop.CurrentImage).ToList());

            cache.Images.AddRange(gameSector
                                  .DataLayer
                                  .ImageData
                                  .Where(e => Vector2.Distance(
                                             e.Position.ToVector2(),
                                             player.CurrentImage.Position.ToVector2()) <= DrawingDistance + 1024 || e.SelectedFrame.Contains("fog"))
                                  .ToList());

            //get selected item of player (just in case) / for now...
            var previousSelectedItem = gameSector
                                       .DataLayer
                                       .PlayerItems
                                       .FirstOrDefault(pItem => pItem.OwnerName == player.DisplayName && pItem.Selected);


            unserializedPlayerMetadata.TimeStamp = DateTime.Now;

            //Position of the meta data is here now.. but it should be changed later on
            cache.Metadata = new IdentifiableNetworkCommand()
            {
                Id              = player.CurrentImage.Id,
                CommandName     = gameSector.Tag,
                CommandArgument = unserializedPlayerMetadata.GetType().FullName,
                Data            = SerializationAdapter.SerializeObject(unserializedPlayerMetadata)
            };


            return(cache);
        }
예제 #4
0
        private void RenderableControl_KeyDown(object sender, KeyEventArgs e)
        {
            if (this.camActionAllowed)
            {
                if (e.KeyCode == Keys.Space && !this.IsActionInProgress && !this.camBeginDragScene)
                {
                    this.camBeginDragScene = true;
                    this.OnCamActionRequiresCursorChanged(EventArgs.Empty);
                    this.Cursor = CursorHelper.HandGrab;
                }
                else if (e.KeyCode == Keys.F)
                {
                    if (DualityEditorApp.Selection.MainGameObject != null)
                    {
                        this.View.FocusOnObject(DualityEditorApp.Selection.MainGameObject);
                    }
                    else
                    {
                        this.View.ResetCamera();
                    }
                }
                else if (e.Control && e.KeyCode == Keys.Left)
                {
                    this.drawCamGizmoState = CameraAction.Move;
                    Vector3 pos = this.CameraObj.Transform.Pos;
                    pos.X = MathF.Round(pos.X - 1.0f);
                    this.CameraObj.Transform.Pos = pos;
                    this.Invalidate();
                }
                else if (e.Control && e.KeyCode == Keys.Right)
                {
                    this.drawCamGizmoState = CameraAction.Move;
                    Vector3 pos = this.CameraObj.Transform.Pos;
                    pos.X = MathF.Round(pos.X + 1.0f);
                    this.CameraObj.Transform.Pos = pos;
                    this.Invalidate();
                }
                else if (e.Control && e.KeyCode == Keys.Up)
                {
                    this.drawCamGizmoState = CameraAction.Move;
                    Vector3 pos = this.CameraObj.Transform.Pos;
                    pos.Y = MathF.Round(pos.Y - 1.0f);
                    this.CameraObj.Transform.Pos = pos;
                    this.Invalidate();
                }
                else if (e.Control && e.KeyCode == Keys.Down)
                {
                    this.drawCamGizmoState = CameraAction.Move;
                    Vector3 pos = this.CameraObj.Transform.Pos;
                    pos.Y = MathF.Round(pos.Y + 1.0f);
                    this.CameraObj.Transform.Pos = pos;
                    this.Invalidate();
                }
                else if (e.Control && e.KeyCode == Keys.Add)
                {
                    this.drawCamGizmoState = CameraAction.Move;
                    Vector3 pos = this.CameraObj.Transform.Pos;
                    pos.Z = MathF.Round(pos.Z + 1.0f);
                    this.CameraObj.Transform.Pos = pos;
                    this.Invalidate();
                }
                else if (e.Control && e.KeyCode == Keys.Subtract)
                {
                    this.drawCamGizmoState = CameraAction.Move;
                    Vector3 pos = this.CameraObj.Transform.Pos;
                    pos.Z = MathF.Round(pos.Z - 1.0f);
                    this.CameraObj.Transform.Pos = pos;
                    this.Invalidate();
                }
            }

            this.OnKeyDown(e);
        }
예제 #5
0
        public void EqualizePressureInZone(int cycleNum)
        {
            if (Air == null || (_tileAtmosInfo.LastCycle >= cycleNum)) return; // Already done.

            _tileAtmosInfo = new TileAtmosInfo();

            var startingMoles = Air.TotalMoles;
            var runAtmos = false;

            // We need to figure if this is necessary
            for (var i = 0; i < Atmospherics.Directions; i++)
            {
                var direction = (AtmosDirection) (1 << i);
                if (!_adjacentBits.HasFlag(direction)) continue;
                var other = _adjacentTiles[i];
                if (other?.Air == null) continue;
                var comparisonMoles = other.Air.TotalMoles;
                if (!(MathF.Abs(comparisonMoles - startingMoles) > Atmospherics.MinimumMolesDeltaToMove)) continue;
                runAtmos = true;
                break;
            }

            if (!runAtmos) // There's no need so we don't bother.
            {
                _tileAtmosInfo.LastCycle = cycleNum;
                return;
            }

            var queueCycle = ++_gridAtmosphereComponent.EqualizationQueueCycleControl;
            var totalMoles = 0f;
            var tiles = ArrayPool<TileAtmosphere>.Shared.Rent(Atmospherics.ZumosHardTileLimit);
            tiles[0] = this;
            _tileAtmosInfo.LastQueueCycle = queueCycle;
            var tileCount = 1;
            for (var i = 0; i < tileCount; i++)
            {
                if (i > Atmospherics.ZumosHardTileLimit) break;
                var exploring = tiles[i];

                if (i < Atmospherics.ZumosTileLimit)
                {
                    var tileMoles = exploring.Air.TotalMoles;
                    exploring._tileAtmosInfo.MoleDelta = tileMoles;
                    totalMoles += tileMoles;
                }

                for (var j = 0; j < Atmospherics.Directions; j++)
                {
                    var direction = (AtmosDirection) (1 << j);
                    if (!exploring._adjacentBits.HasFlag(direction)) continue;
                    var adj = exploring._adjacentTiles[j];
                    if (adj?.Air == null) continue;
                    if(adj._tileAtmosInfo.LastQueueCycle == queueCycle) continue;
                    adj._tileAtmosInfo = new TileAtmosInfo {LastQueueCycle = queueCycle};

                    if(tileCount < Atmospherics.ZumosHardTileLimit)
                        tiles[tileCount++] = adj;
                    if (adj.Air.Immutable)
                    {
                        // Looks like someone opened an airlock to space!
                        ExplosivelyDepressurize(cycleNum);
                        return;
                    }
                }
            }

            if (tileCount > Atmospherics.ZumosTileLimit)
            {
                for (var i = Atmospherics.ZumosTileLimit; i < tileCount; i++)
                {
                    //We unmark them. We shouldn't be pushing/pulling gases to/from them.
                    var tile = tiles[i];
                    if (tile == null) continue;
                    tiles[i]._tileAtmosInfo.LastQueueCycle = 0;
                }

                tileCount = Atmospherics.ZumosTileLimit;
            }

            //tiles = tiles.AsSpan().Slice(0, tileCount).ToArray(); // According to my benchmarks, this is much slower.
            //Array.Resize(ref tiles, tileCount);

            var averageMoles = totalMoles / (tileCount);
            var giverTiles = ArrayPool<TileAtmosphere>.Shared.Rent(tileCount);
            var takerTiles = ArrayPool<TileAtmosphere>.Shared.Rent(tileCount);
            var giverTilesLength = 0;
            var takerTilesLength = 0;

            for (var i = 0; i < tileCount; i++)
            {
                var tile = tiles[i];
                tile._tileAtmosInfo.LastCycle = cycleNum;
                tile._tileAtmosInfo.MoleDelta -= averageMoles;
                if (tile._tileAtmosInfo.MoleDelta > 0)
                {
                    giverTiles[giverTilesLength++] = tile;
                }
                else
                {
                    takerTiles[takerTilesLength++] = tile;
                }
            }

            var logN = MathF.Log2(tileCount);

            // Optimization - try to spread gases using an O(nlogn) algorithm that has a chance of not working first to avoid O(n^2)
            if (giverTilesLength > logN && takerTilesLength > logN)
            {
                // Even if it fails, it will speed up the next part.
                Array.Sort(tiles, 0, tileCount, Comparer);

                for (var i = 0; i < tileCount; i++)
                {
                    var tile = tiles[i];
                    tile._tileAtmosInfo.FastDone = true;
                    if (!(tile._tileAtmosInfo.MoleDelta > 0)) continue;
                    var eligibleDirections = AtmosDirection.Invalid;
                    var eligibleDirectionCount = 0;
                    for (var j = 0; j < Atmospherics.Directions; j++)
                    {
                        var direction = (AtmosDirection) (1 << j);
                        if (!tile._adjacentBits.HasFlag(direction)) continue;
                        var tile2 = tile._adjacentTiles[j];

                        // skip anything that isn't part of our current processing block.
                        if (tile2._tileAtmosInfo.FastDone || tile2._tileAtmosInfo.LastQueueCycle != queueCycle)
                            continue;

                        eligibleDirections |= direction;
                        eligibleDirectionCount++;
                    }

                    if (eligibleDirectionCount <= 0)
                        continue; // Oof we've painted ourselves into a corner. Bad luck. Next part will handle this.

                    var molesToMove = tile._tileAtmosInfo.MoleDelta / eligibleDirectionCount;
                    for (var j = 0; j < Atmospherics.Directions; j++)
                    {
                        var direction = (AtmosDirection) (1 << j);
                        if (!eligibleDirections.HasFlag(direction)) continue;

                        tile.AdjustEqMovement(direction, molesToMove);
                        tile._tileAtmosInfo.MoleDelta -= molesToMove;
                        tile._adjacentTiles[j]._tileAtmosInfo.MoleDelta += molesToMove;
                    }
                }

                giverTilesLength = 0;
                takerTilesLength = 0;

                for (var i = 0; i < tileCount; i++)
                {
                    var tile = tiles[i];
                    if (tile._tileAtmosInfo.MoleDelta > 0)
                    {
                        giverTiles[giverTilesLength++] = tile;
                    }
                    else
                    {
                        takerTiles[takerTilesLength++] = tile;
                    }
                }

                // This is the part that can become O(n^2).
                if (giverTilesLength < takerTilesLength)
                {
                    // as an optimization, we choose one of two methods based on which list is smaller. We really want to avoid O(n^2) if we can.
                    var queue = ArrayPool<TileAtmosphere>.Shared.Rent(tileCount);
                    for (var j = 0; j < giverTilesLength; j++)
                    {
                        var giver = giverTiles[j];
                        giver._tileAtmosInfo.CurrentTransferDirection = AtmosDirection.Invalid;
                        giver._tileAtmosInfo.CurrentTransferAmount = 0;
                        var queueCycleSlow = ++_gridAtmosphereComponent.EqualizationQueueCycleControl;
                        var queueLength = 0;
                        queue[queueLength++] = giver;
                        giver._tileAtmosInfo.LastSlowQueueCycle = queueCycleSlow;
                        for (var i = 0; i < queueLength; i++)
                        {
                            if (giver._tileAtmosInfo.MoleDelta <= 0)
                                break; // We're done here now. Let's not do more work than needed.

                            var tile = queue[i];
                            for (var k = 0; k < Atmospherics.Directions; k++)
                            {
                                var direction = (AtmosDirection) (1 << k);
                                if (!tile._adjacentBits.HasFlag(direction)) continue;
                                var tile2 = tile._adjacentTiles[k];
                                if (giver._tileAtmosInfo.MoleDelta <= 0) break; // We're done here now. Let's not do more work than needed.
                                if (tile2._tileAtmosInfo.LastQueueCycle != queueCycle) continue;
                                if (tile2._tileAtmosInfo.LastSlowQueueCycle == queueCycleSlow) continue;

                                queue[queueLength++] = tile2;
                                tile2._tileAtmosInfo.LastSlowQueueCycle = queueCycleSlow;
                                tile2._tileAtmosInfo.CurrentTransferDirection = direction.GetOpposite();
                                tile2._tileAtmosInfo.CurrentTransferAmount = 0;
                                if (tile2._tileAtmosInfo.MoleDelta < 0)
                                {
                                    // This tile needs gas. Let's give it to 'em.
                                    if (-tile2._tileAtmosInfo.MoleDelta > giver._tileAtmosInfo.MoleDelta)
                                    {
                                        // We don't have enough gas!
                                        tile2._tileAtmosInfo.CurrentTransferAmount -= giver._tileAtmosInfo.MoleDelta;
                                        tile2._tileAtmosInfo.MoleDelta += giver._tileAtmosInfo.MoleDelta;
                                        giver._tileAtmosInfo.MoleDelta = 0;
                                    }
                                    else
                                    {
                                        // We have enough gas.
                                        tile2._tileAtmosInfo.CurrentTransferAmount += tile2._tileAtmosInfo.MoleDelta;
                                        giver._tileAtmosInfo.MoleDelta += tile2._tileAtmosInfo.MoleDelta;
                                        tile2._tileAtmosInfo.MoleDelta = 0;
                                    }
                                }
                            }
                        }

                        // Putting this loop here helps make it O(n^2) over O(n^3)
                        for (var i = queueLength - 1; i >= 0; i--)
                        {
                            var tile = queue[i];
                            if (tile._tileAtmosInfo.CurrentTransferAmount != 0 && tile._tileAtmosInfo.CurrentTransferDirection != AtmosDirection.Invalid)
                            {
                                tile.AdjustEqMovement(tile._tileAtmosInfo.CurrentTransferDirection, tile._tileAtmosInfo.CurrentTransferAmount);
                                tile._adjacentTiles[tile._tileAtmosInfo.CurrentTransferDirection.ToIndex()]
                                    ._tileAtmosInfo.CurrentTransferAmount += tile._tileAtmosInfo.CurrentTransferAmount;
                                tile._tileAtmosInfo.CurrentTransferAmount = 0;
                            }
                        }
                    }

                    ArrayPool<TileAtmosphere>.Shared.Return(queue);
                }
                else
                {
                    var queue = ArrayPool<TileAtmosphere>.Shared.Rent(tileCount);
                    for (var j = 0; j < takerTilesLength; j++)
                    {
                        var taker = takerTiles[j];
                        taker._tileAtmosInfo.CurrentTransferDirection = AtmosDirection.Invalid;
                        taker._tileAtmosInfo.CurrentTransferAmount = 0;
                        var queueCycleSlow = ++_gridAtmosphereComponent.EqualizationQueueCycleControl;
                        var queueLength = 0;
                        queue[queueLength++] = taker;
                        taker._tileAtmosInfo.LastSlowQueueCycle = queueCycleSlow;
                        for (var i = 0; i < queueLength; i++)
                        {
                            if (taker._tileAtmosInfo.MoleDelta >= 0)
                                break; // We're done here now. Let's not do more work than needed.

                            var tile = queue[i];
                            for (var k = 0; k < Atmospherics.Directions; k++)
                            {
                                var direction = (AtmosDirection) (1 << k);
                                if (!tile._adjacentBits.HasFlag(direction)) continue;
                                var tile2 = tile._adjacentTiles[k];

                                if (taker._tileAtmosInfo.MoleDelta >= 0) break; // We're done here now. Let's not do more work than needed.
                                if (tile2._tileAtmosInfo.LastQueueCycle != queueCycle) continue;
                                if (tile2._tileAtmosInfo.LastSlowQueueCycle == queueCycleSlow) continue;
                                queue[queueLength++] = tile2;
                                tile2._tileAtmosInfo.LastSlowQueueCycle = queueCycleSlow;
                                tile2._tileAtmosInfo.CurrentTransferDirection = direction.GetOpposite();
                                tile2._tileAtmosInfo.CurrentTransferAmount = 0;

                                if (tile2._tileAtmosInfo.MoleDelta > 0)
                                {
                                    // This tile has gas we can suck, so let's
                                    if (tile2._tileAtmosInfo.MoleDelta > -taker._tileAtmosInfo.MoleDelta)
                                    {
                                        // They have enough gas
                                        tile2._tileAtmosInfo.CurrentTransferAmount -= taker._tileAtmosInfo.MoleDelta;
                                        tile2._tileAtmosInfo.MoleDelta += taker._tileAtmosInfo.MoleDelta;
                                        taker._tileAtmosInfo.MoleDelta = 0;
                                    }
                                    else
                                    {
                                        // They don't have enough gas!
                                        tile2._tileAtmosInfo.CurrentTransferAmount += tile2._tileAtmosInfo.MoleDelta;
                                        taker._tileAtmosInfo.MoleDelta += tile2._tileAtmosInfo.MoleDelta;
                                        tile2._tileAtmosInfo.MoleDelta = 0;
                                    }
                                }
                            }
                        }

                        for (var i = queueLength - 1; i >= 0; i--)
                        {
                            var tile = queue[i];
                            if (tile._tileAtmosInfo.CurrentTransferAmount == 0 || tile._tileAtmosInfo.CurrentTransferDirection == AtmosDirection.Invalid)
                                continue;

                            tile.AdjustEqMovement(tile._tileAtmosInfo.CurrentTransferDirection, tile._tileAtmosInfo.CurrentTransferAmount);

                            tile._adjacentTiles[tile._tileAtmosInfo.CurrentTransferDirection.ToIndex()]
                                ._tileAtmosInfo.CurrentTransferAmount += tile._tileAtmosInfo.CurrentTransferAmount;
                            tile._tileAtmosInfo.CurrentTransferAmount = 0;
                        }
                    }

                    ArrayPool<TileAtmosphere>.Shared.Return(queue);
                }

                for (var i = 0; i < tileCount; i++)
                {
                    var tile = tiles[i];
                    tile.FinalizeEq();
                }

                for (var i = 0; i < tileCount; i++)
                {
                    var tile = tiles[i];
                    for (var j = 0; j < Atmospherics.Directions; j++)
                    {
                        var direction = (AtmosDirection) (1 << j);
                        if (!tile._adjacentBits.HasFlag(direction)) continue;
                        var tile2 = tile._adjacentTiles[j];
                        if (tile2?.Air?.Compare(Air) == GasMixture.GasCompareResult.NoExchange) continue;
                        _gridAtmosphereComponent.AddActiveTile(tile2);
                        break;
                    }
                }

                ArrayPool<TileAtmosphere>.Shared.Return(tiles);
                ArrayPool<TileAtmosphere>.Shared.Return(giverTiles);
                ArrayPool<TileAtmosphere>.Shared.Return(takerTiles);
            }
        }
예제 #6
0
        public void PlaySound(int channel, ResourceSound sound, float volume)
        {
            if (channel == 0)
            {
                //First available channel
                for (int i = 0; i < _channels.Length; i++)
                {
                    if (_channels[i] == null || !_channels[i].Source.IsPlaying)
                    {
                        _channels[i]?.Dispose();
                        channel = i + 1;
                        break;
                    }
                }

                if (channel == 0)
                {
                    return;
                }
            }

            StopChannel(channel);

            // convert from DM volume (0-100) to OpenAL volume (db)
            IClydeAudioSource source = sound.Play(AudioParams.Default.WithVolume(20 * MathF.Log10(volume)));

            _channels[channel - 1] = new DreamSoundChannel(source);
        }
예제 #7
0
        protected virtual void OnCollectStateOverlayDrawcalls(Canvas canvas)
        {
            // Gather general data
            Point cursorPos = this.PointToClient(Cursor.Position);

            // Update action text from hovered / selection / action object
            Vector2 actionTextPos = new Vector2(cursorPos.X + 30, cursorPos.Y + 10);

            this.actionText.SourceText = this.UpdateActionText(ref actionTextPos);

            // Collect the views overlay layer drawcalls
            this.CollectLayerOverlayDrawcalls(canvas);

            // Collect the states overlay drawcalls
            canvas.PushState();
            {
                // Draw camera movement indicators
                if (this.camAction != CameraAction.None)
                {
                    canvas.PushState();
                    canvas.State.ColorTint = ColorRgba.White.WithAlpha(0.5f);
                    if (this.camAction == CameraAction.DragScene)
                    {
                        // Don't draw anything.
                    }
                    else if (this.camAction == CameraAction.Move)
                    {
                        canvas.FillCircle(this.camActionBeginLoc.X, this.camActionBeginLoc.Y, 3);
                        canvas.DrawLine(this.camActionBeginLoc.X, this.camActionBeginLoc.Y, cursorPos.X, cursorPos.Y);
                    }
                    canvas.PopState();
                }

                // Normalize action text position
                if (this.actionText.Fonts != null && this.actionText.Fonts.Any(r => r.IsAvailable && r.Res.IsPixelGridAligned))
                {
                    actionTextPos.X = MathF.Round(actionTextPos.X);
                    actionTextPos.Y = MathF.Round(actionTextPos.Y);
                }

                // Draw current action text
                if (!this.actionText.IsEmpty)
                {
                    canvas.DrawText(this.actionText, actionTextPos.X, actionTextPos.Y, drawBackground: true);
                }

                // Update / Draw current status text
                {
                    this.statusText.SourceText = this.UpdateStatusText();
                    if (!this.statusText.IsEmpty)
                    {
                        Vector2 statusTextSize = this.statusText.Size;
                        canvas.DrawText(this.statusText, 10, this.ClientSize.Height - statusTextSize.Y - 10, drawBackground: true);
                    }
                }
            }
            canvas.PopState();

            // Draw a focus indicator at the view border
            canvas.PushState();
            {
                ColorRgba focusColor   = ColorRgba.Lerp(this.FgColor, this.BgColor, 0.25f).WithAlpha(255);
                ColorRgba noFocusColor = ColorRgba.Lerp(this.FgColor, this.BgColor, 0.75f).WithAlpha(255);
                canvas.State.SetMaterial(new BatchInfo(DrawTechnique.Mask, this.Focused ? focusColor : noFocusColor));
                canvas.DrawRect(0, 0, this.ClientSize.Width, this.ClientSize.Height);
            }
            canvas.PopState();
        }
예제 #8
0
 /// <summary>
 /// Initializes a new instance of the <see cref="ImageBrushApplicator"/> class.
 /// </summary>
 /// <param name="image">
 /// The image.
 /// </param>
 /// <param name="region">
 /// The region.
 /// </param>
 /// <param name="sourcePixels">
 /// The sourcePixels.
 /// </param>
 public ImageBrushApplicator(PixelAccessor <TColor> sourcePixels, IImageBase <TColor> image, RectangleF region)
     : base(sourcePixels)
 {
     this.source  = image.Lock();
     this.xLength = image.Width;
     this.yLength = image.Height;
     this.offset  = new Vector2(MathF.Max(MathF.Floor(region.Top), 0), MathF.Max(MathF.Floor(region.Left), 0));
 }
예제 #9
0
 //replacement for Mathf.CeilToInt();
 public static int CeilToInt(float inValue)
 {
     return((int)MathF.Ceiling(inValue));
 }
예제 #10
0
 static float f2(Vector x)
 {
     return(100 * MathF.Pow(x[1] - MathF.Pow(x[0], 3), 2) + MathF.Pow(1 - x[0], 2));
 }
예제 #11
0
        public override void HandleMcpePlayerAction(McpePlayerAction message)
        {
            var action = (PlayerAction)message.actionId;

            lock (_breakSync)
            {
                if (GameMode == GameMode.Creative)
                {
                    return;
                }

                Block block;
                if (action == PlayerAction.StartBreak)
                {
                    block = Level.GetBlock(message.coordinates);
                    var inHand = Inventory.GetItemInHand();
                    var drops  = block.GetDrops(inHand);

                    float tooltypeFactor = drops == null || drops.Length == 0 ? 5f : 1.5f;                     // 1.5 if proper tool

                    var multiplier = 1f;
                    switch (inHand.ItemMaterial)
                    {
                    case ItemMaterial.None:
                        break;

                    case ItemMaterial.Wood:
                        multiplier = 2f;
                        break;

                    case ItemMaterial.Stone:
                        multiplier = 4f;
                        break;

                    case ItemMaterial.Gold:
                        multiplier = 12f;
                        break;

                    case ItemMaterial.Iron:
                        multiplier = 6f;
                        break;

                    case ItemMaterial.Diamond:
                        multiplier = 8f;
                        break;
                    }

                    foreach (var enchantment in inHand.GetEnchantings())
                    {
                        if (enchantment.Id == EnchantingType.Efficiency && enchantment.Level > 0)
                        {
                            multiplier += MathF.Sqrt(enchantment.Level) + 1;
                        }
                    }

                    if (Effects.TryGetValue(EffectType.Haste, out var effect))
                    {
                        if (effect is Haste haste && haste.Level > 0f)
                        {
                            multiplier *= 1f + (haste.Level * 0.2f);
                        }
                    }

                    var hardness = block.Hardness;

                    double breakTime = MathF.Ceiling((hardness * tooltypeFactor * 20f));

                    McpeLevelEvent message1 = McpeLevelEvent.CreateObject();
                    message1.eventId  = 3600;
                    message1.position = message.coordinates;
                    message1.data     = (int)((double)ushort.MaxValue / (breakTime / multiplier));

                    Level.RelayBroadcast(message1);

                    BlockFace face = (BlockFace)message.face;

                    IsBreakingBlock = true;
                    BlockBreakTimer.Restart();
                    BreakingBlockCoordinates = block.Coordinates;
                    BlockBreakTime           = breakTime / multiplier;
                    BreakingFace             = face;

                    //		Log.Info(
                    //			$"Start Breaking block. Hardness: {hardness} | ToolTypeFactor; {tooltypeFactor} | BreakTime: {breakTime} | Multiplier: {multiplier} | BLockBreakTime: {breakTime / multiplier} | IsBreaking: {IsBreakingBlock}");

                    var blockStartBreak = new BlockStartBreakEvent(this, block);
                    EventDispatcher.DispatchEventAsync(blockStartBreak).Then(result =>
                    {
                        if (result.IsCancelled)
                        {
                            SendBlockBreakEnd(block.Coordinates);
                            return;
                        }
                    });

                    return;
                }
                else if (action == PlayerAction.AbortBreak)
                {
                    var elapsed      = BlockBreakTimer.ElapsedMilliseconds;
                    var elapsedTicks = elapsed / 50d;

                    //	Log.Info($"!! Abort Break !!! Ticks elapsed: {elapsedTicks} | Required: {BlockBreakTime} | IsBreaking: {IsBreakingBlock}");

                    block = Level.GetBlock(message.coordinates);
                    if (IsBreakingBlock && BreakingBlockCoordinates == block.Coordinates)
                    {
                        IsBreakingBlock = false;
                        BlockBreakTimer.Reset();

                        EventDispatcher.DispatchEventAsync(new BlockAbortBreakEvent(this, block));
                    }

                    return;
                }
                else if (action == PlayerAction.StopBreak)
                {
                    var elapsed      = BlockBreakTimer.ElapsedMilliseconds;
                    var elapsedTicks = elapsed / 50d;

                    //Log.Info($"## !! Stop Break !!! Ticks elapsed: {elapsedTicks} | Required: {BlockBreakTime} | IsBreaking: {IsBreakingBlock}");

                    if (IsBreakingBlock)
                    {
                        //BlockFace face = (BlockFace) message.face;
                        if (elapsedTicks >= BlockBreakTime || Math.Abs(elapsedTicks - BlockBreakTime) < 2.5
                            )                     //Give a max time difference of 2.5 ticks.
                        {
                            StopBreak(BreakingBlockCoordinates);
                        }
                        else
                        {
                        }
                    }
                    else
                    {
                        IsBreakingBlock = false;
                        BlockBreakTimer.Reset();
                    }

                    return;
                }
            }

            base.HandleMcpePlayerAction(message);
        }
예제 #12
0
 static float f1(Vector x)
 {
     return(100 * MathF.Pow(MathF.Pow(x[0], 2) - x[1], 2) + MathF.Pow(1 - x[0], 2));
 }
예제 #13
0
 static float f4(Vector x)
 {
     return(MathF.Pow(x[0] + 10 * x[1], 2) + 5 * MathF.Pow(x[2] - x[3], 2) +
            MathF.Pow(x[1] - 2 * x[2], 4) + 10 * MathF.Pow(x[0] - x[3], 4));
 }
예제 #14
0
        public bool filter(CombatUnit unit)
        {
            switch (rangeType)
            {
            case RangeType.none:
                return(MathF.Abs(unit.position - pivotPos) <= maxDistance && minDistance <= MathF.Abs(unit.position - pivotPos));

            case RangeType.lefthand:
                return((pivotPos - unit.position) <= maxDistance && minDistance <= (pivotPos - unit.position));

            case RangeType.righthand:
                return(-(pivotPos - unit.position) <= maxDistance && minDistance <= -(pivotPos - unit.position));
            }
            return(MathF.Abs(unit.position - pivotPos) <= maxDistance && minDistance <= MathF.Abs(unit.position - pivotPos));
        }
예제 #15
0
        public static Runnable getkey()
        {
            Mem Memory    = new Mem();
            int ProcessID = Memory.GetProcIdFromName("pwn3.exe");

            Memory.OpenProcess(ProcessID);

            float height = Memory.ReadFloat("pwn3.exe+0x01900600,20,64,720,318,238,114,98");


            float new_y       = 0;
            float new_x       = 0;
            float rotation    = Memory.ReadFloat("pwn3.exe+0x019019A0,44C,C0,3C8,4,108,2FC,254");
            float temp_x      = 0;
            float temp_y      = 0;
            float current_y   = 0;
            float current_x   = 0;
            bool  lock_height = false;

            while (true)
            {
                current_x = Memory.ReadFloat("pwn3.exe+0x01900600,20,64,720,318,238,114,94");
                current_y = Memory.ReadFloat("pwn3.exe+0x01900600,20,64,720,318,238,114,90");
                rotation  = Memory.ReadFloat("pwn3.exe+0x019019A0,44C,C0,3C8,4,108,2FC,254");
                height    = Memory.ReadFloat("pwn3.exe+0x01900600,20,64,720,318,238,114,98");


                Thread.sleep(5);
                for (int i = 32; i < 127; i++)
                {
                    int keyState = GetAsyncKeyState(i);
                    if (keyState == 32768)
                    {
                        if (i == 32 && lock_height == true)
                        {
                            height = Memory.ReadFloat("pwn3.exe+0x01900600,20,64,720,318,238,114,98");
                            height = height + 100;
                        }


                        if (i == 48)
                        {
                            lock_height = false;
                        }
                        if (i == 57)
                        {
                            lock_height = true;
                        }

                        if ((Char)i == 'E')
                        {
                            current_x = Memory.ReadFloat("pwn3.exe+0x01900600,20,64,720,318,238,114,94");


                            temp_x = MathF.Sin(rotation * (MathF.PI) / 180) * 100;
                            new_x  = current_x + temp_x;
                        }

                        if ((Char)i == 'Q')
                        {
                            current_y = Memory.ReadFloat("pwn3.exe+0x01900600,20,64,720,318,238,114,90");

                            temp_y = MathF.Sin((rotation - 90) * (MathF.PI) / 180) * 100;
                            new_y  = current_y + -temp_y;
                            Debug.WriteLine("rotation: " + rotation + "temp_y: " + temp_y);
                        }


                        if ((Char)i == 'W')
                        {
                            current_y = Memory.ReadFloat("pwn3.exe+0x01900600,20,64,720,318,238,114,90");

                            temp_y = MathF.Sin((rotation - 90) * (MathF.PI) / 180) * 100;
                            new_y  = current_y + -temp_y;


                            current_x = Memory.ReadFloat("pwn3.exe+0x01900600,20,64,720,318,238,114,94");


                            temp_x = MathF.Sin(rotation * (MathF.PI) / 180) * 100;
                            new_x  = current_x + temp_x;
                        }
                        //if ((Char)i == 'E')
                        //{

                        //    new_x = current_x + 100;


                        //}

                        //if ((Char)i == 'Q')
                        //{

                        //    new_y = current_y + 100;

                        //}
                        if ((Char)i == 'R')
                        {
                            Memory.WriteMemory("pwn3.exe+0x01900600,20,64,720,318,238,114,94", "float", "0");
                            Memory.WriteMemory("pwn3.exe+0x01900600,20,64,720,318,238,114,90", "float", "0");
                            Memory.WriteMemory("pwn3.exe+0x01900600,20,64,720,318,238,114,98", "float", "5005");
                        }
                    }
                    //Memory.WriteMemory("pwn3.exe+0x01900600,20,64,720,318,238,114,98", "float", height.ToString());


                    if (lock_height == true)
                    {
                        Memory.WriteMemory("pwn3.exe+0x01900600,20,64,720,318,238,114,98", "float", height.ToString());
                        Memory.WriteMemory("pwn3.exe+0x01900600,20,64,720,318,238,114,94", "float", new_x.ToString());
                        Memory.WriteMemory("pwn3.exe+0x01900600,20,64,720,318,238,114,90", "float", new_y.ToString());
                    }
                }
            }
        }
예제 #16
0
 //replacement for Mathf.FloorToInt();
 public static int FloorToInt(float inValue)
 {
     return((int)MathF.Floor(inValue));
 }
예제 #17
0
        public static Ray CalculateRayFromMousePosition([NotNull] CameraComponent camera, Vector2 mousePosition, Matrix worldView)
        {
            // determine the mouse position normalized, centered and correctly oriented
            var screenPosition = new Vector2(2f * (mousePosition.X - 0.5f), -2f * (mousePosition.Y - 0.5f));

            if (camera.Projection == CameraProjectionMode.Perspective)
            {
                // calculate the ray direction corresponding to the click in the view space
                var verticalFov      = MathUtil.DegreesToRadians(camera.VerticalFieldOfView);
                var rayDirectionView = Vector3.Normalize(new Vector3(camera.AspectRatio * screenPosition.X, screenPosition.Y, -1 / MathF.Tan(verticalFov / 2f)));

                // calculate the direction of the ray in the gizmo space
                var rayDirectionGizmo = Vector3.Normalize(Vector3.TransformNormal(rayDirectionView, worldView));

                return(new Ray(worldView.TranslationVector, rayDirectionGizmo));
            }
            else
            {
                // calculate the direction of the ray in the gizmo space
                var rayDirectionGizmo = Vector3.Normalize(Vector3.TransformNormal(-Vector3.UnitZ, worldView));

                // calculate the position of the ray in the gizmo space
                var halfSize        = camera.OrthographicSize / 2f;
                var rayOriginOffset = new Vector3(screenPosition.X * camera.AspectRatio * halfSize, screenPosition.Y * halfSize, 0);
                var rayOrigin       = Vector3.TransformCoordinate(rayOriginOffset, worldView);

                return(new Ray(rayOrigin, rayDirectionGizmo));
            }
        }
예제 #18
0
 //replacement for Mathf.Floor()
 public static float Floor(float inValue)
 {
     return(MathF.Floor(inValue));
 }
예제 #19
0
 protected override float GetMainArcDistanceFade(int i, int segments)
 {
     return(MathF.Cos((float)i / (segments - 1) * MathF.PI / 2));
 }
예제 #20
0
        public static void Main(string[] args)
        {
            Console.WriteLine("Hello!");
            IEnumerable <string> devices = ALC.ALC.GetStringList(GetEnumerationStringList.DeviceSpecifier);

            Console.WriteLine($"Devices: {string.Join(", ", devices)}");

            // Get the default device, then go though all devices and select the AL soft device if it exists.
            string deviceName = ALC.ALC.GetString(ALDevice.Null, AlcGetString.DefaultDeviceSpecifier);

            foreach (string d in devices)
            {
                if (d.Contains("OpenAL Soft"))
                {
                    deviceName = d;
                }
            }

            IEnumerable <string> allDevices =
                EnumerateAll.GetStringList(GetEnumerateAllContextStringList.AllDevicesSpecifier);

            Console.WriteLine($"All Devices: {string.Join(", ", allDevices)}");

            ALDevice  device  = ALC.ALC.OpenDevice(deviceName);
            ALContext context = ALC.ALC.CreateContext(device, (int[])null);

            ALC.ALC.MakeContextCurrent(context);

            CheckALError("Start");

            ALC.ALC.GetInteger(device, AlcGetInteger.MajorVersion, 1, out int alcMajorVersion);
            ALC.ALC.GetInteger(device, AlcGetInteger.MinorVersion, 1, out int alcMinorVersion);
            string alcExts = ALC.ALC.GetString(device, AlcGetString.Extensions);

            ALContextAttributes attrs = ALC.ALC.GetContextAttributes(device);

            Console.WriteLine($"Attributes: {attrs}");

            string exts = AL.AL.Get(ALGetString.Extensions);
            string rend = AL.AL.Get(ALGetString.Renderer);
            string vend = AL.AL.Get(ALGetString.Vendor);
            string vers = AL.AL.Get(ALGetString.Version);

            Console.WriteLine(
                $"Vendor: {vend}, \nVersion: {vers}, \nRenderer: {rend}, \nExtensions: {exts}, \nALC Version: {alcMajorVersion}.{alcMinorVersion}, \nALC Extensions: {alcExts}");

            Console.WriteLine("Available devices: ");
            IEnumerable <string> list = EnumerateAll.GetStringList(GetEnumerateAllContextStringList.AllDevicesSpecifier);

            foreach (string item in list)
            {
                Console.WriteLine("  " + item);
            }

            Console.WriteLine("Available capture devices: ");
            list = ALC.ALC.GetStringList(GetEnumerationStringList.CaptureDeviceSpecifier);
            foreach (string item in list)
            {
                Console.WriteLine("  " + item);
            }

            int auxSlot = 0;

            if (EFX.IsExtensionPresent(device))
            {
                Console.WriteLine("EFX extension is present!!");
                EFX.GenEffect(out int effect);
                EFX.Effect(effect, EffectInteger.EffectType, (int)EffectType.Reverb);
                EFX.GenAuxiliaryEffectSlot(out auxSlot);
                EFX.AuxiliaryEffectSlot(auxSlot, EffectSlotInteger.Effect, effect);
            }

            // Record a second of data
            CheckALError("Before record");
            short[]         recording     = new short[44100 * 4];
            ALCaptureDevice captureDevice = ALC.ALC.CaptureOpenDevice(null, 44100, ALFormat.Mono16, 1024);

            {
                ALC.ALC.CaptureStart(captureDevice);

                int current = 0;
                while (current < recording.Length)
                {
                    int samplesAvailable = ALC.ALC.GetAvailableSamples(captureDevice);
                    if (samplesAvailable > 512)
                    {
                        int samplesToRead = Math.Min(samplesAvailable, recording.Length - current);
                        ALC.ALC.CaptureSamples(captureDevice, ref recording[current], samplesToRead);
                        current += samplesToRead;
                    }

                    Thread.Yield();
                }

                ALC.ALC.CaptureStop(captureDevice);
            }
            CheckALError("After record");

            // Playback the recorded data
            CheckALError("Before data");
            AL.AL.GenBuffer(out int alBuffer);
            // short[] sine = new short[44100 * 1];
            // FillSine(sine, 4400, 44100);
            // FillSine(recording, 440, 44100);
            AL.AL.BufferData(alBuffer, ALFormat.Mono16, ref recording[0], recording.Length * 2, 44100);
            CheckALError("After data");

            AL.AL.Listener(ALListenerf.Gain, 0.1f);

            AL.AL.GenSource(out int alSource);
            AL.AL.Source(alSource, ALSourcef.Gain, 1f);
            AL.AL.Source(alSource, ALSourcei.Buffer, alBuffer);
            if (EFX.IsExtensionPresent(device))
            {
                EFX.Source(alSource, EFXSourceInteger3.AuxiliarySendFilter, auxSlot, 0, 0);
            }

            AL.AL.SourcePlay(alSource);

            Console.WriteLine("Before Playing: " + AL.AL.GetErrorString(AL.AL.GetError()));

            if (DeviceClock.IsExtensionPresent(device))
            {
                long[] clockLatency = new long[2];
                DeviceClock.GetInteger(device, GetInteger64.DeviceClock, clockLatency);
                Console.WriteLine("Clock: " + clockLatency[0] + ", Latency: " + clockLatency[1]);
                CheckALError(" ");
            }

            if (SourceLatency.IsExtensionPresent())
            {
                SourceLatency.GetSource(alSource, SourceLatencyVector2d.SecOffsetLatency, out Vector2d values);
                SourceLatency.GetSource(alSource, SourceLatencyVector2i.SampleOffsetLatency, out int values1,
                                        out int values2, out long values3);
                Console.WriteLine("Source latency: " + values);
                Console.WriteLine($"Source latency 2: {Convert.ToString(values1, 2)}, {values2}; {values3}");
                CheckALError(" ");
            }

            while (AL.AL.GetSourceState(alSource) == ALSourceState.Playing)
            {
                if (SourceLatency.IsExtensionPresent())
                {
                    SourceLatency.GetSource(alSource, SourceLatencyVector2d.SecOffsetLatency, out Vector2d values);
                    SourceLatency.GetSource(alSource, SourceLatencyVector2i.SampleOffsetLatency, out int values1,
                                            out int values2, out long values3);
                    Console.WriteLine("Source latency: " + values);
                    Console.WriteLine($"Source latency 2: {Convert.ToString(values1, 2)}, {values2}; {values3}");
                    CheckALError(" ");
                }

                if (DeviceClock.IsExtensionPresent(device))
                {
                    long[] clockLatency = new long[2];
                    DeviceClock.GetInteger(device, GetInteger64.DeviceClock, 1, clockLatency);
                    Console.WriteLine("Clock: " + clockLatency[0] + ", Latency: " + clockLatency[1]);
                    CheckALError(" ");
                }

                Thread.Sleep(10);
            }

            AL.AL.SourceStop(alSource);

            // Test float32 format extension
            if (EXTFloat32.IsExtensionPresent())
            {
                Console.WriteLine("Testing float32 format extension with a sine wave...");

                float[] sine = new float[44100 * 2];
                for (int i = 0; i < sine.Length; i++)
                {
                    sine[i] = MathF.Sin(440 * MathF.PI * 2 * (i / (float)sine.Length));
                }

                int buffer = AL.AL.GenBuffer();
                EXTFloat32.BufferData(buffer, FloatBufferFormat.Mono, sine, 44100);

                AL.AL.Listener(ALListenerf.Gain, 0.1f);

                AL.AL.Source(alSource, ALSourcef.Gain, 1f);
                AL.AL.Source(alSource, ALSourcei.Buffer, buffer);

                AL.AL.SourcePlay(alSource);

                while (AL.AL.GetSourceState(alSource) == ALSourceState.Playing)
                {
                    Thread.Sleep(10);
                }

                AL.AL.SourceStop(alSource);
            }

            // Test double format extension
            if (EXTDouble.IsExtensionPresent())
            {
                Console.WriteLine("Testing float64 format extension with a saw wave...");

                double[] saw = new double[44100 * 2];
                for (int i = 0; i < saw.Length; i++)
                {
                    double t = i / (double)saw.Length * 440;
                    saw[i] = t - Math.Floor(t);
                }

                int buffer = AL.AL.GenBuffer();
                EXTDouble.BufferData(buffer, DoubleBufferFormat.Mono, saw, 44100);

                AL.AL.Listener(ALListenerf.Gain, 0.1f);

                AL.AL.Source(alSource, ALSourcef.Gain, 1f);
                AL.AL.Source(alSource, ALSourcei.Buffer, buffer);

                AL.AL.SourcePlay(alSource);

                while (AL.AL.GetSourceState(alSource) == ALSourceState.Playing)
                {
                    Thread.Sleep(10);
                }

                AL.AL.SourceStop(alSource);
            }


            ALC.ALC.MakeContextCurrent(ALContext.Null);
            ALC.ALC.DestroyContext(context);
            ALC.ALC.CloseDevice(device);

            Console.WriteLine("Goodbye!");

            Console.WriteLine("Playing sound...");
            ExampleSound();
            Console.WriteLine("Done!");
        }
예제 #21
0
        protected virtual void OnUpdateState()
        {
            Camera     cam       = this.CameraComponent;
            GameObject camObj    = this.CameraObj;
            Point      cursorPos = this.PointToClient(Cursor.Position);

            float unscaledTimeMult = Time.TimeMult / Time.TimeScale;

            this.camTransformChanged = false;

            if (this.camAction == CameraAction.DragScene)
            {
                Vector2 curPos  = new Vector2(cursorPos.X, cursorPos.Y);
                Vector2 lastPos = new Vector2(this.camActionBeginLoc.X, this.camActionBeginLoc.Y);
                this.camActionBeginLoc = new Point((int)curPos.X, (int)curPos.Y);

                float refZ = (this.HasCameraFocusPosition && camObj.Transform.Pos.Z < this.CameraFocusPosition.Z - cam.NearZ) ? this.CameraFocusPosition.Z : 0.0f;
                if (camObj.Transform.Pos.Z >= refZ - cam.NearZ)
                {
                    refZ = camObj.Transform.Pos.Z + MathF.Abs(cam.FocusDist);
                }

                Vector2 targetOff = (-(curPos - lastPos) / this.GetScaleAtZ(refZ));
                Vector2 targetVel = targetOff / unscaledTimeMult;
                MathF.TransformCoord(ref targetVel.X, ref targetVel.Y, camObj.Transform.Angle);
                this.camVel.Z           *= MathF.Pow(0.9f, unscaledTimeMult);
                this.camVel             += (new Vector3(targetVel, this.camVel.Z) - this.camVel) * unscaledTimeMult;
                this.camTransformChanged = true;
            }
            else if (this.camAction == CameraAction.Move)
            {
                Vector3 moveVec = new Vector3(
                    cursorPos.X - this.camActionBeginLoc.X,
                    cursorPos.Y - this.camActionBeginLoc.Y,
                    this.camVel.Z);

                const float BaseSpeedCursorLen = 25.0f;
                const float BaseSpeed          = 3.0f;
                moveVec.X = BaseSpeed * MathF.Sign(moveVec.X) * MathF.Pow(MathF.Abs(moveVec.X) / BaseSpeedCursorLen, 1.5f);
                moveVec.Y = BaseSpeed * MathF.Sign(moveVec.Y) * MathF.Pow(MathF.Abs(moveVec.Y) / BaseSpeedCursorLen, 1.5f);

                MathF.TransformCoord(ref moveVec.X, ref moveVec.Y, camObj.Transform.Angle);

                if (this.camBeginDragScene)
                {
                    float refZ = (this.HasCameraFocusPosition && camObj.Transform.Pos.Z < this.CameraFocusPosition.Z - cam.NearZ) ? this.CameraFocusPosition.Z : 0.0f;
                    if (camObj.Transform.Pos.Z >= refZ - cam.NearZ)
                    {
                        refZ = camObj.Transform.Pos.Z + MathF.Abs(cam.FocusDist);
                    }
                    moveVec = new Vector3(moveVec.Xy * 0.5f / this.GetScaleAtZ(refZ), moveVec.Z);
                }

                this.camVel = moveVec;
                this.camTransformChanged = true;
            }
            else if (this.camVel.Length > 0.01f)
            {
                this.camVel *= MathF.Pow(0.9f, unscaledTimeMult);
                this.camTransformChanged = true;
            }
            else
            {
                this.camTransformChanged = this.camTransformChanged || (this.camVel != Vector3.Zero);
                this.camVel = Vector3.Zero;
            }
            if (this.camTransformChanged)
            {
                camObj.Transform.MoveBy(this.camVel * unscaledTimeMult);
                this.View.OnCamTransformChanged();
                this.Invalidate();
            }

            // If we're currently executing the game, invalidate every frame
            if (DualityApp.ExecContext == DualityApp.ExecutionContext.Game)
            {
                this.Invalidate();
            }

            // If we previously skipped a repaint event because we already rendered
            // a frame with that number, perform another repaint once we've entered
            // the next frame. This will make sure we won't forget about previous
            // one-shot invalidate calls just because we were already done rendering that
            // frame.
            if (this.renderFrameScheduled && this.renderFrameLast != Time.FrameCount)
            {
                this.Invalidate();
            }
        }
예제 #22
0
 private float GetFlipSign(NvGpuEngine3dReg Reg)
 {
     return(MathF.Sign(ReadRegisterFloat(Reg)));
 }
예제 #23
0
 protected virtual int ObjectSort(T x, T y)
 {
     return(MathF.Sign(x.Position.Z - y.Position.Z));
 }
예제 #24
0
        private void ValidateResult(Single[] firstOp, Single[] result, [CallerMemberName] string method = "")
        {
            if (BitConverter.SingleToInt32Bits(result[0]) != BitConverter.SingleToInt32Bits(MathF.Round(firstOp[0])))
            {
                Succeeded = false;
            }
            else
            {
                for (var i = 1; i < RetElementCount; i++)
                {
                    if (BitConverter.SingleToInt32Bits(result[i]) != BitConverter.SingleToInt32Bits(MathF.Round(firstOp[i])))
                    {
                        Succeeded = false;
                        break;
                    }
                }
            }

            if (!Succeeded)
            {
                Console.WriteLine($"{nameof(Sse41)}.{nameof(Sse41.RoundCurrentDirection)}<Single>(Vector128<Single>): {method} failed:");
                Console.WriteLine($"  firstOp: ({string.Join(", ", firstOp)})");
                Console.WriteLine($"   result: ({string.Join(", ", result)})");
                Console.WriteLine();
            }
        }
예제 #25
0
            public int Compare(BaseItem x, BaseItem y)
            {
                PackageItem itemA = x as PackageItem;
                PackageItem itemB = y as PackageItem;

                if (itemA == itemB)
                {
                    return(0);
                }
                if (itemA == null)
                {
                    return(this.sortOrder == SortOrder.Ascending ? 1 : -1);
                }
                if (itemB == null)
                {
                    return(this.sortOrder == SortOrder.Ascending ? -1 : 1);
                }

                int result = 0;

                if (result == 0 || this.sortMode == SortMode.Version)
                {
                    if (itemA.Version < itemB.Version)
                    {
                        result = -1;
                    }
                    else if (itemA.Version > itemB.Version)
                    {
                        result = 1;
                    }
                }
                if (result == 0 || this.sortMode == SortMode.Date)
                {
                    if (itemA.ItemPackageInfo.PublishDate < itemB.ItemPackageInfo.PublishDate)
                    {
                        result = -1;
                    }
                    else if (itemA.ItemPackageInfo.PublishDate > itemB.ItemPackageInfo.PublishDate)
                    {
                        result = 1;
                    }
                }
                if (result == 0 || this.sortMode == SortMode.Downloads)
                {
                    int itemANum = itemA.Downloads.HasValue ? itemA.Downloads.Value : 0;
                    int itemBNum = itemB.Downloads.HasValue ? itemB.Downloads.Value : 0;
                    result = itemANum - itemBNum;
                }
                if (result == 0 || this.sortMode == SortMode.Name)
                {
                    result = string.Compare(itemA.Title, itemB.Title);
                }
                if (result == 0 || this.sortMode == SortMode.PackageType)
                {
                    result = (int)itemA.Type - (int)itemB.Type;
                }
                if (result == 0 || this.sortMode == SortMode.CombinedScore)
                {
                    float scoreA = (float)itemA.ItemPackageInfo.DownloadCount * (1.0f - MathF.Clamp((float)(DateTime.Now - itemA.ItemPackageInfo.PublishDate).TotalDays / 360.0f, 0.001f, 1.0f));
                    float scoreB = (float)itemB.ItemPackageInfo.DownloadCount * (1.0f - MathF.Clamp((float)(DateTime.Now - itemB.ItemPackageInfo.PublishDate).TotalDays / 360.0f, 0.001f, 1.0f));
                    if (scoreA < scoreB)
                    {
                        result = -1;
                    }
                    else if (scoreA > scoreB)
                    {
                        result = 1;
                    }
                }
                if (result == 0)
                {
                    result = itemA.GetHashCode() - itemB.GetHashCode();
                }

                return((this.sortOrder == SortOrder.Ascending) ? -result : result);
            }
예제 #26
0
 public bool Contains(float x, float y)
 {
     return(Radius >= MathF.Sqrt(MathF.Pow(Center.X - x, 2) + MathF.Pow(Center.Y - y, 2)));
 }
예제 #27
0
 public static float FilterDefencePerMilValue(float defence)
 {
     return MathF.Min(defence, MaxDefence);
 }
        private void ValidateResult(Single[] firstOp, Single[] secondOp, Single[] thirdOp, Single[] result, [CallerMemberName] string method = "")
        {
            if (BitConverter.SingleToInt32Bits(MathF.Round(-(firstOp[0] * secondOp[0]) - thirdOp[0], 3)) != BitConverter.SingleToInt32Bits(MathF.Round(result[0], 3)))
            {
                Succeeded = false;
            }
            else
            {
                for (var i = 1; i < RetElementCount; i++)
                {
                    if (BitConverter.SingleToInt32Bits(MathF.Round(-(firstOp[i] * secondOp[i]) - thirdOp[i], 3)) != BitConverter.SingleToInt32Bits(MathF.Round(result[i], 3)))
                    {
                        Succeeded = false;
                        break;
                    }
                }
            }

            if (!Succeeded)
            {
                TestLibrary.TestFramework.LogInformation($"{nameof(Fma)}.{nameof(Fma.MultiplySubtractNegated)}<Single>(Vector128<Single>, Vector128<Single>, Vector128<Single>): {method} failed:");
                TestLibrary.TestFramework.LogInformation($"   firstOp: ({string.Join(", ", firstOp)})");
                TestLibrary.TestFramework.LogInformation($"  secondOp: ({string.Join(", ", secondOp)})");
                TestLibrary.TestFramework.LogInformation($"   thirdOp: ({string.Join(", ", thirdOp)})");
                TestLibrary.TestFramework.LogInformation($"    result: ({string.Join(", ", result)})");
                TestLibrary.TestFramework.LogInformation(string.Empty);
            }
        }
예제 #29
0
 /// <summary>
 /// Calculates the distance between two <see cref="PositionF"/> objects.
 /// </summary>
 public static double DistanceTo(PositionF from, PositionF to) => MathF.Sqrt(Square(to.X - from.X) + Square(to.Y - from.Y) + Square(to.Z - from.Z));
        /// <inheritdoc/>
        protected override void OnFrameApply(ImageFrame <TPixel> source, Rectangle sourceRectangle, Configuration configuration)
        {
            int kernelYHeight = this.KernelY.Rows;
            int kernelYWidth  = this.KernelY.Columns;
            int kernelXHeight = this.KernelX.Rows;
            int kernelXWidth  = this.KernelX.Columns;
            int radiusY       = kernelYHeight >> 1;
            int radiusX       = kernelXWidth >> 1;

            int startY = sourceRectangle.Y;
            int endY   = sourceRectangle.Bottom;
            int startX = sourceRectangle.X;
            int endX   = sourceRectangle.Right;
            int maxY   = endY - 1;
            int maxX   = endX - 1;

            using (Buffer2D <TPixel> targetPixels = configuration.MemoryAllocator.Allocate2D <TPixel>(source.Width, source.Height))
            {
                source.CopyTo(targetPixels);

                Parallel.For(
                    startY,
                    endY,
                    configuration.ParallelOptions,
                    y =>
                {
                    Span <TPixel> sourceRow = source.GetPixelRowSpan(y);
                    Span <TPixel> targetRow = targetPixels.GetRowSpan(y);

                    for (int x = startX; x < endX; x++)
                    {
                        float rX = 0;
                        float gX = 0;
                        float bX = 0;
                        float rY = 0;
                        float gY = 0;
                        float bY = 0;

                        // Apply each matrix multiplier to the color components for each pixel.
                        for (int fy = 0; fy < kernelYHeight; fy++)
                        {
                            int fyr     = fy - radiusY;
                            int offsetY = y + fyr;

                            offsetY = offsetY.Clamp(0, maxY);
                            Span <TPixel> sourceOffsetRow = source.GetPixelRowSpan(offsetY);

                            for (int fx = 0; fx < kernelXWidth; fx++)
                            {
                                int fxr     = fx - radiusX;
                                int offsetX = x + fxr;

                                offsetX = offsetX.Clamp(0, maxX);
                                Vector4 currentColor = sourceOffsetRow[offsetX].ToVector4().Premultiply();

                                if (fy < kernelXHeight)
                                {
                                    Vector4 kx = this.KernelX[fy, fx] * currentColor;
                                    rX        += kx.X;
                                    gX        += kx.Y;
                                    bX        += kx.Z;
                                }

                                if (fx < kernelYWidth)
                                {
                                    Vector4 ky = this.KernelY[fy, fx] * currentColor;
                                    rY        += ky.X;
                                    gY        += ky.Y;
                                    bY        += ky.Z;
                                }
                            }
                        }

                        float red   = MathF.Sqrt((rX * rX) + (rY * rY));
                        float green = MathF.Sqrt((gX * gX) + (gY * gY));
                        float blue  = MathF.Sqrt((bX * bX) + (bY * bY));

                        ref TPixel pixel = ref targetRow[x];
                        pixel.PackFromVector4(new Vector4(red, green, blue, sourceRow[x].ToVector4().W).UnPremultiply());
                    }
                });

                Buffer2D <TPixel> .SwapOrCopyContent(source.PixelBuffer, targetPixels);
            }
        }