Esempio n. 1
0
        public void FreeLeft()
        {
            var mm = new MemoryManager(new Ram(10, 1));

            var p1 = mm.Allocate(_pcb);
            var p2 = mm.Allocate(_pcb);
            var p3 = mm.Allocate(_pcb);

            mm.Free(p1);

            var freePages = mm.FreePages.ToArray();
            Assert.That(freePages[0].Offset, Is.EqualTo(0));
            Assert.That(freePages[1].Offset, Is.EqualTo(6));

            mm.Free(p3);

            freePages = mm.FreePages.ToArray();
            Assert.That(freePages[0].Offset, Is.EqualTo(0));
            Assert.That(freePages[1].Offset, Is.EqualTo(3));

            mm.Free(p2);

            freePages = mm.FreePages.ToArray();
            Assert.That(freePages.Length, Is.EqualTo(1));
            Assert.That(freePages[0].Offset, Is.EqualTo(0));
            Assert.That(freePages[0].Size, Is.EqualTo(10));
        }
Esempio n. 2
0
        public void Free()
        {
            var mm = new MemoryManager(new Ram(10, 1));

            var p1 = mm.Allocate(_pcb);
            var p2 = mm.Allocate(_pcb);
            var p3 = mm.Allocate(_pcb);

            var freeBlock = mm.FreePages.Single();
            Assert.That(freeBlock.Offset, Is.EqualTo(6));
            Assert.That(freeBlock.Size, Is.EqualTo(4));
        }
Esempio n. 3
0
        public void Allocate()
        {
            var mm = new MemoryManager(new Ram(10, 1));

            var p1 = mm.Allocate(_pcb);
            var p2 = mm.Allocate(_pcb);
            var p3 = mm.Allocate(_pcb);

            var allocated = mm.AllocatedPages.ToArray();
            Assert.That(allocated.Length, Is.EqualTo(3));
            Assert.That(new PageInfo(p1), Is.EqualTo(allocated[0]));
            Assert.That(new PageInfo(p2), Is.EqualTo(allocated[1]));
            Assert.That(new PageInfo(p3), Is.EqualTo(allocated[2]));
        }
            /// <inheritdoc />
            public override void Blend(MemoryManager memoryManager, Span <TPixel> destination, Span <TPixel> background, Span <TPixel> source, Span <float> amount)
            {
                Guard.MustBeGreaterThanOrEqualTo(background.Length, destination.Length, nameof(background.Length));
                Guard.MustBeGreaterThanOrEqualTo(source.Length, destination.Length, nameof(source.Length));
                Guard.MustBeGreaterThanOrEqualTo(amount.Length, destination.Length, nameof(amount.Length));

                using (IBuffer <Vector4> buffer = memoryManager.Allocate <Vector4>(destination.Length * 3, false))
                {
                    Span <Vector4> destinationSpan = buffer.Slice(0, destination.Length);
                    Span <Vector4> backgroundSpan  = buffer.Slice(destination.Length, destination.Length);
                    Span <Vector4> sourceSpan      = buffer.Slice(destination.Length * 2, destination.Length);

                    PixelOperations <TPixel> .Instance.ToVector4(background, backgroundSpan, destination.Length);

                    PixelOperations <TPixel> .Instance.ToVector4(source, sourceSpan, destination.Length);

                    for (int i = 0; i < destination.Length; i++)
                    {
                        destinationSpan[i] = PorterDuffFunctions.HardLight(backgroundSpan[i], sourceSpan[i], amount[i]);
                    }

                    PixelOperations <TPixel> .Instance.PackFromVector4(destinationSpan, destination, destination.Length);
                }
            }
Esempio n. 5
0
        /// <summary>
        /// Constructs a new user-created <see cref="OverlayPlaneGraphic"/> with the specified dimensions.
        /// </summary>
        /// <param name="rows">The number of rows in the overlay.</param>
        /// <param name="columns">The number of columns in the overlay.</param>
        protected OverlayPlaneGraphic(int rows, int columns)
        {
            Platform.CheckPositive(rows, "rows");
            Platform.CheckPositive(columns, "columns");

            _index          = -1;
            _frameIndex     = 0;
            _label          = string.Empty;
            _description    = string.Empty;
            _type           = OverlayType.G;
            _subtype        = null;
            _source         = OverlayPlaneSource.User;
            _overlayGraphic = new GrayscaleImageGraphic(
                rows, columns,                                  // the reported overlay dimensions
                8,                                              // bits allocated is always 8
                8,                                              // overlays always have bit depth of 1, but we upconverted the data
                7,                                              // the high bit is now 7 after upconverting
                false, false,                                   // overlays aren't signed and don't get inverted
                1, 0,                                           // overlays have no rescale
                MemoryManager.Allocate <byte>(rows * columns)); // new empty pixel buffer

            this.Color = System.Drawing.Color.PeachPuff;
            base.Graphics.Add(_overlayGraphic);
        }
