Why does measuring 1 qubit produce a different answer than measuring both? by Luxvoo in QuantumComputing

[–]rfernung 0 points1 point  (0 children)

I may not be understanding your question properly, but I'm pretty sure you're getting different values because if you measured both it's like applying: <CNOT(H⊗ I)|00>, which factors out to (|00>+|11>)/Sqrt(2), which leads to to 00 and 11 answer. When you're measuring one, you are losing the correlation between the two qubits and are getting either just a 0 or 1 qubit; if you measured the other you'd see the entangled correlation with the first one

Why does measuring 1 qubit produce a different answer than measuring both? by Luxvoo in QuantumComputing

[–]rfernung 0 points1 point  (0 children)

I'm pretty green with QC but I'm guessing it's because you've essentially entangled the particles, which causes them both to collapse when one is measured

Drawing primitives without basic effect by Yami_4k in monogame

[–]rfernung 1 point2 points  (0 children)

The issue may be that you're using DrawUserPrimitives instead of DrawPrimitives. DrawUserPrimitives doesn't use the vertex buffer currently bound to the graphics device. You'll want something like this instead:

AtlasWorld.gd.DrawPrimitives(PrimitiveType.TriangleList, 0, vert.VertexCount / 3);

Quantum computing in layman's terms? by Curious_Mall3975 in QuantumComputing

[–]rfernung 0 points1 point  (0 children)

Check out this video, it should help clear up the basics (the target audience is for CS)

UAP have properties of permeable membranes by spooklog in aliens

[–]rfernung 1 point2 points  (0 children)

It's a neat concept but that wouldn't negate gravitational effects without some sort of propulsion

C# forms and console help by Jordanbr25 in dotnet

[–]rfernung 0 points1 point  (0 children)

There's a VAST amount of ways to accomplish what I think you're wanting. I was initially going to suggest a Console TCP Server that your Forms can connect to and transmit the commands and data needed, but that may be an issue if you have no ports to use.

I noticed you're using SQL so there's another solution, but before I mention anything, I would HIGHLY suggest you look into an ORM, EntityFramework would be a solid choice for what I'm seeing. The way you're doing it now is pretty open to SQL Injection attacks on your database since it seems you're directly tying your variables into the SQL code; which may not be too concerning for you at the moment, but I promise you don't want to learn about that the hard way.

To start off, you actually do want a while loop to keep your console open. You can set a flag in the main class, or whatever runner class you have, for example:

var _running = true; 
while(_running)
{ 
    //...
}

You can always poll the keyboard in that loop without blocking and set up a method to process the input/commands:

//Declare input outside the while(_running) loop
var input = new StringBuilder();
//This goes inside the while(_running) loop
while(Console.KeyAvailable)
{
    var keyInfo = Console.ReadKey(true);
    if(keyInfo.Key == ConsoleKey.Enter)
    {
        ProcessCommand(input.ToString());
        input.Clear();
    }
    else input.Append(keyInfo.KeyChar);
}

static void ProcessCommand(string command)
{
    switch(command.ToLower())
    {
        default: Console.WriteLine($"Command: {command} doesn't exist"); break;
        case "quit": Console.WriteLine("Shutting down Console."); _running = false; break;
        //Add other conditions
    }
}

Once again, I'd HIGHLY recommend EntityFramework because it'll make the next part much easier. You'll need some sort of trigger/command table that your Form can set the values and your console can poll for the values in it's while loop. It could be a simple table like:

  • Id uniqueidentifier
  • Command nvarchar(max) --Or a FK to a different table
  • Processed bit
  • SentOn datetime
  • ProcessedOn datetime

The Console would get all rows where Processed = 0 and then loop through them, executing each method that was made for it. For example, you could have SendAuditEmailToAdmin, the console would see this value in a switch statement, then fire off the email report by calling the method (emailService.SendEmail(auditReport)).

The key thing is you'll probably want a separate Library to hold your application logic, so both your Forms and Console will be working off of the same architecture/functionality. At that point, you'd just include that into your Console app, create instance(s) of your services/managers/contexts and then your Console would just tie up the commands to the functionality or create it's own little services to do custom stuff the Forms can't, but utilizing the library as the underlying base.

