Jump to content

  • Log In with Google      Sign In   
  • Create Account

Banner advertising on our site currently available from just $5!


1. Learn about the promo. 2. Sign up for GDNet+. 3. Set up your advert!


Washu

Member Since 24 Mar 2001
Offline Last Active Today, 09:15 AM

#5219320 Can you have to long of a hash string key.

Posted by Washu on Yesterday, 08:45 AM

Why are you storing GUID's in memory as a string. Store them as a quadruplet of dwords (which is effectively what they are), or use the Win32 GUID structure..


#5218959 c++ count lines in txt file and then read these lines without reopening a file

Posted by Washu on 24 March 2015 - 08:11 PM

Also, for those who are curious as to the memory mapped way... This is a non-modifying version that does not require more than one allocation for the file (again, you can do the same with vector and reserve). As you can see, the code does get more complicated, and we need to use a helper object for storing our ranges. We could have mapped the view with FILE_MAP_COPY, and then modified it (thus not modifying the underlying file), however that would involve an extra copy.
 
#include <iostream>
#include <vector>
#include <memory>
#include <windows.h>

template<class T>
struct basic_string_range {
    T const * startPtr;
    T const * endPtr;
};

typedef basic_string_range<char> string_range;
typedef basic_string_range<wchar_t> wstring_range;

template<class T>
std::basic_ostream<T> & operator <<(std::basic_ostream<T> & out, string_range const & range) {
    return out.write(range.startPtr, range.endPtr - range.startPtr);
}

typedef std::unique_ptr<void, BOOL(__stdcall *)(HANDLE)> safe_handle;
typedef std::unique_ptr<char const, BOOL(__stdcall *)(LPCVOID)> file_pointer;

int main() {
    safe_handle fileHandle(CreateFile(L"text.txt", GENERIC_READ, 0, 0, OPEN_EXISTING, 0, 0), CloseHandle);
    auto fileSize = GetFileSize(fileHandle.get(), 0);
    safe_handle mappingHandle(CreateFileMapping(fileHandle.get(), 0, PAGE_READONLY, 0, 0, 0), CloseHandle);
    file_pointer fileView(reinterpret_cast<char const *>(MapViewOfFile(mappingHandle.get(), FILE_MAP_READ, 0, 0, fileSize)), UnmapViewOfFile);
    auto fileViewPtr = fileView.get();

    std::vector<string_range> ptrs;
    string_range range = { fileViewPtr };

    for (size_t i = 1; i < fileSize; ++i) {
        if (fileViewPtr[i] == '\r' || fileViewPtr[i] == '\n') {
            if (i + 1 < fileSize && fileViewPtr[i + 1] == '\n')
                ++i;
            range.endPtr = fileViewPtr + i;
            ptrs.push_back(range);
            if (i + 1 < fileSize) {
                range = { fileViewPtr + i + 1 };
            }
        }
    }
    range.endPtr = fileViewPtr + fileSize;
    ptrs.push_back(range);

    std::cout << "Lines: " << ptrs.size() << std::endl;
    for (auto && ptr : ptrs) {
        std::cout << ptr << std::endl;
    }
}



#5218763 c++ count lines in txt file and then read these lines without reopening a file

Posted by Washu on 24 March 2015 - 08:43 AM

Since we're going crazy with memory mapping, why not just go the C-style route?

- Load the entire file into memory.
- Scan it for newline characters, converting each into a null terminator as you find it.
- Keep the count of each newline you replaced.
- Allocate a char*[] using newline count.
- Loop over the modified file again, setting each pointer to the start of each respective string (the start of the file and at the character following each null terminator). Stop your loop when you hit the newline count you've been tracking.


Why on earth would you do this loop twice, when you can combine both steps into one.... even in C you could simply reallocate the array of pointers if necessary. Telling the size of the file is pretty damn simple too... A C++ version:
 
	std::ifstream fin("somefile.txt", std::ios_base::in);
	fin.seekg(0, fin.end);
	auto length = fin.tellg();
	fin.seekg(0, fin.beg);

	std::vector<char> data;
	data.reserve(length);

	std::vector<size_t> string_offsets;
	string_offsets.push_back(0);

	while (fin) {
		auto ch = fin.get();
		if (ch == '\n') {
			data.push_back(0);
			string_offsets.push_back(data.size());
		}
		else {
			data.push_back(ch);
		}
	}
	data.push_back(0);

	for (auto && offset : string_offsets) {
		std::cout << (&data[0] + offset) << std::endl;
	}



#5217857 Any good cross platform C++ scheduler libraries?

Posted by Washu on 20 March 2015 - 08:30 AM