Esempio n. 6
0
        private static byte[] SlabVtkImageData(vtkImageData slabData, Action <IntPtr, byte[], int, int, int, bool> slabAggregator, int bitsPerVoxel, bool signed)
        {
            // get the pointer to the image data
            var pData = slabData.GetScalarPointer();

            if (pData.Equals(IntPtr.Zero))
            {
                return(null);
            }

            // get number of subsamples and pixels per subsample
            var dataDimensions  = slabData.GetDimensions();
            var subsamplePixels = dataDimensions[0] * dataDimensions[1];
            var subsamples      = dataDimensions[2];

            // compute byte length of slabbed output data
            var dataLength = subsamplePixels * slabData.GetScalarSize();

            // slab data to managed buffer
            var pixelData = MemoryManager.Allocate <byte>(dataLength);

            slabAggregator.Invoke(pData, pixelData, subsamples, subsamplePixels, bitsPerVoxel / 8, signed);
            return(pixelData);
        }
Esempio n. 7
0
        private static byte[] MipPixelDataFromVtkSlab(vtkImageData slabImageData)
        {
            VtkHelper.StaticInitializationHack();

#if true // Do our own MIP, albeit slowly
            int[]  sliceDimensions = slabImageData.GetDimensions();
            int    sliceDataSize   = sliceDimensions[0] * sliceDimensions[1];
            IntPtr slabDataPtr     = slabImageData.GetScalarPointer();

            byte[] pixelData = MemoryManager.Allocate <byte>(sliceDataSize * sizeof(short));

            // Init with first slice
            Marshal.Copy(slabDataPtr, pixelData, 0, sliceDataSize * sizeof(short));

            // Walk through other slices, finding maximum
            unsafe
            {
                short *psSlab = (short *)slabDataPtr;

                fixed(byte *pbFrame = pixelData)
                {
                    short *psFrame = (short *)pbFrame;

                    for (int sliceIndex = 1; sliceIndex < sliceDimensions[2]; sliceIndex++)
                    {
                        for (int i = 0; i < sliceDataSize - 1; ++i)
                        {
                            int slabIndex = sliceIndex * sliceDataSize + i;
                            if (psSlab[slabIndex] > psFrame[i])
                            {
                                psFrame[i] = psSlab[slabIndex];
                            }
                        }
                    }
                }
            }

            return(pixelData);
#else // Ideally we'd use VTK to do the MIP (MinIP, Average...)
            vtkVolumeRayCastMIPFunction mip    = new vtkVolumeRayCastMIPFunction();
            vtkVolumeRayCastMapper      mapper = new vtkVolumeRayCastMapper();

            mapper.SetVolumeRayCastFunction(mip);
            mapper.SetInput(slabImageData);

            //TODO: Need to figure out how to use mapper to output vtkImageData

            vtkImageAlgorithm algo = new vtkImageAlgorithm();
            algo.SetInput(mapper.GetOutputDataObject(0));

            using (vtkExecutive exec = mapper.GetExecutive())
            {
                VtkHelper.RegisterVtkErrorEvents(exec);
                exec.Update();

                // Note: These report no output port, must have to do something else to get mapper to give us data
                //return exec.GetOutputData(0);
                return(mapper.GetOutputDataObject(0));
            }
#endif
        }
Esempio n. 8
0
 /// <summary>
 /// Unpacks the overlay data into an 8-bit overlay pixel data buffer.
 /// </summary>
 /// <returns>The unpacked, 8-bit overlay pixel data buffer.</returns>
 public byte[] Unpack()
 {
     byte[] unpackedPixelData = MemoryManager.Allocate <byte>(_rows * _columns);
     Unpack(_rawOverlayData, unpackedPixelData, _offset, unpackedPixelData.Length, _bigEndianWords);
     return(unpackedPixelData);
 }
Esempio n. 9
0
 public void Allocate(uint count)
 {
     address = (byte *)MemoryManager.Allocate((uint)count);
     length  = count;
 }
Esempio n. 10
0
 public MemoryBlock(uint length)
 {
     address     = (byte *)MemoryManager.Allocate((uint)length);
     this.length = length;
 }