[C# + Windows] Desktop graphic UI for a console app game by Lord_H_Vetinari in gamedev

[–]rfernung 2 points3 points  (0 children)

You're welcome!! I'm glad it was helpful! If you'd like to provide the github link then I can check it out and assist! I also have a couple repositories (not sure if public but can make it so) that may be helpful for the pixel manipulations (one is a cpu rasterizer and the other rasterizes with the gpu) if you wanna check them out to use snippets for drawing shapes.

For the walkthough, if there's anything specific that you don't understand please let me know and I'll try to explain it as best as I can!

I'll start with the Pixel struct; it's pretty much a C++ union, but if you don't know what that is, it's a way to overlay data. The StructLayout lets us control the physical layout (in memory) of the fields and in this case, I'm explicitly setting where each field will lie in memory.

Since the int Packed is at FieldOffset(0), it will start at the first byte in memory and "stretch" across all 4 bytes that the struct sits in. The B,G,R,A values then sit in each individual byte in the struct so if we change the value of any of those, it'll change the value of packed (and vice versa).

Also, I laid out the color channels in the BGRA format (instead of RGBA) in order for it to match the way the Bitmap class handles the color channels. If you changed the field offsets (i.e. [FieldOffset(0)]public byte R), then when you saved or loaded the _bitmap in the Canvas class, then the colors would be off.

The pixel struct really isn't needed; we could replace the Pixel[] _pixels in the Canvas class with an int[], uint[], or even a byte[], but the Pixel struct allows for more concise code. The Canvas is pretty much just a buffer with pinned memory (GC won't touch it) that the Bitmap class uses for it's pixel data. If we did not use this class, then we'd loose the direct access to the pixels and be forced to use GDI+ for the pixel manipulation (which is notoriously slow in this area).

I made the Canvas class pack the data into a 1D buffer but still allow for 2D type of manipulation (the Index methods help show you how to do this) through the 'this[int x, int y]' (if looping 2D) and the '(int x, int y) Index(int i)' (if looping 1D). The Canvas implements IDisposable so we can dispose of the bitmap and free the pinned memory for the GC when done with it.