You should look into Intel's TBB.


#5214222 Vulkan is Next-Gen OpenGL

Posted by Washu on 03 March 2015 - 09:35 AM

why should someone want to use D3D12 ?

 
The reason to prefer D3D has always been more robust drivers and better tools on an API that hits ~95% of the target market.  That's it.  Preference for one vendor or one platform comes nowhere into it, nor do any malicious backdoor shenanigans.  The D3D driver model was simply a better driver model that, once the emotional aspect of the original API war burned out, became obvious to everyone that it allowed for this to happen.  But that's also the hurdle that Vulkan now has to get over (and Khronos are making the right kind of noises about this, which is encouraging).
 
Right now Vulkan seems to have a head-start, and if we can get a spec, sample apps, some functional tools and reasonable drivers from all 3 desktop vendors by SIGGRAPH, it should eat D3D 12.
 
On the other hand if Khronos stall or if the vendors fail to deliver then D3D 12 will have a chance to jump back ahead.
 
Either way the next year is going to be interesting. biggrin.png


Robust tools are a huge winning point there. OpenGL could target 95% of the market as well, but the lack of decent vendor agnostic tools made it a real pain in the keister to use. Using an API where you can actually debug what is going on (PIX for example) is really important. Unfortunately, OpenGL never really had that capability and you were stuck with whatever tools the various GPU vendors provided. Which, frankly, all suck in their own unique ways.

Vulkan certainly looks interesting, but I also recall the LAST TIME we were promised something great OpenGL wise. You might remember how that ended. So at the moment I'm going to go with current mood: Pessimistic without further evidence.


#5209297 Why am I getting Access Violation Reading with XMVector3TransformCoord

Posted by Washu on 07 February 2015 - 01:20 PM

Well interestingly, I did more research and it was told the class address wasn't proply aligned and to use _mm_malloc function. Which I did and it works. I remembered to free the class when done with _mm_free function as well. That's something I learned new today.


In 32 bit mode objects allocated on the heap are aligned to an 8 byte boundary. Meanwhile the non-unaligned load/store operations require paragraph alignment (16 bytes) for cache reasons. As such, sometimes things "might" work when you don't allocate them using an aligned allocator, and some might end up unaligned (as you found out).

In C there's an aligned_alloc function, and in C++ you can use the std::align function to return an aligned pointer from a block of memory (of course, this does require you to allocate sufficient memory to fit the aligned object plus however is necessary to align it). Do note that if you simply point a class at your aligned memory... a constructor will not be called. So if you have non-trivial constructors you need to use placement new, and if you have a non-trivial destructor you will need to invoke that as well.


#5209203 XML Serialization

Posted by Washu on 06 February 2015 - 08:06 PM

Umm..., a quick google on C# XML, will turn up plenty of results.

Other than that you're going to have to be a LOT MORE specific about what you're trying to ask.


#5209193 MASM Assembly Help!

Posted by Washu on 06 February 2015 - 07:17 PM

move AH, 9h


"move" is not a valid opcode.