Esempio n. 11
0
 private static byte[] AllocatePixelData(int rows, int columns, int bitsPerPixel)
 {
     return(MemoryManager.Allocate <byte>(rows * columns * bitsPerPixel / 8));
 }
        internal override void Apply()
        {
            this.NiNode_ctor = NetScriptFramework.Main.GameInfo.GetAddressOf(68936);
            _cachedOffsets   = new int[256];

            ulong vid        = 17693;
            int   baseOffset = 0x5430;

            Events.OnMainMenu.Register(e =>
            {
                if (this._curPlaceNode == null)
                {
                    var alloc = MemoryManager.Allocate(0x130, 0);
                    Memory.InvokeCdecl(this.NiNode_ctor, alloc, 0);
                    this._curPlaceNode = MemoryObject.FromAddress <NiNode>(alloc);
                    this._curPlaceNode.IncRef();

                    alloc             = MemoryManager.Allocate(0x10, 0);
                    this._curPlacePos = MemoryObject.FromAddress <NiPoint3>(alloc);
                    Memory.WriteZero(this._curPlacePos.Address, 0xC);
                }
            }, 0, 1);

            Memory.WriteHook(new HookParameters()
            {
                Address       = NetScriptFramework.Main.GameInfo.GetAddressOf(vid, 0x5CF2 - baseOffset, 0, "0F B6 D9 0F BE C2"),
                IncludeLength = 6,
                ReplaceLength = 6,
                Before        = ctx =>
                {
                    TESObjectWEAP weap = null;
                    Actor actor        = null;

                    int count = ctx.CX.ToUInt8();
                    try
                    {
                        weap = MemoryObject.FromAddress <TESObjectWEAP>(ctx.R12);
                    }
                    catch
                    {
                    }
                    try
                    {
                        actor = MemoryObject.FromAddress <Actor>(ctx.R15);
                    }
                    catch
                    {
                    }

                    int now = count;
                    _mod(weap, actor, ref now);

                    if (now > 255)
                    {
                        now = 255;
                    }

                    if (now != count)
                    {
                        ctx.CX = new IntPtr(now);
                    }
                },
            });

            Memory.WriteHook(new HookParameters()
            {
                Address       = NetScriptFramework.Main.GameInfo.GetAddressOf(vid, 0x603D - baseOffset, 0, "E8"),
                IncludeLength = 5,
                ReplaceLength = 5,
                After         = ctx =>
                {
                    TESObjectWEAP weap = null;
                    Actor actor        = null;
                    int count          = ctx.AX.ToUInt8();

                    try
                    {
                        weap = MemoryObject.FromAddress <TESObjectWEAP>(ctx.R12);
                    }
                    catch
                    {
                    }
                    try
                    {
                        actor = MemoryObject.FromAddress <Actor>(ctx.R15);
                    }
                    catch
                    {
                    }

                    int now = count;
                    _mod(weap, actor, ref now);

                    if (now > 255)
                    {
                        now = 255;
                    }

                    if (now != count)
                    {
                        ctx.AX = new IntPtr(now);
                    }
                },
            });

            Memory.WriteHook(new HookParameters()
            {
                Address       = NetScriptFramework.Main.GameInfo.GetAddressOf(42928, 0xB91B - 0xB360, 0, "E8"),
                IncludeLength = 5,
                ReplaceLength = 5,
                After         = ctx =>
                {
                    if (settings.ForceDrawTime.Value >= 0.0)
                    {
                        ctx.XMM0f = (float)settings.ForceDrawTime.Value;
                    }
                    else
                    {
                        int track = _projTrack;
                        if (track > 0)
                        {
                            track--;
                            _projTrack = track;

                            if (_projStrength.HasValue)
                            {
                                ctx.XMM0f = _projStrength.Value;
                                if (track == 0)
                                {
                                    _projStrength = null;
                                }
                            }
                            else
                            {
                                _projStrength = ctx.XMM0f;
                            }
                        }
                    }
                },
            });

            Memory.WriteHook(new HookParameters()
            {
                Address       = NetScriptFramework.Main.GameInfo.GetAddressOf(vid, 0x621C - baseOffset, 0, "F3 0F 10 44 24 48"),
                IncludeLength = 0, //0x3D - 0x1C,
                ReplaceLength = 0x3D - 0x1C,
                Before        = ctx =>
                {
                    var pos = MemoryObject.FromAddress <NiPoint3>(ctx.BP + 0x68);

                    int index = ctx.SI.ToUInt8();
                    if (index <= 1)
                    {
                        pos.X = Memory.ReadFloat(ctx.SP + 0x48);
                        pos.Y = Memory.ReadFloat(ctx.SP + 0x4C);
                        pos.Z = Memory.ReadFloat(ctx.SP + 0x50);
                        return;
                    }

                    var plr       = PlayerCharacter.Instance;
                    bool isPlayer = plr != null && plr.Cast <PlayerCharacter>() == ctx.R15;
                    if (isPlayer)
                    {
                        _projTrack = index;
                    }
                    else
                    {
                        _projTrack = 0;
                    }

                    float x = 0.0f;
                    float y = 0.0f;
                    _calculate_projectile_offset(index - 1, ref x, ref y);

                    if (this._curPlaceHadNode)
                    {
                        var npos = this._curPlaceNode.WorldTransform.Position;
                        npos.X   = Memory.ReadFloat(ctx.SP + 0x48);
                        npos.Y   = Memory.ReadFloat(ctx.SP + 0x4C);
                        npos.Z   = Memory.ReadFloat(ctx.SP + 0x50);

                        this._curPlacePos.X = x;
                        this._curPlacePos.Y = 0.0f;
                        this._curPlacePos.Z = y;
                        this._curPlaceNode.WorldTransform.Translate(this._curPlacePos, npos);

                        pos.X = npos.X;
                        pos.Y = npos.Y;
                        pos.Z = npos.Z;
                    }
                    else
                    {
                        bool didGet = false;
                        if (isPlayer)
                        {
                            var pcam = PlayerCamera.Instance;
                            if (pcam != null)
                            {
                                var pnode = pcam.Node;
                                if (pnode != null)
                                {
                                    byte[] buf = Memory.ReadBytes(pnode.WorldTransform.Address, 0x34);
                                    Memory.WriteBytes(this._curPlaceNode.WorldTransform.Address, buf);

                                    var tpos            = this._curPlaceNode.WorldTransform.Position;
                                    tpos.X              = Memory.ReadFloat(ctx.SP + 0x48);
                                    tpos.Y              = Memory.ReadFloat(ctx.SP + 0x4C);
                                    tpos.Z              = Memory.ReadFloat(ctx.SP + 0x50);
                                    this._curPlacePos.X = x;
                                    this._curPlacePos.Y = 0.0f;
                                    this._curPlacePos.Z = y;
                                    this._curPlaceNode.WorldTransform.Translate(this._curPlacePos, pos);
                                    didGet = true;
                                }
                            }
                        }

                        if (!didGet)
                        {
                            pos.X = Memory.ReadFloat(ctx.SP + 0x48) + x;
                            pos.Y = Memory.ReadFloat(ctx.SP + 0x4C);
                            pos.Z = Memory.ReadFloat(ctx.SP + 0x50) + y;
                        }
                    }
                }
            });

            Events.OnWeaponFireProjectilePosition.Register(e =>
            {
                if (e.Node != null)
                {
                    byte[] buf = Memory.ReadBytes(e.Node.WorldTransform.Address, 0x34);
                    Memory.WriteBytes(this._curPlaceNode.WorldTransform.Address, buf);
                    this._curPlaceHadNode = true;
                }
                else
                {
                    this._curPlaceHadNode = false;
                }
            }, 50);
        }