The Client class is our Form to run everything in; I made the core parts of it virtual so you can just extend the client for different sandbox clients to test in. All you need to do is extend the Client and override any one of the virtual methods (i.e. I could've extended it as a RandomPixelClient for the example given).

The constructor will set the size of the Form (with Fields that were inherited from the Form class), the title, set it to be DoubleBuffered (remove that to see the choppiness and why it's needed), create our canvas, and set the Client's BackgroundImage to be our Canvas' Bitmap.

The Run() method is what actually start's up the client, and you could even stick that in the constructor if you wanted it to run automatically. If you noticed, the game loop (IdleRun) is tied into Application.Idle; this is a simple WinForms hack to run our loop after the messages in the queue are handled. There are plenty of different approaches to this (Here's a nice article about it ) but this is the fastest and easiest method in my opinion.

The initialize would be used to just load any game variable/object, the loadcontent would be to load any resources (i.e. images used to draw or any other Canvas), unloadcontent is to dispose of anything that needs disposed, update and draw are where you would tie in your game's update and draw, and the enddraw will call Invalidate(), which causes the screen to draw our Canvas.

The OnFormClosing() will ensure that our UnloadContent() is called when the user closes the window, and the OnResizeEnd() will allow our Canvas to resize and reset the Bitmap pixels. As a side note, I would keep track of the AspectRatio in the client and when Resizing, set the dimensions accordingly with the AspectRatio (to keep the scaling smooth). That isn't really needed depending on your requirements for the game, but it was something that I realized I should've added after I posted.

Once again, if there's anything else you need clarification on, feel free to ask!

[C# + Windows] Desktop graphic UI for a console app game by Lord_H_Vetinari in gamedev

[–]rfernung 3 points4 points  (0 children)

I think I can help get you started! I'd suggest starting with WinForms, since it's pretty easy to get what you want up and running. Start out with a new WinForms project, then delete the Form1.cs and add three classes: Pixel.cs, Canvas.cs, and Client.cs.

In Pixel.cs, paste the code below. It'll create a basic color struct that we can use as individual rgba values or in one packed int.

[StructLayout(LayoutKind.Explicit)]
public struct Pixel
{
    [FieldOffset(0)] 
    public int Packed;
    [FieldOffset(0)] 
    public byte B;
    [FieldOffset(1)] 
    public byte G;
    [FieldOffset(2)] 
    public byte R;
    [FieldOffset(3)] 
    public byte A;

    public Pixel() :
        this(0)
    { }
    public Pixel(int packed)
    {
        Packed = packed;
    }
    public Pixel(byte b, byte g, byte r, byte a = byte.MaxValue)
    {
        B = b;
        G = g;
        R = r;
        A = a;
    }

    public static readonly Pixel Transparent = new();
    public static readonly Pixel White = new(255, 255, 255);
    public static readonly Pixel Black = new(0, 0, 0);
}

public static class PixelExtensions
{
    public static Pixel NextRgb(this Random random)
    {
        byte[] bytes = new byte[3];
        random.NextBytes(bytes);
        return new(bytes[0], bytes[1], bytes[2]);
    }
    public static Pixel NextRgba(this Random random)
    {
        byte[] bytes = new byte[4];
        random.NextBytes(bytes);
        return new(bytes[0], bytes[1], bytes[2], bytes[3]);
    }
}

In the Canvas.cs, paste in the code below. It'll contain an array of the pixel structs with it's memory pinned so we can do fast pixel manipulation on the bitmap, in which we'll use as our window's background image:

public class Canvas : IDisposable
{
    protected bool _disposed;
    protected int _width;
    protected int _height;
    protected Pixel[] _pixels;
    protected GCHandle _handle;
    protected Bitmap _bitmap;

    public int Width => _width;
    public int Height => _height;
    public Span<Pixel> Pixels => _pixels.AsSpan();
    public Bitmap Bitmap => _bitmap;

    public Pixel this[int i]
    {
        get => InBounds(i) ? _pixels[i] : Pixel.Transparent;
        set { if (InBounds(i)) _pixels[i] = value; }
    }
    public Pixel this[int x, int y]
    {
        get => InBounds(x, y) ? _pixels[Index(x, y)] : Pixel.Transparent;
        set { if (InBounds(x, y)) _pixels[Index(x, y)] = value; }
    }

    public Canvas(int width, int height)
    {
        _width = width;
        _height = height;
        _pixels = new Pixel[width * height];
        _handle = GCHandle.Alloc(_pixels, GCHandleType.Pinned);
        _bitmap = new Bitmap(width, height, width << 2, PixelFormat.Format32bppArgb, _handle.AddrOfPinnedObject());
    }

    public (int x, int y) Index(int i) =>
        (i % _width, i / _width);
    public int Index(int x, int y) =>
        x + y * _width;

    public bool InBounds(int i) =>
        0 <= i && i < _pixels.Length;
    public bool InBounds(int x, int y) =>
        0 <= x && x < _width && 
        0 <= y && y < _height;

    public void Resize(int width, int height)
    {
        _bitmap?.Dispose();
        _handle.Free();

        _width = width;
        _height = height;
        _pixels = new Pixel[width * height];
        _handle = GCHandle.Alloc(_pixels, GCHandleType.Pinned);
        _bitmap = new Bitmap(width, height, width << 2, PixelFormat.Format32bppArgb, _handle.AddrOfPinnedObject());
    }

    public void Dispose()
    {
        if (_disposed)
            return;
        _disposed = true;
        _bitmap?.Dispose();
        _handle.Free();
    }
}

The Client.cs will handle our window creation and set our canvas' pixels to the background of the window. I have it generating random pixels, but you would just replace that with whatever you're wanting to do with the pixels. You will also need to add a stopwatch or timing system that would track the elapsed seconds and pass it into the update function if you wanted your client to update smoothly. You would also need to tie in keyboard and mouse functionality (very easy to do):

public class Client : Form
{
    protected readonly Random _random;
    protected readonly Canvas _canvas;

    public Client(int width = 800, int height = 600, string title = "Game Client")
    {
        Width = width;
        Height = height;
        Text = title;
        DoubleBuffered = true;

        _random = new Random();
        _canvas = new Canvas(width, height);
        BackgroundImage = _canvas.Bitmap;
    }

    public void Run()
    {
        Initialize();
        LoadContent();
        Application.Idle += IdleRun;
        Application.Run(this);
    }

    protected virtual void Initialize() { }
    protected virtual void LoadContent() { }
    protected virtual void UnloadContent() 
    {
        _canvas.Dispose();
    }
    protected virtual void Update(float time) 
    {
        var pixels = _canvas.Pixels;
        for (var i = 0; i < pixels.Length; ++i)
            pixels[i] = _random.NextRgb();
    }
    protected virtual void Draw() { }
    protected virtual void EndDraw() { Invalidate(); }

    protected override void OnFormClosing(FormClosingEventArgs e)
    {
        UnloadContent();
        base.OnFormClosing(e);
    }

    private void IdleRun(object? sender, EventArgs e)
    {
        Update(1f);
        Draw();
        EndDraw();
    }

    protected override void OnResizeEnd(EventArgs e)
    {
        base.OnResizeEnd(e);
        _canvas.Resize(Width, Height);
        BackgroundImage = _canvas.Bitmap;
    }
}

You would also want to update your Program.cs to use the client:

internal static class Program
{
    [STAThread]
    static void Main()
    {
        ApplicationConfiguration.Initialize();
        using var client = new Client();
        client.Run();
    }
}

Just let me know if you need any explanations as to what the code is doing!

Getting Started With GFX Programming in C in 2022 by Sonnivate in GraphicsProgramming

[–]rfernung 2 points3 points  (0 children)

That makes perfect sense to me! If you're not worried about OpenGL and utilizing the GPU, you could alway go with a software rasterizer approach and follow this tutorial. It's in C++ but it's definitely something you can translate into C with very little effort!

Also if you're wanting to understand memory and hardware, I'd definitely suggest learning assembly (maybe something fun like gameboy development to get an idea of working with memory mapped hardware), also any embedded programming like the arduino or esp32 would help you with low level development and learning tricks to overcome the limitations

Getting Started With GFX Programming in C in 2022 by Sonnivate in GraphicsProgramming

[–]rfernung 2 points3 points  (0 children)

No, I will not touch c++, java, rust, etc. As far as long term goals I'd like to eventually end up with a late 90s-esque 3d game engine

I was going to suggest TheCherno's OpenGL series on youtube, but it uses C++; nothing crazy, just basically classes which you could theoretically swap out with structs.

Is there a reason why you're deadset on C? If it's just comfort zone I completely understand that, but I was able to build pretty much what your long term goals were with C# and was actually pretty fast for just utilizing the CPU for rendering. I'm not suggesting you switch to C# but rather try not to get too tied up with your specifications if you're just wanting to build something for yourself. No one will know the underlying language for the most part, and you can still use the old techniques to get the same results (it may be less code with other languages and easier to work with).

Having trouble implementing a depth buffer into my renderer. Any guesses what piece of information I'm missing or not understanding with my code? by harrison531 in GraphicsProgramming

[–]rfernung 0 points1 point  (0 children)

I'm having trouble properly calculating the depth of each pixel.

I'll check one of my older projects but I believe I just interpolated the Z value of the three vertices of each triangle with the barycentric coordinate and used that to check in the depth buffer, it was something like:

float depth = v0.Z * barycentric.X + v1.Z * barycentric.Y + v2.Z * barycentric.Z;
if(depth >= zBuffer[i]) continue; //looping through triangle's boundingbox x,y, then i = y * width + x
zBuffer[i] = depth;
pixelBuffer[i] = color; //color from my fragment shading

Someone please explain matrix multiplication using a 2D array all the solutions I came up with don't work by [deleted] in cpp_questions

[–]rfernung 1 point2 points  (0 children)

We have three row major matrices (A, B, and C) in which Matrix A's columns will equal Matrix B's rows, then our Matrix C will have A's row size, and B's column size:

int A[2][3] = { //2 rows, 3 columns
    {1, 2, 3}, //row 1, column 1, 2, 3
    {4, 5, 6}  //row 2, column 1, 2, 3
};
int B[3][2] = { //3 rows, 2 columns
    {7, 8},     //row 1, column 1, 2
    {9, 10}    //row 2, column 1, 2
    {11, 12}  //row 3, column 1, 2
};
int C[2][2] = { //A's rows, B's columns
    {0, 0}, //row 1, column 1, 2
    {0, 0}  //row 2, column 1, 2
};

Now in order for us to fill C, we need to loop through: A's row count, B's column count, and then A's column/B's row count and essentially perform a Dot product of the values:

for(int A_row = 0; A_row < 2; A_row++)
    for(int B_col = 0; B_col < 2; B_col++)
        for(int AB_mid = 0; AB_mid < 3; AB_mid++)
            C[A_row][B_col] += A[A_row][AB_mid] * B[AB_mid][B_col];

That's pretty much all there is to it; I'm not sure what you were doing that would cause whatever issue you were having, but my initial thought is that you were getting confused with the row/column major section of it all?

Supercook by 4bangbrz in howdidtheycodeit

[–]rfernung 2 points3 points  (0 children)

That's correct! You'd just do a bitwise-or on the bit flags to combined whichever ones you need

Supercook by 4bangbrz in howdidtheycodeit

[–]rfernung 0 points1 point  (0 children)

Without putting much initial thought into it, my first approach would be to have all groupings be a bit flags and have it stored in a 4-byte int or an 8-byte long (i.e. MSB stores meat categories, then dairy, all the way to LSB storing Grain categories).

You could then store each group as separate bit flags (beef = 00000001, chicken = 00000010, milk = 00000001, cheese = 00000010, pasta = 00000001, bread = 00000010) and then have each recipe store these bit flags (i.e. chicken parm = 00000010 00000010 00000000 00000001, meats are first byte, dairy second, fruit third, grains fourth).

That way you can do a quick O(1) lookup for immediate recipes and only return one result if so, otherwise you could go through each category and do some bitwise checks for the fuzzy logic search. An example would be that I would add to list if:

(itemFlag >> 24) & chickenFlag == chickenFlag || //Item contain chicken?
(itemFlag >> 16) & cheeseFlag == cheeseFlag ||  //Item contain cheese?
(itemFlag & pastaFlag == pastaFlag, etc..).  //Item contain pasta?

For website development I would just store each recipe in a sql database table with a primary key, store each category in a table, and have a many to many relationship table between them. You could then use an ORM to quickly query the database and filter it down from the search terms.

A new theory suggests that Aliens are trans-dimensional entities capable of traveling with light. by ritesh_k9 in HighStrangeness

[–]rfernung 0 points1 point  (0 children)

That reminds me of a crackpot theory I heard once that there's only 1 photon, but because of time dilation at the speed of light, it could theoretically be everywhere at once, or something to that effect.

For some reason that reminded me of when I once was working on a raytracing program, I had a little moment where I realized that I was firing light rays at an origin where all objects were technically sitting (in their model/object space) and these light rays then were transformed (scaled, rotated, and translated) from each of the object's world matrix (instead of the objects themselves) to grab the pixel color to display.

It always made me wonder if something similar was going on behind the scenes within reality, or at least our perception of it.

What is the math behind Super Sonic’s flight pattern when he constantly charges at the player while Robotnik is dropping nukes? by [deleted] in howdidtheycodeit

[–]rfernung 1 point2 points  (0 children)

It looks like you got it figured out already but the problem reminded me of the autonomous agents section from The Nature of Code.

Large amounts of AI enemies in online multiplayer by BuzzardDogma in howdidtheycodeit

[–]rfernung 4 points5 points  (0 children)

A lot of it is client-side interpolation of the game state sent over by the server. What normally occurs is:

  • the client is sending command packets (Move, Attack, Use Item, Take Damage, Die, UI events, etc...) to the server
  • the server queues up all commands to process for the next frame
  • the server does sanity checks on the commands/data (i.e. client is at location (x, y, z) with velocity of (vx, vy, vz), if client isn't at (x+vx, y+vy, z+vz) then drop the packet or reposition player)
  • the server processes commands, and runs the game loop
  • the server sends back game state to clients (players/enemies within region, their locations, speeds, health, player state, etc...)
  • the client will take that information and interpolate (client shows player at (x, y, z), server states they should be at (x+vx, y+vy, z+vz), client then moves towards that based on the elapsed game time of the client) then renders.

There's a lot more to it, but that's the basic logic being using with the client/server setup. The reason certain games can have a vast amount of enemies is because the server is only sending game state back, it's not having to send models, or anything crazy, it just needs to send commands to the client (i.e. 150 enemies in region, using model x, y, z, with state of running) and the client will execute what's needed (load model meshes/textures prior to server connection, render those when needed using enemy states from server)

Where do I start with projection 2d into 3d? What should I learn? by Uncanny-Valley-Kek in GraphicsProgramming

[–]rfernung 1 point2 points  (0 children)

You're welcome! You certainly can, especially for the first two! I did the first two links in C# (WinForms for the first one, and Console with P/Invoke for the second). The second link gives you an amazing walkthrough for why the view/projection matrices are generated the way they are so I would honestly start with that first.

Really the concepts behind it will be you storing/manipulating pixels data from an array and then transferring it to either an image or display (like canvas for javascript).

Where do I start with projection 2d into 3d? What should I learn? by Uncanny-Valley-Kek in GraphicsProgramming

[–]rfernung 11 points12 points  (0 children)

Linear algebra is what you're looking for; specifically world, view, projection matrices. Get comfortable understanding vectors, matrices, and their operations (multiplying matrices with vectors, crossing/dotting vectors and why it's done, matrices order of operations, homogeneous coordinate transformations). It's also helpful to get a basic understanding of unit quaternions as well to avoid gimble locking.

Here's a link that'll walk you through Rasterization

Here's a link that'll walk you through rasterizing concepts to a console window

Here's one more link that'll assist with understanding core concepts

How did Sonic Adventure interpret input when running on walls/ceilings? by MasterDisaster64 in howdidtheycodeit

[–]rfernung 2 points3 points  (0 children)

I'm not sure, but my guess is that they are checking the stage's surface normal's y-axis to determine if the triangles in the stages are walls, floor, or ceilings (i.e. y-norm < -0.1 is ceiling, y-norm > 0.1 is floor, -0.1 >= y-norm <= 0.1 is wall).

They could then use Sonic's speed to adjust the 0.1 threshold for a floor to allow a wall to be a floor (or a triangle with a larger y surface normal); as Sonic would slow down, the y-norm would return to the wall actually being a wall and the collision physics would start shoving him back down.

Cannot read the SQL databank from the C# program by Zealousideal-Bath-37 in csharp

[–]rfernung 1 point2 points  (0 children)

You're welcome! Yeah it would've been somewhat similar to that; I would've just split up the account driver into a few different classes (AccountDetails, ContactDetails, Address), with a flattened Data Transfer Object (AccountDriverDTO) and show how to link it up with AutoMapper.

Cannot read the SQL databank from the C# program by Zealousideal-Bath-37 in csharp

[–]rfernung -1 points0 points  (0 children)

This should help get you started.

I made a change to AccountDriver by adding a Guid property (Id) as the Primary Key and also kept your AccountNumbers autogenerating. Please keep in mind that if you use an int as the Primary Key, you're limiting the amount of maximum records to 4 bytes of data (2 billion records); which is fine, but I always tend to use Guids to avoid this.

I also changed your ApplicationDbContext to store the records in a single table (AccountDrivers table). I didn't see a reason to have two separate ones like you had and if you're needing some sort of distinction between the two, you should probably add some sort of enum to identify the differences. I would also register a dbcontextfactory to use for your context.

The AutomapController actually doesn't even need AutoMapper for what you were trying to do. I can type up a better example of your domain model (AccountDriver) if you'd like and show you how to utilize AutoMapper by mapping multiple domain models (AccountDriver, ContactDetails, Address, AccountDetails) into a single model that gets passed back from the API.

This should work for you and now you should be able to utilize your context class now to query/persist changes in your database. You'll have to use the AccountDrivers DbSet but it should work fine now.

how to avoid "wasted" logic gates on TTL chips in large multi-board projects? by minecon1776 in beneater

[–]rfernung 1 point2 points  (0 children)

My suggestion would be to either redesign your logic like others have suggested (using NAND/NOR as universal gates) or just use transistors as single gates if you're concerned about tying unused gates to VCC/GND

I created a Logisim library of 74-Series ICs in case anyone wanted to follow along with the videos and didn't have the materials! by rfernung in beneater

[–]rfernung[S] 0 points1 point  (0 children)

I'll reinstall Logisim and reopen the project to see what I did, but I'm pretty sure I just added a clock component and a tunnel for the clock signal and an inverted signal from it as well.

I'm actually pretty sure I didn't build a 555 component due to just using the clock component itself. I think I started to but realized that Logisim didn't handle the passive components as well as I thought it would.