Additionally, i would recommend learning 32 bit assembly, as 16 bit assembly is pretty much not used anywhere and the architecture of 16 bit mode is pretty much replicated nowhere (so the knowledge isn't even useful on other platforms for the most part)


#5208009 When to use pointers or objects in 'Composition'?

Posted by Washu on 01 February 2015 - 01:52 AM

E.g. if you have a TextureCache object that depends on the Graphics object, make sure it is declared after the Graphics object. Then you can safely pass the Graphics instance to the TextureCache constructor and be sure the TextureCache will be destroyed before the Graphics:

Most modern compilers will warn on this, thankfully.


#5208000 Some programmers actually hate OOP languages? WHAT?!

Posted by Washu on 01 February 2015 - 12:18 AM

In fact, I'm just going to lock this.


#5207974 Some programmers actually hate OOP languages? WHAT?!

Posted by Washu on 31 January 2015 - 07:11 PM

Nice language and conversation handling there from a "senior mod". Congrats.

I really would like to be nice. I really really would. But when someone makes trivially falsifiable statements as though they were blanket truths it becomes REAL HARD not to simply enter into my default stance, which is one of sarcasm and scorn (in case you weren't aware). That being said, the tone of the rest of this post is ENTIRELY SINCERE.

does vs 2015 looks like that when you install it? My VS 2013 does not, and I dont see any 'deafult' in tools..export setting, just options to import, export and reset setting but hey.. Im stupid so what do I know? I'll leave it to you smart and gentle guys and I promise I will check the world's VS entire install base before making stupid claims.

You need to reset your settings in order to pick a new default. Since this appears to be VERY CONFUSING for you, let me assist you with a series of images, taken from Visual Studio 2013 I might add, that detail HOW you do this. In addition, visual studio looks like whatever you want it to look like. It's had the ability to import and export color settings for a while now, and comes with two default themes (a dark and light theme) since 2012 (shown at the bottom).

Now, I do hope this tutorial is not too hard to follow. I have tried to make it AS SIMPLE AS POSSIBLE:
You start here:
VS2013-Tools-Import-Export-settings.png
Then you go to here:
Screenshot%202015-01-31%2017.05.18.png
Which is followed by this screen:
Screenshot%202015-01-31%2017.05.23.png
After which you get here:
Screenshot%202015-01-31%2017.05.28.png
Do note that clicking "Finish" at this point will reset all of your key bindings and color customizations, along with your default selected language preference.
 
To choose themes you go here:
VS2013-Tools-Options.png
Which leads to here:
Screenshot%202015-01-31%2017.10.02.png
 
I realize this was VERY complicated and terribly difficult to figure out. I really hope that I've made this supremely complex tutorial on how to change your default language and theme as simple as possible. That being said, I can certainly understand if you found it too complex to follow. Please DO FEEL FREE to ask for clarification on any points you found too hard or confusing to follow. Maybe a youtube video would help?


#5207886 Some programmers actually hate OOP languages? WHAT?!

Posted by Washu on 31 January 2015 - 12:07 PM

true.. I shouldn't have used "born" but rather "came to rule" or something like that.

Regarding Microsoft and C#.. we went from a position where C# was the (only) solution to every problem... maybe you forgot the Windows Phones that just supported C#.. or you forgot the versions of Visual Studio where you had.. new project.. C# or "other languages".. it was all about XNA, Silverlight and co. , to the current situation where .NET became the official scapegoat for the Vista debacle, there are no more "other languages" in VS tongue.png , and C++ is the suggested solution for everything performance oriented.
This shows how little you know.

Visual studio sets its self up based on what you choose when initially starting it as your preferred development environment. If you happen to choose C++ it will default to C++ as the preferred project type. This has been the case since Visual Studio 2003 (when C# was first introduced). You can change your default by going to "Tools / Import and Export Settings..." In which case your visual studio new project screen MIGHT look like:
Screenshot%202015-01-31%2010.07.54.png

Do note, Visual Studio 2015 in that screenshot.

Please fact check yourself before posting something stupid, thanks. Do note that just because you have seen one purple elephant does not mean all elephants are purple. This is a clear anecdotal fallacy.


#5207795 Some programmers actually hate OOP languages? WHAT?!

Posted by Washu on 30 January 2015 - 09:54 PM

OOP was born in a era when computers were getting faster and faster with no sign of a slow down. In those years, it was all about abstractions and optimize programmers' cost and time. Languages such as Java and C# started in that world and hit their target perfectly. Java bureaucracy of interfaces, factories, adapters and all that cruft managed to make a huge impact in the software business, allowing less experienced programmers to jump aboard because most hard and unsafe elements of the process were hidden away.

There's a lot of your history that is wrong and/or misleading. Most of the principles of Object Orientation were modeled in Smalltalk. OOP existed prior to then, however formalization of many of the common principle of object orientation happened in Smalltalk. Additionally, it was not developed as a means of making things more accessible to programmers, it was developed as a means of managing dependencies between systems. The ideas of Java (where absolutely everything is an object), are mostly a bastardization of those concepts taken from the same C++ misinterpretation of the same ideas. If you go back and read the original principles (ISP, LSP, OCP, DIP, and SRP), you will note that they do not make such strange assumptions as "public, private and protected variables" or similar things. Those are more crutches introduced into languages like C++ and Java to keep developers from making mistakes.
 

The gamedev world has always been resisting to changes, they were ages late to the "C party" (most games were done in assembler up to fairly recent days), ages late to the C++ party, and never really got in the C#/Java party because the party was over before they showed up (talking about AAA here, if you are writing a Mario clone in 2015 it doesn't really matter what tech you are using).

Game developers tend to be early adopters, actually. They just tend to also be old fogies who are resistant to change. C# is used quite commonly in game development (AAA), as are many other languages that are quite a bit "slower" than the examples you named (lua).

The Java/C# way of approaching abstractions is now "not cool" because we live in very different times.. computers are not getting faster, they're getting actually smaller and slower.. they have more cores and multithread requirements hit us like a rock.. devs had to start worrying about things like battery life.. at that point, the cost of a virtual machine started to loose it's appeal. We're now back in a situation where devs need to fight for every cpu cycle, care about memory to CPU transfer times, caches and so on.. abstraction over these things is not an option anymore.

...
All this gave to the "Mike Actons" of the industry the big chance to get out of their labs and proudly claim "see! I told you so!"... my very personal opinion is that they're just naturally inclined to resist changes, but, this time around, they got lucky and history worked in their favor.

Uh, no. Mike Acton's whole presentation isn't an argument against "Object Orientation," it's an argument against organizing data in a stupid manner with respect to its usage. If something is going to be dealt with as a batch process, that something should be organized as a batch process. Object orientation doesn't require every integer to be an object.
 

And so you see the shifts.. Microsoft shying away from C# to embrace C++ and similar trends all around the software industry.. the very fact that C++ got such a deep revamp and went into overdrive mode wrt updates is also a sign.

Microsoft just open sourced a massive chunk of C#, which along with the new .Net JIT that adds significant improvements to it, including the ability to use SIMD in C# is quite a huge step. There is no sign of them "shying away" from C#. The reason for the recent updates to C++ on Microsoft's part is mainly due to the huge developer backlash against C++/CX and other nonsense that they pushed strongly in VS2010/VS2012 as "C++ improvements." As for the C++ standards committee, that was more due to demand from developers for them to actually update the language to be a useful programming language that handles modern concerns. C++, prior to C++11, did not have any idea of what a thread was, nor anything about threads. As such, threading was entirely implementation defined. The language updates have only been a partial success though, as there are not only the old areas of undefined behavior but whole new realms of it, while only incorporating a rather small set of ideas and standard capabilities.
 

At the end of the day, OOP is now seen as "uncool" because it doesn't solve the big problems of today's high performance software: parallelism and data locality.

Parallelism and data locality are not at odds with OO. Just with people who don't understand how to use OO (i.e. that think every structure should be an object). Each paradigm has its place and problems that it solves optimally.


#5207442 Efficient way to erase an element from std::vector

Posted by Washu on 29 January 2015 - 09:28 AM

template<typename ContainerType>
void SwapAndPopAtIndex(ContainerType & container, size_t index)
{
    if (index + 1 != container.size())//#####################
        std::swap(container[index], container.back());
    container.pop_back();
}

Could you just remove the highlighted line, assuming that if an item is expensive to swap, it will contain it's own early-out inside a if-swapping-this-with-this test?

One would hope, but in practice the reality is that if you're writing a general purpose library chances are someone is going to do something stupid with it (such as having an expensive to copy object with no early out on the copy side). Better to be safe than sorry.


#5207368 Efficient way to erase an element from std::vector

Posted by Washu on 29 January 2015 - 01:56 AM

Normally you use move-semantics to avoid the copies (for non-trivial types). std::swap() handles that for you, though a single std::move() would work.
 
Here's my general function for swap-and-popping vectors:

//Swap-and-pop a specific element of a container, swapping the element with the element at the back of the container and then popping it off the stack.
//This does not preserve the order of the elements.
template<typename ContainerType>
void SwapAndPopAtIndex(ContainerType &container, size_t index)
{
	//Don't swap the back element with itself, and also don't swap out of range.
	/*
		The (index+1) is to prevent the back element from swapping with itself.

		This could be more clearly written as:	if(index >= (container.size()-1))
		...but since 'container.size()' is unsigned,
		the -1 would accidentally loop it around if size() returns 0, which is a likely occurance.
	*/
	if((index+1) >= container.size())
		return;

	//Swap the element with the back element.
	std::swap(container[index], container.back());

	//Pop the back of the container, deleting our old element.
	container.pop_back();
}
It does not preserve the order of elements.


The fact that it does not handle the case of desiring to remove the last element means this is less than a robust solution, as you end up having to write a conditional for every usage... I would recommend modifications to properly handle the case of popping the last element. Additionally, an assert for when the index is >= size would be more appropriate, as the desired goal is to fail in a non-silent manner when someone does something stupid (like try and remove an element outside of the bounds of the container). Furthermore, by handling the swap case in a saner manner, i.e. simply skipping it if we're the last element, we can call this function without requiring any additional checks. Whereas with your current one, you require a check to see if you're the last element (in which case you just pop) or call this method, which then does the same check AGAIN. Thus the solution below is probably more what you desire:
 
template<typename ContainerType>
void SwapAndPopAtIndex(ContainerType & container, size_t index)
{
    // ensure that we're not attempting to access out of the bounds of the container.
    assert(index < container.size());

    //Swap the element with the back element, except in the case when we're the last element.
    if (index + 1 != container.size())
        std::swap(container[index], container.back());

    //Pop the back of the container, deleting our old element.
    container.pop_back();
}





PARTNERS