Esempio n. 13
0
        public unsafe ComposedLut(IComposableLut[] luts, BufferCache <int> cache, BufferCache <double> doubleCache)
        {
            //luts.Validate();
            int            lutCount;
            IComposableLut firstLut, lastLut;

            GetFirstAndLastLut(luts, out firstLut, out lastLut, out lutCount);

            _minInputValue  = (int)Math.Round(firstLut.MinInputValue);
            _maxInputValue  = (int)Math.Round(firstLut.MaxInputValue);
            _minOutputValue = (int)Math.Round(lastLut.MinOutputValue);
            _maxOutputValue = (int)Math.Round(lastLut.MaxOutputValue);

            _length = _maxInputValue - _minInputValue + 1;
            _data   = cache != null?cache.Allocate(_length) : MemoryManager.Allocate <int>(_length);

            const int intermediateDataSize = 8192;             // each double entry is 8 bytes so the entire array is 64kB - just small enough to stay off the large object heap
            var       intermediateData     = doubleCache != null?doubleCache.Allocate(intermediateDataSize) : MemoryManager.Allocate <double>(intermediateDataSize);

            try
            {
                fixed(double *intermediateLutData = intermediateData)
                fixed(int *composedLutData = _data)
                {
                    var min       = _minInputValue;
                    var max       = _maxInputValue + 1;
                    var pComposed = composedLutData;

                    // performs the bulk lookups in 64kB chunks (8k entries @ 8 bytes per) in order to keep the intermediate buffer off the large object heap
                    for (var start = min; start < max; start += intermediateDataSize)
                    {
                        var stop  = Math.Min(max, start + intermediateDataSize);
                        var count = stop - start;

                        var pIntermediate = intermediateLutData;
                        for (var i = start; i < stop; ++i)
                        {
                            *pIntermediate++ = i;
                        }

                        for (var j = 0; j < lutCount; ++j)
                        {
                            luts[j].LookupValues(intermediateData, intermediateData, count);
                        }

                        pIntermediate = intermediateLutData;
                        for (var i = 0; i < count; ++i)
                        {
                            *pComposed++ = (int)Math.Round(*pIntermediate++);
                        }
                    }
                }
            }
            finally
            {
                if (doubleCache != null)
                {
                    doubleCache.Return(intermediateData);
                }
            }
        }
