Insert an element into an Associative Array ?
I'm playing around with associative arrays right now and I can't seem to figure out how to add additional objects to the array. I tried insert but it doesn't recognize both arguments. Also, if I do this it produces an error: Node[bool] test; Node node; Node[bool] temp = [ false:node ]; test ~= temp; Error 1 Error: cannot append type Node[bool] to type Node[bool] C:\Users\CP\Documents\Visual Studio 2010\Projects\D\STDS\NPC.d 256 Does this mean you can't use the append operator on associative arrays ? ( this one ~= ) ?
Re: Insert an element into an Associative Array ?
Ok, thanks for the help, much appreciated. On Wednesday, 4 April 2012 at 19:57:40 UTC, ixid wrote: Oops, the comment should read as follows, and test[bool] should not be on the next line. //Conceptually maybe clearer as Node[] test[bool]
Binary Heap Errors Class level vs function level
I'm still messing around with binary heaps. I've successfully created and used it on the function level but for some reason when I move it to the class level I get an error. Furthermore, i'm not entirely sure how to use a binary heap without auto as the type. class AStar { ReferenceNode[] openListContainer; auto openList = BinaryHeap!(ReferenceNode[], a.fScore b.fScore)(openListContainer, 0 ); // Error } Error 1 Error: template instance BinaryHeap!(ReferenceNode[],a.fScore b.fScore) BinaryHeap!(ReferenceNode[],a.fScore b.fScore) does not match template declaration BinaryHeap(Store,alias less = a b) if (isRandomAccessRange!(Store) || isRandomAccessRange!(typeof(Store.init[]))) C:\Users\CP\Documents\Visual Studio 2010\Projects\D\STDS\NPC.d 101 However this is ok: class AStar { void RandomFunction() { ReferenceNode[] openListContainer; openListContainer.length = 500; auto openList = BinaryHeap!(ReferenceNode[], a.fScore b.fScore)(openListContainer, 0 ); //This is ok } } I'd also like to try this, but can't seem to figure it out: class AStar { ReferenceNode[] openListContainer; auto openList; //no identifier for declarator openlist this() { openListContainer.length = 500; openList = = BinaryHeap!(ReferenceNode[], a.fScore b.fScore)(openListContainer, 0 ); } } If I know what type openList was, after creating the heap, I could simply use that. I tried using typeid( openList ) to find out. I got the type being something like: BinaryHeap!(Referencenode[], a.fScore b.fScore) openList; However trying to use this as the type gives me this error: Error 1 Error: template instance BinaryHeap!(ReferenceNode[],a.fScore b.fScore) BinaryHeap!(ReferenceNode[],a.fScore b.fScore) does not match template declaration BinaryHeap(Store,alias less = a b) if (isRandomAccessRange!(Store) || isRandomAccessRange!(typeof(Store.init[]))) C:\Users\CP\Documents\Visual Studio 2010\Projects\D\STDS\NPC.d 101 Error 2 Error: BinaryHeap!(ReferenceNode[],a.fScore b.fScore) is used as a type C:\Users\CP\Documents\Visual Studio 2010\Projects\D\STDS\NPC.d 101 I'm just trying to get a variable called openList to the class level so it doesn't keep getting initialized everytime the function is called. Any ideas on how to work this out?
Re: Min-Heap and Hash Table help
Thanks, yes, that did work. However now when trying to insert nodes I get this error: Cannot grow a heap created over a range. I This is what I have: Node[] a; auto b = BinaryHeap!(Node[], a.fScore b.fScore)(a); Node test, test2; test2.fScore = 9; test.fScore = 10; b.insert( test ); I also tried this: Node[2500] a; auto b = BinaryHeap!(Node[], a.fScore b.fScore)(a); Node test, test2; test2.fScore = 9; test.fScore = 10; b.insert( test ); It gives the same error. I also tried this: Node[2500] a; auto b = BinaryHeap!(Array!Node, a.fScore b.fScore)(a); Node test, test2; test2.fScore = 9; test.fScore = 10; b.insert( test ); Error 1 Error: this._store()[this._length()] is not an lvalue C:\DLang\dmd2\src\phobos\std\container.d 2676 How exactly would I grow this heap? or How would I give it enough room so that I don't need to make it larger? On Tuesday, 3 April 2012 at 11:28:06 UTC, Timon Gehr wrote: On 04/03/2012 05:17 AM, Chris Pons wrote: I'm still having troubles with the min-heap. Node[] a; auto b = BinaryHeap!a.fScore b.fScore( a[] ); Error 1 Error: template instance BinaryHeap!(a.fScore b.fScore) BinaryHeap!(a.fScore b.fScore) does not match template declaration BinaryHeap(Store,alias less = a b) if (isRandomAccessRange!(Store) || isRandomAccessRange!(typeof(Store.init[]))) C:\Users\CP\Documents\Visual Studio 2010\Projects\D\STDS\NPC.d 252 That is an API design issue. This should work: auto b = BinaryHeap!(Node[], a.fScore b.fScore)(a);
Re: Min-Heap and Hash Table help
Thanks! This clears up that part very well. I'm a lot closer to having a decent path finding algorithm now. On Tuesday, 3 April 2012 at 21:24:24 UTC, Chris Cain wrote: On Tuesday, 3 April 2012 at 19:38:12 UTC, Chris Pons wrote: Thanks, yes, that did work. However now when trying to insert nodes I get this error: Cannot grow a heap created over a range. I This is what I have: ... Hey there, BinaryHeap is using the slice of memory you're giving it to use as a heap. In the first code you gave, your array is length = 0. In other words, there is no place to actually insert things! When you specified Node[2500] a, you are making an array of size 2500 filled with zeros. You still don't have any room to insert, because all of the space in the array is still taken up. Depending on your data, your option might be to just insert all the items you want first, then heapify the resulting array, maybe like this: Node[] a; foreach(i; 0..5) { Node nextNode; nextNode.fScore = (i*3) % 5; a ~= nextNode; } auto b = BinaryHeap!(Node[], a.fScore b.fScore)(a); while(!b.empty()) { writeln(b.front()); b.removeFront(); } Otherwise, if you know a maximum bound for the number of inputs, you could simply allocate enough memory to store your items, and then use the initialSize parameter. Something like this: Node[] a; // or Node[10] a; for a static array sized to 10... a.length = 10; // 0 states that nothing is in the heap auto b = BinaryHeap!(Node[], a.fScore b.fScore)(a, 0); foreach(i; 0..5) { Node nextNode; nextNode.fScore = (i*3) % 5; b.insert(nextNode); } while(!b.empty()) { writeln(b.front()); b.removeFront(); } The thing you looked like you were doing with your third option looks like it was getting close to the right track for yet another potential solution, but apparently a bug prevents this from working: http://d.puremagic.com/issues/show_bug.cgi?id=6959 If this was working, then you could use Array for an unbounded input (because it supports insertBack). I hope this helps!
Re: Add Element to list not Working
Thanks. I tried doing this and the list didn't update: void AddToList( SList!int list, int i ) { list.insert( i ); } SList!int intList; AddToList( intList, 42 ); but when I switched to this, it worked: SList!int intList; void AddToList( int i ) { intList.insert( i ); } AddToList( 42 ); The first method didn't give an error it just didn't update the list as I thought. Any idea? On Monday, 2 April 2012 at 06:07:40 UTC, Ali Çehreli wrote: On 04/01/2012 10:45 PM, Chris Pons wrote: I'm trying to add an element to a list with insert but that doesn't seem to do anything at all. If I try using ~= it says that Error: cannot append type Node to type SList!(Node). I'm pretty confused about using ~= because it works fine for arrays but apperantly not for lists. How do I add an element to a list? import std.stdio; import std.container; void main() { auto l = SList!int(); l.insert(42);// inserts front l.insert(43);// this too assert(l == SList!int(43, 42)); // inserts after the specified range (l[] is the entire list) l.insertAfter(l[], 44); assert(l == SList!int(43, 42, 44)); // This doesn't work because SList.Range doesn't define opOpAssign!~ // l[] ~= 45; } Ali
Re: Add Element to list not Working
Ah, thank you. I didn't realize taht SList is a struct and that it used value semantics. That clears this up. On Monday, 2 April 2012 at 14:22:25 UTC, Ali Çehreli wrote: On 04/01/2012 11:18 PM, Chris Pons wrote: Thanks. I tried doing this and the list didn't update: void AddToList( SList!int list, int i ) { list.insert( i ); } Oh, that has nothing to do with SList. SList is a struct and as a fundamental rule of D, structs are copied to functions. SList happens to be a struct. The list parameter of AddToList and the list variable that is passed to the function as an argument are two different variables. SList!int intList; AddToList( intList, 42 ); but when I switched to this, it worked: SList!int intList; void AddToList( int i ) { intList.insert( i ); } Global variables are not a good solution of course. :( The solution here is to pass the argument by-reference by the 'ref' keyword: void AddToList( ref SList!int list, int i ) { // ... } Ali P.S. There is this chapter that covers 'ref' and most (but not all) types of function parameters: http://ddili.org/ders/d.en/function_parameters.html
Length of an SLIst ?
I'm trying to find the length of a Slist. I've tried using the built in .length function but it generates this error: Error: no property 'length' for type 'SList!(Node)'. Are there any other built in ways to find the length?
Min-Heap and Hash Table help
I'm trying to work with and implement and priority queue( min-heap ) and a hash table. This is the first time I've worked with these data structures so I looked up some information about them to gain an understanding. From what I read, a min-heap is a binary tree that is sorted by a priority. In my case I have a struct called Node for an A* algorithm that I wanted to place in a min-heap sorted by an integer, their f score. Initially the min-heap will only have one item in it with others added later. From looking at the Library reference I have gathered this: struct Node { bool walkable; //Whether this node is blocked or open vect2 position; //The tile's position on the map in pixels int xIndex, yIndex; //The index values of the tile in the array Node*[4] connections; //An array of pointers to nodes this current node connects to Node* parent; int gScore; int hScore; int fScore; } Class AStar { Node[] a; Node start; void FindPath(Node[] PathGraph ) { a ~= start; //Heapify as min-heap by f Score? openList = heapify(a, a.fScore b.fScore ); //...After some work If I want to add a new Node Node new; //Will the list stay sorted?? openList.insert( new ); } } How would I create a min-heap sorted by fScore? Will the list stay sorted after I add a new node? As far as hash tables goes, it seems like I need to use an associative array, is that right? What exactly would the key/hash be? How would I implement this if the hash table is supposed to contain the struct Node?
Re: Min-Heap and Hash Table help
Yes, I did see that. How would I set the predicate to sort by fScore? An integer in my struct. On Monday, 2 April 2012 at 22:53:55 UTC, Justin Whear wrote: On Tue, 03 Apr 2012 00:47:56 +0200, Chris Pons wrote: I'm trying to work with and implement and priority queue( min-heap ) and a hash table. This is the first time I've worked with these data structures so I looked up some information about them to gain an understanding. From what I read, a min-heap is a binary tree that is sorted by a priority. In my case I have a struct called Node for an A* algorithm that I wanted to place in a min-heap sorted by an integer, their f score. Initially the min-heap will only have one item in it with others added later. How would I create a min-heap sorted by fScore? Will the list stay sorted after I add a new node? As far as hash tables goes, it seems like I need to use an associative array, is that right? What exactly would the key/hash be? How would I implement this if the hash table is supposed to contain the struct Node? BinaryHeap in std.container can be made to work as a min-heap, in fact the documentation specifically mentions such a use: http://dlang.org/ phobos/std_container.html#BinaryHeap
Re: Min-Heap and Hash Table help
On Monday, 2 April 2012 at 23:30:38 UTC, Justin Whear wrote: On Tue, 03 Apr 2012 01:06:54 +0200, Chris Pons wrote: Yes, I did see that. How would I set the predicate to sort by fScore? An integer in my struct. auto myHeap = BinaryHeap!`a.fScore b.fScore`( rangeOfNodes ); Ok, makes sense, will the heap be automatically sorted every time I add a new item ? Might be a dumb question, but i'm going to be removing and adding many nodes.
Re: Min-Heap and Hash Table help
I'm still having troubles with the min-heap. Node[] a; auto b = BinaryHeap!a.fScore b.fScore( a[] ); Error 1 Error: template instance BinaryHeap!(a.fScore b.fScore) BinaryHeap!(a.fScore b.fScore) does not match template declaration BinaryHeap(Store,alias less = a b) if (isRandomAccessRange!(Store) || isRandomAccessRange!(typeof(Store.init[]))) C:\Users\CP\Documents\Visual Studio 2010\Projects\D\STDS\NPC.d 252
Add Element to list not Working
I'm trying to add an element to a list with insert but that doesn't seem to do anything at all. If I try using ~= it says that Error: cannot append type Node to type SList!(Node). I'm pretty confused about using ~= because it works fine for arrays but apperantly not for lists. How do I add an element to a list?
Initializing multidimentional Array with a struct
I'm trying to figure out how to initialize a multi-dimentional array with a struct. I thought it would be straight forward, but i'm running into problems. I'm using nested for loops, and just setting the current index to a blank version of my struct but that gives me this error: Error: no [] operator overload for type Node. I didn't know I needed to overload that operator, usually didn't need to in C++ as far as I remember. struct Node { bool walkable; vect2 position; int xIndex, yIndex; Node*[4] connections; } void InitializePathGraph() { for( int x = 0; x mapWidth; x++ ) { for( int y = 0; y mapHeight; y++ ) { Node node; PathGraph[x][y] = node;// ERROR } } }
Re: Initializing multidimentional Array with a struct
I also tried this, which gives an out of range error: void InitializePathGraph() { PathGraph.length = mapWidth; foreach( elem; PathGraph ) { elem.length = mapHeight; } Node node; for( int x = 0; x mapWidth - 1; x++ ) { for( int y = 0; y mapHeight - 1; y++ ) { PathGraph[x][y] = node; } } } This is really confusing me.
Re: Initializing multidimentional Array with a struct
Yes sorry, I was looking to initialize to the default value of node. Thank you for the help! On Saturday, 31 March 2012 at 21:59:50 UTC, Ali Çehreli wrote: On 03/31/2012 02:34 PM, Chris Pons wrote: I'm trying to figure out how to initialize a multi-dimentional array with a struct. I thought it would be straight forward, but i'm running into problems. I'm using nested for loops, and just setting the current index to a blank version of my struct but that gives me this error: Error: no [] operator overload for type Node. I didn't know I needed to overload that operator, usually didn't need to in C++ as far as I remember. struct Node { bool walkable; vect2 position; int xIndex, yIndex; Node*[4] connections; } void InitializePathGraph() { for( int x = 0; x mapWidth; x++ ) { for( int y = 0; y mapHeight; y++ ) { Node node; PathGraph[x][y] = node;// ERROR } } } Do you want to initialize with the default value of Node? Then it is as easy as the following: import std.stdio; struct Node {} void main() { Node[2][3] a; // fixed-length of fixed-length Node[][] b = new Node[][](2, 3); // slice of slice writeln(a); writeln(b); } The output: [[Node(), Node()], [Node(), Node()], [Node(), Node()]] [[Node(), Node(), Node()], [Node(), Node(), Node()]] Please note the different meanings of 2 and 3 for the fixed-length array and the new expression: lines and rows are swapped! Ali
How to remove element from an SList?
Right now i'm struggling with trying to understand how to remove an element from a n SList. I only want to remove one element, not a range of elements. I also don't want to use an Array because I will have to reshuffle elements to take care of the empty spot when I remove it. The only thing I've seen so far is find from std. algorithm and linearRemove. However I can't get find to work and I don't exactly believe linearRemove will work either because afaik that removes up to the index specified? I'm not to clear on this. Here's a simplified example of what I was trying: SList!int intList; intList.insert( 1 ); auto a = find( intList, 1 ); intList.linearRemove( a );
Re: XML Parsing
On Tuesday, 20 March 2012 at 04:32:13 UTC, Adam D. Ruppe wrote: I know very little about std.xml (I looked at it and said 'meh' and wrote my own lib), but my lib makes this pretty simple. https://github.com/adamdruppe/misc-stuff-including-D-programming-language-web-stuff grab dom.d and characterencodings.d This has a bit of an html bias, but it works for xml too. === import arsd.dom; import std.file; import std.stdio; import std.conv; void main() { auto document = new Document(readText(test12.xml), true, true); auto map = document.requireSelector(map); writeln(to!int(map.width), x, to!int(map.height)); foreach(tile; document.getElementsByTagName(tile)) writeln(tile.gid); } === $ dmd test12.d dom.d characterencodings.d $ test12 25x19 snip tile data Let me explain the lines: auto document = new Document(readText(test12.xml), true, true); We use std.file.readText to read the file as a string. Document's constructor is: (string data, bool caseSensitive, bool strictMode). So, true, true means it will act like an XML parser, instead of trying to correct for html tag soup. Now, document is a DOM, like you see in W3C or web browsers (via javascript), though it is expanded with a lot of convenience and sugar. auto map = document.requireSelector(map); querySelector and requireSelector use CSS selector syntax to fetch one element. querySelector may return null, whereas requireSelector will throw an exception if the element is not found. You can learn more about CSS selector syntax on the web. I tried to cover a good chunk of the standard, including most css2 and some css3. Here, I'm asking for the first element with tag name map. You can also use querySelectorAll to get all the elements that match, returned as an array, which is great for looping. writeln(to!int(map.width), x, to!int(map.height)); The attributes on an element are exposed via dot syntax, or you can use element.getAttribute(name) if you prefer. They are returned as strings. Using std.conv.to, we can easily convert them to integers. foreach(tile; document.getElementsByTagName(tile)) writeln(tile.gid); And finally, we get all the tile tags in the document and print out their gid attribute. Note that you can also call the element search functions on individual elements. That will only return that element and its children. Here, you didn't need it, but you can also use element.innerText to get the text inside a tag, pretty much covering basic data retrieval. Note: my library is not good at handling huge files; it eats a good chunk of memory and loads the whole document at once. But, it is the easiest way I've seen (I'm biased though) to work with xml files, so I like it. Thank you. I'll check it out.
XML Parsing
Hey Guys, I am trying to parse an XML document with std.xml. I've looked over the reference of std.xml as well as the example but i'm still stuck. I've also looked over some example code, but it's a bit confusing and doesn't entirely help explain what i'm doing wrong. As far as I understand it, I should load a file with read in std.file and save that into a string. From there, I check to make sure the string xmlData is in a proper xml format. This is where it gets a bit confusing, I followed the example and created a new instance of the class document parser and then tried to parse an attribute from the start tag map. The value i'm targeting right now is the width of the map in tiles, and want to save this into an integer. However, the value I get is 0. Any help would be MUCH appreciated. Here is a reference to the XML file: http://pastebin.com/tpUU1Wtv //These two functions are called in my main loop. void LoadMap(string filename) { enforce( filename != , Filename is invalid! ); xmlData = cast(string) read(filename); enforce( xmlData != , Read file Failed! ); debug StopWatch sw = StopWatch(AutoStart.yes); check(xmlData); debug writeln( Verified XML in , sw.peek.msecs, ms.); } void ParseMap() { auto xml = new DocumentParser(xmlData); xml.onStartTag[map] = (ElementParser xml) { mapWidth = to!int(xml.tag.attr[width]); xml.parse(); }; xml.parse(); writeln(Map Width: , mapWidth); }
Error 42 Symbol Undefined
Hello, I'm trying to use the Gl3n (https://bitbucket.org/dav1d/gl3n) but I keep getting error 42 whenever I try this: alias Vector!(float, 2) vect2; vect2 position; position.x = 2.0f; //This is what causes the error I looked into how the struct was implemented and x is an alias for a get/set function that interacts with the array that stores the values for the vector. I've tried something like this: alias Vector!(float, 2) vect2; vect2 position; position = vect2(0.0f, 0.0f); However, both methods give the same error: Error 42: Symbol Undefined pure nothrow @property @safe void gl3n.linalg.Vector!(float, 2).Vector.set_!('x').set_(float) C:\Users\CP\Documents\Visual Studio 2010\Projects\D\STDS\ Error 42: Symbol Undefined _D4gl3n6linalg16__T6VectorTfVi2Z6Vector6__initZ I have the module linalg imported like this at the top: import Gl3n.linalg; //Gl3n is the folder the source files are in
Re: DLL's and D
Yes, this is a lot more clear, thanks. On Thursday, 15 March 2012 at 05:06:16 UTC, Mike Parker wrote: On 3/15/2012 12:26 PM, Chris Pons wrote: I haven't used DLL's much, especially one I've built on my own, so guidance would be appreciated. I'm trying to figure out how to build a DLL which was written in D but i'm not sure i'm doing this right. I'm using VS2010 and Visual D. Visual D has a template for Dll's in D, so I used that to create a new project. The DLL compiles just fine, but i'm having trouble even getting import to work with it. I was following the How-To on this page, http://dlang.org/dll.html#Dcode , but I can't even get import to work. With import, is that supposed to reference the name of the DLL? So if I had one named math.dll, I would write import math.dll? You are misunderstanding what the import statement does. It has absolutely nothing to do with linked libraries or DLLs. It works at the source level. In the example, the source module that is used to compile the DLL is called mydll.d (so is the DLL, but that's irrelevant). Then, in the program that uses it, you use 'import mydll;' to make the declarations in that source module visible to the compiler. For this to work, mydll.d has to be the import path, either relative to test.d in the example, or somewhere you specify with the -I switch. The actual DLL file has no part in this process. It becomes involved later, in the link step. So if your math DLL has source modules named, for example, math/vector.d and math/matrix.d, *those* are what you import in your code. import math.vector; import math.matrix; As long as those modules are somewhere on the import path, that's all you need. The compiler doesn't know or care about the DLL itself at this point. Also, what exactly is different between the dynamic load and static link in the link above? I assume you already understand how to link static libraries to a program -- you pass it to the linker. When using DMD, we typically pass it to the compiler and it hands it off to the linker for us: dmd mymodule.d someLibrary.lib That's the only way to make the symbols in a static library available to the executable at runtime -- those symbols must be compiled into the executable. A DLL is not compiled into the executable. It is loaded at runtime. This can be done in two ways: by the operating system (static load), or manually by the executable (dynamic load). In the example, you compile mydll.d and mydll.def with the following command: dmd -ofmydll.dll -L/IMPLIB mydll.d dll.d mydll.def This results in mydll.dll and mydll.lib. Now, assuming mydll.lib is in the same directory as test.d, you can use this command to create an executable that will use static loading: dmd test.d mydll.lib The actual symbols of mydll are in mydll.dll. mydll.lib, in this case, does not contain those symbols. Instead, it contains the necessary information for the OS to load the DLL into memory. So when the executable is launched, the OS sees that information, then looks for mydll.dll automatically. For dynamic loading, you don't link with mydll.lib. Instead, you have to implement some extra code in your program to load the DLL and any symbols you need via the Win32 API. The last example on that page does just that. It uses Runtime.loadLibrary (which, under the hood, uses the Win32 function LoadLibrary) to load the DLL. It then loads the getMyClass function using the Win32 function GetProcAddress. Note that it uses the fully mangled name of the function to do so. So, to dynamically load the mydll example, you would add code to test.d to load mydll.dll and to load the pointer for the print function. To compile, you would do this: dmd test.d You no longer need to link with mydll.lib, since you are loading the library manually (dynamically). Would I need to load the DLL for every module that imports it? No. Once the executable is compiled, the concept of modules essentially disappears. Everything is loaded into memory. The DLL is loaded into the executable's address space exactly one time. This makes the symbols available to everything in the same process. Even if you were to manually load the DLL multiple times with Runtime.loadLibrary, the OS would only actually load it once. I believe you've used Derelict, yes? When you call something like DerelictSDL2.load(), Derelict dynamically loads the SDL2 DLL into memory. You only need to call it at one point in your program. After that, it's available to everything in your program. But you still need to import the derelict.sdl2.sdl module into every module uses it so that the compiler knows which declarations are available for you to use. Source modules are used at compile time and must be imported into every module that uses them. DLLs are used at runtime and are only loaded into memory once. I suggest you read up on the difference between compilation
Re: DLL's and D
Ok, I've actually run into another problem. I've decided to use a static library, since my project is small. I have added the path to the static library's .lib file in my project properties, just like with derelict2. However, I'm not sure how to use import properly. The library in question is in location (relative to my project) Libraries/Math/math.lib. If a module in math.lib is matrix, i've tried import declarations like: import Libraries.Math.math.matrix; //probably very wrong import math.matrix; import matrix; I tried to look at derelict2 for an example, and the VisualD project file there, since it created .lib files. The VS 2010 solution file was in project/visuald/DerelictSDL(etc), and each project refernces modules in Derelict2\DerelictSDL\derelict\sdl\ (for example). So it makes sense that the import would be import derelict.sdl.sdl to import sdl.d. This just lead me to believe that import matrix or import math.matrix should work. Am I wrong in assuming that the library contains the D code I need to use? So I would not be trying to import the .d file I used to construct the static library?
Build errors and VS Macros for Build Commands
I've been playing around with VS Macros trying to step away from explicit declarations of library locations. I'm using a google repository as I would like to be able to work on projects either at my desktop or laptop without having to worry about specific library path locations. I tried using a macro like $(SolutionDir) or $(ProjectDir) to specify the current location of the projects but I keep getting this error when building: -- Build started: Project: STDSU, Configuration: Debug Win32 -- Building Debug\STDSU.exe... Error: cannot read file C:\Users\CP\Documents\Visual.d Building Debug\STDSU.exe failed! Details saved as file://C:\Users\CP\Documents\Visual Studio 2010\Projects\D\STDS\Debug\STDSU.buildlog.html == Build: 0 succeeded, 1 failed, 0 up-to-date, 0 skipped == However, if I specify a library location explicitly it all compiles just fine. If the location of my VS solution was: C:\Users\CP\Documents\Visual Studio 2010\Projects\D\STDS I would assume $(SolutionDir) would be equivalent. What am I missing?
Re: Proper Use of Assert and Enforce
Thank you for the valuable information! The difference between assert and enforce is now clearer in my mind. Also, that's a great trick with enforce. On Thursday, 15 March 2012 at 01:08:02 UTC, Jonathan M Davis wrote: On Wednesday, March 14, 2012 20:15:16 Spacen Jasset wrote: Is enforce then a way of generating exceptions in an easier way rather than using some sort of if (failure) throw syntax? In other words, I assume it's a mechanism to help you use exceptions, and not some new semantic. It is purely a way to make throwing an exception use a syntax similar to assert and save a line of code. if(!condition) throw new Exception(msg); becomes enforce(condition, msg); or enforce(condition, new Exception(msg)); It arguably adds very little, but some people really like it. - Jonathan M Davis
DLL's and D
I haven't used DLL's much, especially one I've built on my own, so guidance would be appreciated. I'm trying to figure out how to build a DLL which was written in D but i'm not sure i'm doing this right. I'm using VS2010 and Visual D. Visual D has a template for Dll's in D, so I used that to create a new project. The DLL compiles just fine, but i'm having trouble even getting import to work with it. I was following the How-To on this page, http://dlang.org/dll.html#Dcode , but I can't even get import to work. With import, is that supposed to reference the name of the DLL? So if I had one named math.dll, I would write import math.dll? Right now i'm getting an error, Error: module test is in file test.d which cannot be read. Also, what exactly is different between the dynamic load and static link in the link above? Would I need to load the DLL for every module that imports it? Do I need to use the export keyword for every class/function/etc that is meant to be used outside of the DLL? Also, the DLL i'm trying to make, has several modules, can I import a specific module from the dll? Like, import math.calculus if calculus was a module in the math DLL?
Math Libraries (and vectors, matrices, etc)
Does D have a math library that defines, points, vectors and matrices including the appropriate functions(addition, dot product, cross product, etc)? I'm starting my next game and I would like to know what my options are. I plan on using SDL, I'm not exactly into OpenGL yet, since I'm new and I only wish to work in 2D. Nonetheless, I would prefer to get acquainted with using linear algebra formally in games before I move to 3D.
Re: Math Libraries (and vectors, matrices, etc)
Thanks, I'll take a look. I'm new, so I might need some help properly building this. I will post back if I have any problems. On Tuesday, 13 March 2012 at 20:06:13 UTC, Dmitry Olshansky wrote: On 14.03.2012 0:03, H. S. Teoh wrote: On Tue, Mar 13, 2012 at 08:25:49PM +0100, Chris Pons wrote: Does D have a math library that defines, points, vectors and matrices including the appropriate functions(addition, dot product, cross product, etc)? I'd like to know too. I have a medium-sized D project in the works, but right now I'm stuck at deciding how best to represent matrices and vectors in a generic way. My usage will be significantly different from game programming, though, 'cos I'll be dealing with arbitrary-dimensioned vectors and matrices, not just your typical 2D/3D vector (or 4D homogenous). But it'd be nice if both can be handled generically without crippling performance losses in the 2D/3D case for game dev. T SciD worths a look, though never used nor had the need to: https://github.com/kyllingstad/scid
Re: Math Libraries (and vectors, matrices, etc)
SciD looks nice, but it seems to be a bit too complicated for my use. Are there any other alternatives? On Tuesday, 13 March 2012 at 20:14:14 UTC, Chris Pons wrote: Thanks, I'll take a look. I'm new, so I might need some help properly building this. I will post back if I have any problems. On Tuesday, 13 March 2012 at 20:06:13 UTC, Dmitry Olshansky wrote: On 14.03.2012 0:03, H. S. Teoh wrote: On Tue, Mar 13, 2012 at 08:25:49PM +0100, Chris Pons wrote: Does D have a math library that defines, points, vectors and matrices including the appropriate functions(addition, dot product, cross product, etc)? I'd like to know too. I have a medium-sized D project in the works, but right now I'm stuck at deciding how best to represent matrices and vectors in a generic way. My usage will be significantly different from game programming, though, 'cos I'll be dealing with arbitrary-dimensioned vectors and matrices, not just your typical 2D/3D vector (or 4D homogenous). But it'd be nice if both can be handled generically without crippling performance losses in the 2D/3D case for game dev. T SciD worths a look, though never used nor had the need to: https://github.com/kyllingstad/scid
Re: Math Libraries (and vectors, matrices, etc)
Oops, I didn't see the replies, after my last message. I'll check this out. Thanks! On Tuesday, 13 March 2012 at 20:34:54 UTC, Kiith-Sa wrote: SciD is a scientific math library providing vectors/matrices of arbitrary sizes, but not useful at all for game development. See gl3n for a game-oriented vector/matrix library: https://bitbucket.org/dav1d/gl3n Also, AFAIK, Manu is working on what should end up being a Phobos module for game-oriented matrices/vectors.
Proper Use of Assert and Enforce
I'm new, and trying to incorporate assert and enforce into my program properly. My question revolves around, the fact that assert is only evaluated when using the debug switch. I read that assert throws a more serious exception than enforce does, is this correct? I'm trying to use enforce in conjunction with several functions that initialize major components of the framework i'm using. However, i'm concerned with the fact that my program might continue running, while I personally would like for it to crash, if the expressions i'm trying to check fail. Here is what i'm working on: void InitSDL() { enforce( SDL_Init( SDL_Init_Everything ) 0, SDL_Init Failed!); SDL_WN_SetCaption(Test, null); backGround = SDL_SetVideoMode( xResolution, yResolution, bitsPerPixel, SDL_HWSURFACE | SDL_DOUBLEBUF); enforce( backGround != null, backGround is null!); enforce( TTF_Init() != -1, TTF_Init failed! ); } Is it proper to use in this manner? I understand that I shouldn't put anything important in an assert statement, but is this ok?
Re: Assert and the optional Message
Ok, thank you for the advice. I will look into it.
Re: Assert and the optional Message
Any idea why, system(PAUSE) does work?
Re: Assert and the optional Message
You are right, there is also an option to Pause when program finishes. I never saw it until now. Thank you for all the replies. On Friday, 9 March 2012 at 13:39:02 UTC, Dmitry Olshansky wrote: On 09.03.2012 11:42, Chris Pons wrote: I am new to D and have been playing around with Assert. I figured that using a message with assert would be very helpful, but unfortunately when the message is printed to the console, the console closes and my program ends. Is there any way to get a more permanent message? I've tried adding system(PAUSE) and it doesn't have any effect. Is there any way I could have the assert function print the message to a file? I'm using VS2010 and Visual D if that is of any importance. There is an option to redirect all console output to Output window. Right on the same window where you can choose a debugger (mago/visual studio) IRC.
Assert and the optional Message
I am new to D and have been playing around with Assert. I figured that using a message with assert would be very helpful, but unfortunately when the message is printed to the console, the console closes and my program ends. Is there any way to get a more permanent message? I've tried adding system(PAUSE) and it doesn't have any effect. Is there any way I could have the assert function print the message to a file? I'm using VS2010 and Visual D if that is of any importance.
How to cast a int to a string?
I'm trying to update a string easily whenever I change a numeric component of the string. I've tried to do this so far with no result: while( testInt 10 ) string testString = Test ; int testInt = 0; testString ~= toString(testInt) testInt++; or this: testString ~= cast(string)(testInt) Both of these give an error. This however does not, but it also doesn't seem to update testString I've also tried this: testString ~= cast(char)(testInt); It doens't throw an error, but it doesnt' seem to work either. For the record, i'm not using writln to print to console, this is through SDL and OpenGL so it should be a string.
Re: How to cast a int to a string?
On Tuesday, 6 March 2012 at 23:19:03 UTC, H. S. Teoh wrote: On Wed, Mar 07, 2012 at 12:13:54AM +0100, Chris Pons wrote: I'm trying to update a string easily whenever I change a numeric component of the string. I've tried to do this so far with no result: [...] Try this: import std.conv; ... int i = 1234; string s = to!string(i); T Thanks, that did the trick.
How to check type of an object to a class name?
Is it possible to check the type of an object to a class name? //Something like this: Class test { //... } assert(is(anonObject == typeof(test))
Char * character and string
Hello, I am trying to work with SDL and one of their functions takes a char * file as a function a parameter. However, i'm running into trouble how to actually set this variable in my constructor. I am getting a problem where if I use a pointer to a char and set it as test.bmp I get an error stating cannot implicitly convert expression (file) of type string to char*. After that I decided to try to set file to 'test.bmp' instead, and in that case I get: Unterminated character constant . Although I am familiar with what this error is referring to, I do not know how to add a terminator in D. This is the function that I intend to use the filename in: **Note the function LoadBMP is the one that REQUIRES a pointer to a char -- SDL_Surface * Load(char * file) { SDL_Surface * Temp = null; if((Temp = SDL_LoadBMP(file)) == null) return null; Surface = SDLDisplayFormat(Temp); SDL_FreeSurface(Temp); return Surface; } This is the constructor that is giving me the error: -- char * file; this() { this.filename = test.bmp; } -
Re: Char * character and string
Thank you for the reply. However, I've run into another problem. I changed: --- char * file; this() { this.filename = test.bmp; } --- To: char * file this() { this.filename = toStringz(test.bmp); } --- I am getting this error: Error 1 Error: cannot implicitly convert expression (toStringz(test.bmp)) of type immutable(char)* to char* D:\Documents\Projects\Test\Test\DPBall.d 10 Instead I tried toUTFz, which I used like this: -- char * filename; this() { this.filename = toUTFz(test.bmp); } -- I get these errors: Error 1 Error: template std.utf.toUTFz(P,S) if (isSomeString!(S) isPointer!(P) isSomeChar!(typeof(*P.init)) is(Unqual!(typeof(*P.init)) == Unqual!(ElementEncodingType!(S))) is(immutable(Unqual!(ElementEncodingType!(S))) == ElementEncodingType!(S))) does not match any function template declaration D:\Documents\Projects\Test\Test\DPBall.d 11 Error 2 Error: template std.utf.toUTFz(P,S) if (isSomeString!(S) isPointer!(P) isSomeChar!(typeof(*P.init)) is(Unqual!(typeof(*P.init)) == Unqual!(ElementEncodingType!(S))) is(immutable(Unqual!(ElementEncodingType!(S))) == ElementEncodingType!(S))) cannot deduce template function from argument types !()(string) D:\Documents\Projects\Test\Test\DPBall.d 11 Am I using these functions incorrectly?
Re: Char * character and string
Ok, got it all sorted. Thank you for the guidance.
Re: D, Derelict2, and OpenGL
On Thursday, 23 February 2012 at 19:26:31 UTC, James Miller wrote: I find that when learning a complicated system or library, the best way is to write out the code examples, compile them, then change things until they break, fix it, then make more changes. Eventually you end up with the worst code ever known to man and a thorough understanding of the system at hand. I did it recently when figuring out that there is more to terminal emulation than just IO redirection and interpreting Terminal codes. Most of the time, you'll bang your head against your desk screaming why wont you work until you brain-damage your way into an epiphany, fix everything, achieve enlightenment, ???, PROFIT! I have followed this same pattern when I work with the UDK. Although, with that, its more about searching through source code, reading over the foundation I'm building upon and moving from there to try to implement my classes. For me, that method has been the best to learn. Along with some frustration when it doesn't go as planned. Is the documentation up-to-date on this site? So that I can search through and try to learn more about a certain library and how it could help me?
UnitTest and visual D
I am following the book The D Programming Language and am at the portion about functions and unittest. For some reason I cannot get unittest to do anything noticeable. I right clicked on my Project Properties Command Line and under additional options added -unittest (--main gave me an error saying unrecognized switch). After I compiled the code, the program ran as normal. Am I missing something? This is what I have so far: int[]find(int[] haystack, int needle) { while(haystack.length 0 haystack[0] != needle){ haystack = haystack[1 .. $]; } return haystack; } unittest { int[] a = []; assert(find(a, 5) == []); a = [ 1, 2, 3 ]; assert(find(a, 0) == []); assert(find(a, 1).length == 3); assert(find(a, 2).length == 2); assert(a[0 $ - find(a, 3).length] [ 1, 2 ]); } void main() { int[3] array = [3, 4, 5]; int needle = 4; find(array, needle); }
Re: UnitTest and visual D
Ok, thanks. I haven't run into version(...) yet. Would I be correct if I assumed that this version of void main: void main() {} would only run if -unittest was in the command line? Also, what should be in a unit test? Test cases to make sure certain functions/classes are working as you intend them to? If the unit tests pass, they don't print anything unless you add statements to them which do. You only get stuff being printed out on failure. This works particularly well for the command line (it's normal in Unix-land for stuff to print nothing on success unless them printing stuff out is their job - this makes it easier to pipe programs and the like). Some people complain about it from time to time, but that's the way it is. If you really want them to print something though, you can always add your own print statements. If you compiled with -unittest, the unit tests run before main does, so if all of your tests pass, then your program will run normally after the unit tests have been run. It's not uncommon for people to do something like this so that they can have the unit tests run without running their actual program: version(unittest) void main() {} else void main() { //Your normal main... } - Jonathan M Davis
Re: UnitTest and visual D
Thanks for the response. There are a lot of great features to D that really excites me about using this language. Unittest is definitely one of them. It's hard for me to imagine myself going back to C++ at this point because of the amount of great features in D. :)
D, Derelict2, and OpenGL
I have been reading the book The D Programming Language and am really enjoying D. However, my current motivation to use D was specifically for programming through OpenGL, and I was excited when I found out Dereict2 provided support for OpenGL. My current Gfx card can only support up to OpenGL 3.3, Can Derelict2 support up to OpenGL 3.3? Also, and most importantly, would it be possible for me to follow a book such as the Red Book to learn about using OpenGL with D? Does anyone have a recommendation for a book about OpenGL that is geared towards people new to OpenGL?
Re: D, Derelict2, and OpenGL
Hey David and Vijay, Thank you for the swift replies. It seems like this foray into D and OpenGL could be a bit overwhelming considering I would be learning D and SDL/OpenGL at the same time. So because of this, i'm going to make sure I have a solid base in D to start with. I am an Intermediate level C++ programmer, and I have used SDL/SFML/DirectX so the majority so far in the D programming book is very familiar. I however, do have a newbie Derelict2/OpenGL question. I have a basic program that simply spawns a window using SDL which I found from one of the SDL/OpenGL tuts on the derelict website. In order to use DerelictGL and DerelictSDL do I simply need to import derelict.opengl.gl and import derelict.sdl.sdl and then initialize the modules by typing DerelictSDL.load() , DerelictGL.load()? After this am I free to use SDL/OpenGL functions, like SDL_Init(...), SDL_Quit(); etc?
Re: D, Derelict2, and OpenGL
Ok, thanks for clearing that up. I am really looking forward to seeing what D and Derelict2 can offer. However, I would have liked to post this in the Derelict forums because it seems like the more appropriate place. I know that Aldacron is only one man, and I appreciate his hard work, but how long does it take to get approved to post on that forum? I read that I had to wait for moderator activation (unless I was mistaken) ? On Thursday, 23 February 2012 at 01:15:17 UTC, David wrote: Am 23.02.2012 01:20, schrieb Chris Pons: Hey David and Vijay, Thank you for the swift replies. It seems like this foray into D and OpenGL could be a bit overwhelming considering I would be learning D and SDL/OpenGL at the same time. So because of this, i'm going to make sure I have a solid base in D to start with. I am an Intermediate level C++ programmer, and I have used SDL/SFML/DirectX so the majority so far in the D programming book is very familiar. I however, do have a newbie Derelict2/OpenGL question. I have a basic program that simply spawns a window using SDL which I found from one of the SDL/OpenGL tuts on the derelict website. In order to use DerelictGL and DerelictSDL do I simply need to import derelict.opengl.gl and import derelict.sdl.sdl and then initialize the modules by typing DerelictSDL.load() , DerelictGL.load()? After this am I free to use SDL/OpenGL functions, like SDL_Init(...), SDL_Quit(); etc? No you need also do init opengl after creating the context, here's how I am (was) doing it: -- static this() { DerelictSDL.load(); DerelictGL.load(); } void main() { writefln(main); if(SDL_Init(SDL_INIT_VIDEO)) { writefln(error: SDL_INIT_VIDEO); return; } else { writefln(no error (SDL_INIT_VIDEO)); } SDL_WM_SetCaption(titel, nirgends); SDL_GL_SetAttribute(SDL_GL_BUFFER_SIZE, 16); SDL_GL_SetAttribute(SDL_GL_DEPTH_SIZE, 24); SDL_GL_SetAttribute(SDL_GL_STENCIL_SIZE, 0); SDL_GL_SetAttribute(SDL_GL_DOUBLEBUFFER, 1); //SDL_SetVideoMode(1000, 800, 32, SDL_OPENGL | SDL_RESIZABLE); SDL_SetVideoMode(1000, 800, 32, SDL_OPENGL); DerelictGL.loadModernVersions(GLVersion.GL30); DerelictGL.loadExtendedVersions(); //DerelictGL.loadExtensions(); // rendering goes here } ---
Re: D, Derelict2, and OpenGL
Ok, well it must be something wrong on my end. I have tried logging in with no result. I'll try to work it. I don't know if you are mistaken or not, but looking at the member list sorted by join date, several new members have registered recently. So if approval *is* required, it probably isn't too long. Did you try to log in? At any, rate, I (Aldacron) have nothing to do with approval of members of the forums as a whole. All I can do is moderate posts specifically in the Derelict forum.
Re: D for game Development
On Wednesday, 15 February 2012 at 15:41:02 UTC, Kiith-Sa wrote: On Wednesday, 15 February 2012 at 06:51:11 UTC, RedShift wrote: Can I use OpenGL or DirectX with D? If so, where can I find a guide to get everything setup? Derelict provides bindings for OpenGL and SDL (and many other game-related libraries) - these are used exactly the same way they are used in C/C++, so any OpenGL/SDL tutorials for C/C++ apply. Derelict has a few of its own functions that can/need to be called when initializing, described in its documentation. The current stable version of Derelict supports only OpenGL up to 2.1 and SDL 1.2, but support for OpenGL 3.0+ and SDL2 is being worked on. For the current development version, see https://github.com/aldacron/Derelict3 (Derelict moved to GitHub recently) Ok, So let me get this straight. I can use Derelict with OpenGL 3. ish, and support for 4.0 is on the way. I can also use any tutorials to learn Opengl? That is really good news.
Re: D for game Development
I am sorry about the double post. I am in the middle of trying to install derelict following this tutorial: http://h3.gd/dmedia/?n=Tutorials.SdlGlTutorial1 However, when I get to the third step I get this error: Error 1 Error: module gl is in file 'derelict\opengl\gl.d' which cannot be read D:\Documents\Projects\Test\Test\main.d 3 I am assuming this means that gl.d can not be found. However, my derelict source files are in .../dmd2/src/ext/derelict/ In my VS project under the options panel, I pointed my DMD install path to D:\Documents\Projects\DMD2 . Do I need to set the Import and Library path as well?
How to get Visual D working with Derelict2?
Hey everyone, I am new to D, and interested in using it with Derelict2 for game development. I plan on using Visual D, which I have installed already. I used the visual studio 2008 solution file to build the libraries and the .di files but unfortunately I do not know where to put these files once built or alternatively setup Visual D to recognize their location. Lastly, how would I import these libraries in the code? Such as this, simple test program: module main; import derelict.opengl.gl; //--- This doesn't work, how would I import with the //lib and .di files in the right place? import std.stdio; void main() { try { DerelictGL.load(); writefln(Successfully loaded the OpenGL shared library.); } catch (Exception e) { writefln(Could not load the OpenGL shared library.); } } Thank you for being patient with me!