Esempio n. 14
0
            // Builds the volume array. Takes care of Gantry Tilt correction (pads rows at top/bottom accordingly)
            private ushort[] BuildVolumeArray(ushort pixelPadValue, double normalizedSlope, double normalizedIntercept, out int minVolumeValue, out int maxVolumeValue)
            {
                var volumeData = MemoryManager.Allocate <ushort>(VolumeSize.Volume, TimeSpan.FromSeconds(10));
                var min        = int.MaxValue;
                var max        = int.MinValue;

                float lastFramePos = (float)_frames[_frames.Count - 1].Frame.ImagePositionPatient.Z;

                int position = 0;

                using (var lutFactory = LutFactory.Create())
                {
                    for (var n = 0; n < _frames.Count; n++)
                    {
                        var sourceFrame     = _frames[n].Frame;
                        var frameDimensions = VolumeSize;
                        var paddingRows     = PaddingRows;
                        var gantryTilt      = GantryTilt;

                        // PadTop takes care of padding rows for gantry tilt correction
                        int countRowsPaddedAtTop = 0;
                        if (paddingRows > 0)
                        {
                            // figure out how many rows need to be padded at the top
                            float  deltaMm  = lastFramePos - (float)sourceFrame.ImagePositionPatient.Z;
                            double padTopMm = Math.Tan(gantryTilt) * deltaMm;
                            countRowsPaddedAtTop = (int)(padTopMm / this.VoxelSpacing.Y + 0.5f);

                            //TODO (cr Oct 2009): verify that IPP of the first image is correct for the volume.
                            // account for the tilt in negative radians: we start padding from the bottom first in this case
                            if (gantryTilt < 0)
                            {
                                countRowsPaddedAtTop += paddingRows;
                            }

                            int stop = position + countRowsPaddedAtTop * frameDimensions.Width;
                            for (int i = position; i < stop; i++)
                            {
                                volumeData[i] = pixelPadValue;
                            }
                            position = stop;
                        }

                        // Copy frame data
                        var frameData = sourceFrame.GetNormalizedPixelData();
                        var frameBitsStored = sourceFrame.BitsStored;
                        var frameBytesPerPixel = sourceFrame.BitsAllocated / 8;
                        var frameIsSigned = sourceFrame.PixelRepresentation != 0;
                        var frameModalityLut = lutFactory.GetModalityLutLinear(frameBitsStored, frameIsSigned, sourceFrame.RescaleSlope, sourceFrame.RescaleIntercept);
                        int frameMin, frameMax;
                        CopyFrameData(frameData, frameBytesPerPixel, frameIsSigned, frameModalityLut, volumeData, position, normalizedSlope, normalizedIntercept, out frameMin, out frameMax);
                        position += frameData.Length / sizeof(ushort);
                        min       = Math.Min(min, frameMin);
                        max       = Math.Max(max, frameMax);

                        // Finish out any padding left over from PadTop
                        if (paddingRows > 0)                         // Pad bottom
                        {
                            int stop = position + ((paddingRows - countRowsPaddedAtTop) * frameDimensions.Width);
                            for (int i = position; i < stop; i++)
                            {
                                volumeData[i] = pixelPadValue;
                            }
                            position = stop;
                        }

                        // update progress
                        _callback(n, _frames.Count);
                    }
                }

                minVolumeValue = min;
                maxVolumeValue = max;
                return(volumeData);
            }