TOPIC_TITLE
stringlengths 4
128
| CATEGORIES
stringlengths 13
48
| POST
stringlengths 0
85.6k
| ANSWERS
stringlengths 0
146k
|
---|---|---|---|
UINT what is the header for this | For Beginners | i have seen UINT and want to use it , but what header do i need to #includecant find it lol | Include windows.h. However, what do you want it for?Windows Data Types says that UINT is simply a typedef unsigned int UINT, so if you only want a shorter name for an unsigned integer datatype, then you can just typedef it yourself and name it whatever you want. ; UINT is just an unsigned int - it just has a different name.If you want "UINT myLargeInt;", just do this:"unsigned int myLargeInt;"UINT is a type that's defined by a number of different people. The one you probably use alot is Microsoft's.If you really like the name, 'UINT', just create a header file and add this line:"typedef unsigned int UINT;" and include it from the source files you want to use. |
HLSL Ambient Light Washes Out Texture | Graphics and GPU Programming;Programming | I've been trying to wrap my head around Pixel Shaders and I'm at a point where I understand the logistics of the code but I've run into a problem with the ambient light value. When the "AmbientLightColor" is set to anything other than black it washes out the texture of the cube where the point light is hitting the surface. The side's and back's textures don't even show up, only the ambient color that is set is visible. The shader is a Phong reflection shader using a point light source and my question is: do I need to do another pass to add ambient light or is my shader calculating incorrectly?Here is the shader code:float4 PixelShaderFunctionWithTex(VertexShaderOutput input) : COLOR0{ // Get light direction for this fragment float3 lightDir = normalize(input.WorldPos - LightPosition); // per pixel diffuse lighting // Note: Non-uniform scaling not supported float diffuseLighting = saturate(dot(input.Normal, -lightDir)); // Introduce fall-off of light intensity diffuseLighting *= (LightDistanceSquared / dot(LightPosition - input.WorldPos, LightPosition - input.WorldPos)); // Using Blinn half angle modification for perofrmance over correctness float3 h = normalize(normalize(CameraPos - input.WorldPos) - lightDir); float specLighting = pow(saturate(dot(h, input.Normal)), SpecularPower); float4 texel = tex2D(texsampler, input.TexCoords); return float4(saturate( AmbientLightColor + (texel.xyz * DiffuseColor * LightDiffuseColor * diffuseLighting * 0.6) + // Use light diffuse vector as intensity multiplier (SpecularColor * LightSpecularColor * specLighting * 0.5) // Use light specular vector as intensity multiplier ), texel.w); }Images to help explain my delima:In both images the point light is sitting right infront of the cube mesh.The first image shows the ambient light at almost white. You can see the texture doesn't shine through. In the second image the ambient light is set to dark gray (the color of the left side of the cube). You can see that when the ambient light is dark, the texture shines through but only where the point light shines on it. What I was shooting for was a bright light on the texture from the point light and the ambient light to affect the other sides that are not hit by the point light. Do I need to do another pass to add ambient light or is my shader calculating incorrectly?Thanks,Deeg | Try this:return float4(saturate((texel.xyz * ( AmbientLightColor + DiffuseColor * LightDiffuseColor * diffuseLighting ) * 0.6) + // Use light diffuse vector as intensity multiplier(SpecularColor * LightSpecularColor * specLighting * 0.5) // Use light specular vector as intensity multiplier), texel.w);; deathkrush you are the man! Thanks for your help. Now I need to understand what you've done here. You added the ambient to the diffuse before multiplying it to the pixel? Before I was adding it after my light claculations.Thanks again... |
resource allocation is initialization (RAII) | For Beginners | i currently am throwing an exception in my constructor of my class and i read that when u do such a thing, the objects destructor is never called! meaning if i allocate any memory without using the heap, i have to MANUALLY deallocate the memory myself. An article i read stated using "resource allocation is initialization" can be used to solve this problem and is a must. I'm curious if anyone could give an example or any more useful information on this topic! it's hard for me to understand and i'm not sure if i'm understanding it fully! -thx | Here's what the C++ Faq Lite has to say about it. |
Engine Selection | For Beginners | I'm trying to make a multiplayer shooter sort of like TF2, with less hats and goofy looks.Don't know what engine I should use.I'm doing this on my own so I don't really want to spend all day making every little thing. As far as technical knowledge I make CSS maps and know some some Java, thats it. Don't really want to use Source but UDK is too much for me.Any ideas? | Quote:Original post by raimondi1337I'm trying to make a multiplayer shooter sort of like TF2, with less hats and goofy looks.Don't know what engine I should use.I'm doing this on my own so I don't really want to spend all day making every little thing. As far as technical knowledge I make CSS maps and know some some Java, thats it. Don't really want to use Source but UDK is too much for me.Any ideas?Unity is pretty popular these days. ;Quote:Original post by KaptainKomunistUnity is pretty popular these days.Thanks ill check it out. |
A few general questions | For Beginners | I have a couple small questions that i didn't feel required their own topics.I am a Linux VI C programmer that is getting into opengl. Unfortunately all my friends that i want to share my programs with are on Windows. What, in your opinion, is the best way to make cross platform programs. Should i make the code compile on windows machines via #ifdef WINDOWS statements, which i really don't know what that even does, or should i just statically cross compile them?Also, for some general all around basic game programming articles, what are your favorites?I found: http://www.gamedev.net/reference/articles/article1947.asp and http://www.gamedev.net/reference/articles/article1229.asp series, are they any good, the second one seems pretty heavily windows in the first two, but i haven't looked at all of them yet.Thanks! | Quote:Original post by ChocratesI have a couple small questions that i didn't feel required their own topics.I am a Linux VI C programmer that is getting into opengl. Unfortunately all my friends that i want to share my programs with are on Windows. What, in your opinion, is the best way to make cross platform programs. Should i make the code compile on windows machines via #ifdef WINDOWS statements, which i really don't know what that even does, or should i just statically cross compile them?In your case I suggest using SDL which allows you to abstract most or even all of the platform specific stuff. Then develop on both Windows and Linux in tandem dealing with issues as they arise. ; also, you can create projects with CMake, with is a project builder that lets you create different projects(Makefile, Visual Studio solutions, etc) with the same file for all platforms ; With SDL you'll be using a few #ifdefs.Main is replaced with winmain, for example.Also, on newer Windows platforms, if you don't pump events, it'll assume the program has boned itself and may kill it.Warning! SDL 1.2, the latest stable, doesn't hardware accelerate on Windows anymore.You might use the developmental branch, depending on what your doing and your performance needs. ;Quote:Original post by JoeCooperWith SDL you'll be using a few #ifdefs.Main is replaced with winmain, for example.Also, on newer Windows platforms, if you don't pump events, it'll assume the program has boned itself and may kill it.Doesn't SDL handle all that for you? I haven't used SDL with Windows 7, but with SDL 1.2 at least, the platform-specific details you mentioned are handled automatically. Or have you found that not to be the case? ;Quote:Original post by JoeCooperAlso, on newer Windows platforms, if you don't pump events, it'll assume the program has boned itself and may kill it.Warning! SDL 1.2, the latest stable, doesn't hardware accelerate on Windows anymore.Don't know what you mean by pump, but im sure when i get to it, it wont be too hard to figure out.Any idea why they don't hardware accelerate anymore? This wont be a problem for me until i get better at it, but that seems strange that they would take it out. Did the windows api change drastically and they just haven't got it fully implemented yet?Anyways, ill look into SDL. I used it a number of years ago for a simple 2d game, at the time i thought it was a 2d graphics library, it appears i was mistaken....Thanks all |
Build step to parse source / add code | General and Gameplay Programming;Programming | I'm trying to find out how to add a build step in visual studio to run a program that parses my source for tags or something similar to generate something like script glue code. I would just google it, but I don't know what this is called.Thanks for any info :D | Depending on when you want it called, it can be done as either a pre-build step or a post-build step. The exact method of creating them depends on which version of Visual Studio you're using and which language you're using. ; I'm using visual studio 2008 and c++. I'm looking at luabind to see how they do it, so I very well may find some answers there :D ; Code generator? |
What books did developer read for game development in the 1990s? | For Beginners | I want to make a game But I wonder how game developers worked in the 1990s, how they made games, how they learning before the Internet became as widespread as it is today. etc.how do they know how to build game mechanics as character ability power up system?how they know to reverse engineering game competitor company.what book I should read? | As far as I know (not being a programmer myself), books on the subject started appearing in the early 2000s. Up to that point, it was “learn by doing” and tips from one another. ;The first book that came to mind was Tricks of the Game-Programming Gurus: Lamothe, Andre, Ratcliff, John, Tyler, Denise: 9780672305078: Amazon.com: Books, which was geared toward beginners/students/amateurs. There were others, but that's the best selling pre-2000. After that point in time, game development became a hot topic in the book publishing world. Even GameDev.net has a series - Beginning Game Programming: A GameDev.net Collection (Course Technology Cengage Learning): 9781598638059: Computer Science Books @ Amazon.com.Otherwise, in the professional realm a lot was “learn by doing” as Tom said, or through word of mouth on early Usenet/IRC/websites (pre-GameDev.net in 1999 - see About GameDev.net). ;Computers in that era didn't have an OS like we have today. The machine booted, and you were dropped in a command shell or in an interactive BASIC interpreter. You basically programmed directly at the metal. Video memory was directly accessible, by writing in a known address range you could make pixels appear at the screen in various colors. The “OS” had a corner in the memory too for its data, but nothing prevented you from poking around there. Lua, Python, C#, C++ didn't exist, ANSI-C was just invented (K&R book about that was in 1989 iirc). Assembly language of course did exist (with books) and was used.Monthly computer magazines were published for all types of home computers. Tips and tricks were exchanged in that way, also program listings were printed in those magazines that you could then enter at your own computer. Studying those listings, and trying things for yourself is how you learned. There was also technical documentation about the computer.If you want to enjoy that stuff, today there is a retro-computing movement, that lives in that era, except with slight more modern hardware but still no OS, etc.;Alberth said:Computers in that era didn't have an OS like we have today.In the 1990s there was MSDOS, Several versions of Windows, and of MacOS. And that's not all the operating systems of the nineties, most likely.Like Linux, for instance.;Tom Sloper said:Alberth said:Computers in that era didn't have an OS like we have today.In the 1990s there was MSDOS, Several versions of Windows, and of MacOS. And that's not all the operating systems of the nineties, most likely.Like Linux, for instance.Yep. There were things like Windows 95, Win 98, and at the time I was still using a Commodore Amiga (AmigaOS) .To deal with the original question “what game dev books was I reading in the 90s?” Back in that era, one of my favorites was : The Black Art of 3D Game Programming by André LaMothe. ;Abrash was the guy who did the Windows NT graphics subsystem and worked on Quake.https://www.drdobbs.com/parallel/graphics-programming-black-book/184404919 ;There are a couple of" history of video games" books, that track the rise of the medium and genre.Just google for them. ;GeneralJist said:There are a couple of" history of video games" booksThat's not what the OP is looking for.;Thanks all |
Choosing a career in AI programmer? | Games Career Development;Business | Hello everyone, my name is Ramon Diaz; I am currently studying Game development and programming at SNHU. I have taken the initiative to learn about a professional career in AI programming. I have a lot of gaps in my development in the short term. I have blueprint experience with AI but not enough to choose a career in this profession. I would like to know how I can be competitive leaving the university in 5 months after finishing my studies. I am looking for knowledge from all of you who have been in the industry for years. | Entry level? Know your algorithms, it will help you at interviews. If you have made demos it can help you get jobs, but the market is wide open right now and should be relatively easy to find work for the foreseeable future. Overall, it reads like you are on the right path. When you graduate and start looking for work, be open to any positions rather than just an AI specialty. Once you have a job it is easier to transition into whatever specialty you prefer.;Thank you. ;I would like to know how I can be competitive leaving the university in 5 months after finishing my studies.Talk about last minute. Create AI projects? Or A game with character behaviors? Pathfinding examples. Crowd movements. Anything really. Learn how navigation meshes work.;@dpadam450 Character Behavior is what I doing in the project at this moment. Everything related to AI programming.;@dpadam450 Is it the same when learning C++ in AI as visual scripting Blueprint? If I were to make a demo, what kind of programming should I focus on my attention? ;@frob It is important to have a portfolio? ;Not for programming. You will need to show you know how to do the work, but it is usually some interview questions and writing some code of their choice. If you have something you want to share with them, you can do it if you want. Having done fancy demos can sometimes help get interviews, and can help show your interest and abilities, but it is generally not needed. It does not hurt, unless you do it badly and therefore becomes a cautionary warning. Build it if you want. I have interviewed and hired bunches of programmers without portfolios. ;I'm studying AI at the moment, in terms of statistical learning. I've learned so much about AI over the past few weeks. Check out: https://hastie.su.domains/ISLR2/ISLRv2_website.pdfandMachine Learning with R: Expert techniques for predictive modeling, 3rd Edition |
Newbie desperate for advice! | Games Business and Law;Business | Hi allI'm new to the game development community and need some advice.I've created 2 educational games with a simple idea but are sufficiently challenging for all ages. These could be played on pcs or phones.Is it worth patenting any parts of the games?What would be the best way to monetize?How should I market the games? | hendrix7 said:I'm new to the game development communityReally? Your profile shows that you've been a member here since 2004, and your last activity was in 2007, asking about raycasting.hendrix7 said:Is it worth patenting any parts of the games?Probably not. Expensive and there will be hurdles, and possible lawsuits after the patent is granted (if it is).hendrix7 said:What would be the best way to monetize? How should I market the games?There are several threads here in the Business and Law forum about that. While you wait for more replies from the community, you can read up on those previous answers to those questions. Mainly, “you should have thought about that before you finished your games.” (You wouldn't be “desperate” now.) Good luck with your sales!;@hendrix7 Filing for a patent can be expensive, and you need to document the solution and how it separates from anything else. I have developed software that solved problems in a way that no other software does, but there is only a very small portion of that that can actually be patented. Even though you can file an application yourself, I would recommend hiring an experienced IP attorney. This too is very expensive, though, so you are best off doing this if this idea can provide millions in income. If it can't, then it's actually not that harmful if anybody copies it.You could look at registering trademarks, design and other parts of the games. This is cheaper, but it will protect you brand more than your idea or solution.Again, if this is something that could turn a real profit, it might be worth looking into. If not, it's a very costly waste of time.As for marketing - my day job is actually creating videos and commercials etc., so naturally that's the first thing that comes to mind.Make videos for social media or other platforms where your target audience is likely to see it. Oh, and you need to define a target audience. Know where they are, what they respond to, what their struggles are and how your product will solve their problems, enhance their life experience or in other ways contribute positively to their life.There are several other ways to do this, but the list exceeds my level of expertise in the area.;patenting is costly, and time intensive. As said above, it depends on a lot if it's worth it. ;@hendrix7 Nothing is worth patenting unless you're willing and able to defend your patent. There is no patent police; you're responsible for finding and prosecuting infrigement.What you're patenting has to be novel and non-obvious to a person skilled in the art. You called your idea ‘simple’ which makes me wonder if it's obvious or already in use.;@Tom Sloper Thanks TomI have been programming for a while but not games until now.Thanks for getting back and your advice, particularly patents.;@scott8 Thanks for your reply.I see. The play of the game utilises basic maths skills so I'm guessing it'll be difficult to identify anything that's unique. I suppose, in a similar way, it would be difficult to patent something like ‘Wordle’. Am I right? |
Hi I'm new. Unreal best option ? | For Beginners | Hallo everyone. My name is BBCblkn and I'm new on this forum. Nice to virtually meet you 🙂. One of my biggest dreams is to make my own videogame. I love writing design as in text on how my dream game would be. Now I got no skills to create it. But who knows what life will bring. Is Unreal the best program to have fun with an experience ? Obviously I prefer a simple but capable program. Not pre designed auto drop. Why not install Unreal and roam into it and see if anything happens.My favorite games are in the genre of Fantasy, usually stone age with magic. Dota, Homm, Diablo and the odd one out is the genius Starcraft 1. But I played plenty of different games, especially when I way younger. I don't game currently at all but designing gets my creative juices flowing and is so inspiring and fun. Thanks for having me guys | BBCblkn said:My name is BBCblknI am truly sorry for you. Even Elons daughter has a better name than that.BBCblkn said:Is Unreal the best program to have fun with an experience ?Give it a try, but it's not meant for total beginners.Starting small always is a good idea. 2D is easier than 3D. You could try GameMaker, learn some programming language, learn some math, move on to more advanced engines like UE or Unity… ;There's honestly no perfect program for beginners. If I had to compare Unreal though at my skill level, I would probably pick Unity. However, It really comes down to your needs, and how much programming you want to learn. Furthermore, I would also keep in mind other engines.;@BBCblkn I'd recommend Gamemaker studio 2 as a first engine. It's easy to learn and I haven't had a problem making my game ideas in it yet.There are some good tutorials on YouTube to follow to learn it. Do note you'll be limited to 2D games with GMS2.Bit late to the post, but I hope it helps;gamechfo said:Bit late to the postTwo months late. Always consider whether you honestly believe that a question asked long in the past is still awaiting an answer. Thread locked. |
How to publish a book? | GDNet Lounge;Community | Hello, So, over the holidays I finished my 1st book. Do any of yall writer types know where I can find:an editorpublisherIt's like 99% done, just need to know what to do next. Also, it's cross genre, so it doesn't necessarily fit the standard model. | You've given nowhere near enough information to get a final answer, but I can suggest next steps for you. (For background, I've worked as an author, co-author, editor, and ghostwriter on 9 books so far.)Publishing is a business deal. You need to figure out what business services you need.Do you even need a publisher? Do you need a distributor? You already mention needing an editor. Do you need marketing? Do you need retail agreements? Digital or physical? If physical, POD or offset, how many each of hard or soft, what size of print run can you afford? What business services do you need? Publishers have an awful lot of potential features of what they can provide and what those services cost.Once you know the list of services you actually need, your favorite bookstore will have books that have listings of all the major publishers and hundreds of minor publishers, along with the services they provide and the specialties they work with. Work through the listings methodically, and talk to them all until you've got a deal. You'll also want to start shopping around for a lawyer at that point, both because they have connections and because they'll be working with the contracts you'll be signing.Once you know what you need and have talked with your lawyer the first few times, you will be ready to start shopping around. It's far better if you have more money and are using the publisher as a paid service. That is, you pay them for the services they provide up front. It will cost you many thousand dollars but you'll require far fewer sales to reach profitability. It can be better to do an online plus POD service starting out if you're self funded. If they need to front any of the money there will be two phases to the deal, one phase before it's profitable and another after a threshold is reached and it's profitable. The exact terms will depend on your needs and the services they'll be providing. Before you sign with anyone, you'll need to work back and forth more than once with your lawyer to help you negotiate what's fair in the agreement. Good lawyers understand the costs of the various services and can help you get fair rates.Just like publishing games, the more you need from them the harder your pitch becomes. If you need a lot of services the more it will cost you. If you're looking for them to invest in you, front you money, and pay for the books, don't expect a lot of money from the deal, and in addition your pitch needs to be amazing and you'll be rejected many times. If you've got the money to self-publish and are only looking for retail agreements that's rather easy. ;hmmmWell Self publish might work too. I'm looking for:an editor publishing distribution for ebookNo hard cover or physical book planned at this timemaking cover art. Future Audio book production. I think that's it. I'd be willing to do physical print if needed, but I don't really want to pay for that at this time. frob said:You've given nowhere near enough information to get a final answer The issue is I don't know what questions or criteria I should be asking or looking for. ;Have you considered publishing with Packt?https://www.packtpub.com/;GeneralJist said:2. publishing distribution for ebook 3. No hard cover or physical book planned at this timeFor distribution of an ebook there are plenty of options. Amazon is the biggest with kindle direct publishing requiring little more than an html file and an image for the title. If you are comfortable with software tools you can use that same document to build/compile every other format out there. You're on the hook for everything else with the business if you go that route, but it can work well if you are marketing through your own channels.There are many ebook publishers out there targeting specific platforms and specific readers or specific genres. I mentioned publisher lists, they also include electronic-only publishers. Understand the tools they use against piracy are also helpful since otherwise anybody with access to the file can make unlimited copies.Be careful of contracts, you almost certainly want something that has a non-exclusive agreement since you've done all the work yourself already. If a publisher wants an exclusive deal they need to be putting quite a lot on the negotiating table.GeneralJist said:4. making cover art.Find an artist with the style you like and contact them. Often it's in the range of a couple hundred bucks, especially for ‘unknown’ artists when they're starting with something that wouldn't have seen the light of day otherwise. Artist friends are best, and asking around at local art schools is inexpensive.GeneralJist said:5. Future Audio book production.If you don't need it now, it's something easily done later.GeneralJist said:1. an editorThis one is the most difficult. Skilled editors are amazing. If you go with a publishing house they'll provide professional editors, at professional rates. ;taby said:Have you considered publishing with Packt?https://www.packtpub.com/hmmm 1st time hearing of them.Looks like they are more of an educational option?My book is a mix of mental health journey auto bio, and Sci Fi elements. It's not really a standard “how to” for game dev. ;so I just heard back from my 1st publisher submission.https://triggerhub.org/And they essentially say they be willing to look at it deeper, and have extensive edits to focus on the mental health angle. but they would want me to cut a lot. From what they are hinting at, It sounds like they want to cut a lot of the Game dev and gaming journey, as they are a publisher focused on mental health.So, now I need to decide what to do.I sent them back an email saying I'm open to continued dialogue.Without knowing exactly what they want to cut, and edit, I don't know how to proceed.Also, would it be better to hold out, and find a publisher that is willing to accept most of the game dev journey, as I'm looking for a continued publisher to work with, aka accept most of the book as is. Any advice would be helpful.Thanks yall. ;GeneralJist said:Any advice would be helpful.Look into your own mind and heart.;hmmmok,So I've submitted to a few other places.We shall see.I submitted to this place called author House, and they got back to me really quick, but it looks like they want me to pay a couple thousand for a package:https://www.authorhouse.com/en/catalog/black-and-white-packagesI personally find that a bit frustrating.I mean, really, I wrote the book, I thought traditional publishers get paid from a % of sales?@frobWhat do you think?Is the above package a good deal?I was also a little put off, as it seems the person who called me didn't even read anything about my book, and asked me “so what's your book about?"beyond the above, how does this usually work? Edit: so, after a bit of basic research, it seems the above organization is a bit scamy. The hunt continues. ;You're unlikely to get a publisher deal, where the publisher pays you an advance and distributes your book to retail outlets.You'll have to self-publish, meaning you have to bear all the costs for printing, and nobody will distribute it for you. https://en.wikipedia.org/wiki/Vanity_press |
First-person terrain navigation frustum clipping problem | General and Gameplay Programming;Programming | I am trying to develop first-person terrain navigation. I am able to read a terrain and render it as well as to move around the terrain by interpolating the location of the camera every time I move around. The main problem I have is that depending on the terrain, i.e. moving on a sloping terrain, the near plane clips my view (see below). What is the best way to avoid this? Presumably, I can interpolate the heights for the bottom corners of the near plane … any help would be appreciated. | I believe this can aways be an issue. I mean if you are clipping to a near plane and that plane passes through geometry, it has to do something. That being said you technically don't have to clip to a near plane at all, however many graphics APIs require it. Another other thing to consider is once you have collision working, you can put your camera, including your near clipping plane inside a collidable object, for instance a sphere, such that this problem will never occur. If you are eventually going to make this a real first-person game, that should take care of the problem since your camera will be inside the players head. Even in a 3rd person game you can put them inside a floating sphere. ;Gnollrunner said:That being said you technically don't have to clip to a near plane at all, however many graphics APIs require it.The near clip plane is always needed, even if you use a software rasterizer. If you don't do the clipping, vertices would flip behind the camera, causing glitches way worse than what we get from clipping.mllobera said:What is the best way to avoid this? Presumably, I can interpolate the heights for the bottom corners of the near plane … any help would be appreciated.Yes, basically you want to ensure that the camera is in empty space (above the hightmap), not in solid space (below the heightmap).But in general you can not treat the camera as a simple point, because the front clip plane requires a distance larger than zero. So ideally you build a sphere around the camera which bounds the front clip rectangle of the frustum, and then you make sure the sphere is entirely in empty space, for example. In the specific case of your terrain not having too steep slopes however, it should work well enough to sample height below camera, add some ‘character height’, and place the camera there. That's pretty simple and usually good enough for terrain.It's quite a difficult problem mainly for 3rd person games in levels made from architecture. It's difficult to project the camera out of solid space in ways so the motion still feels smooth and predictable.Some games additionally fade out geometry which is too close, attempting to minimize the issue.Imo, the ‘true’ solution to the problem would be to let the clipping happen, but rendering the interior volume of the geometry as sliced by the clipping plane.That's pretty hard with modern rendering, which usually lacks a definition of solid or empty space. But it was easy to do in the days of Doom / Quake software rendering. When i did such engine, it was possible to render clipped solid walls in simple black color. This felt really robust and not glitchy, so while it does not solve all related problems, i wonder why no game ever did this. ;@undefinedJoeJ said:The near clip plane is always needed, even if you use a software rasterizer. If you don't do the clipping, vertices would flip behind the camera, causing glitches way worse than what we get from clipping.You can clip to a pyramid instead of a frustum. I used to do this many years ago on old hardware. So there is no near clipping plane. In fact you don't need a far clipping plane either.Edit: Just wanted to add as far as I know the near and far clipping planes mostly have to do with optimizing your Z resolution. If you are dealing with that in other ways, I think they aren't strictly necessary. I currently don't even deal with the far plane and let LOD solve Z-fighting issues.;Gnollrunner said:You can clip to a pyramid instead of a frustum.I see. You still have front clip. It is a point, formed indirectly as the intersection of the other other frustum planes.I've misunderstood your claim to be ‘you don't need a front clip’. But you didn't say say that. Sorry. But now i'm curious about the experience with z precision you have had. I guess it just worked? Which then would probably mean: All those painful compromises of ‘make front plane distant so you get acceptable depth precision for large scenes’, are a result of a bad convention being used by APIs?Or did you use no z-Buffer? ;@undefined My whole engine is based on aggressive LOD and culling. I don't do projection in the matrix. It's a post step. My Z coordinates are world distances. My current project does have a near clipping plane mainly because DirectX wants one, but it's not that relevant for my application.;Ah, so you use the pyramid for culling only. But for rasterization, the usual front clip plane at some distance i guess.Still an interesting question if ‘some distance’ is really needed, but i guess yes.I did some experiment about point splatting. It uses spherical projection, which is simple than planar projection:auto WorldToScreen = [&](Vec4 w){Vec4 local = camera.inverseWorld * w;if (local[2] < .1f) return (Vec3(-1)); // <- front clip at some distance of 0.1Vec3 screen = (Vec3&)local;screen[2] = length(screen); // if it was zero, i'd get NaN herescreen[0] = (1 + screen[0] / (screen[2] * camera.fov)) / 2;screen[1] = (1 + screen[1] / (screen[2] * camera.fov)) / 2;return screen;}; Planar projection would cause division by zero too, i guess.;Thanks for all your comments! I will need to investigate how to do what Gnollrunner proposed (about putting the camera inside of a sphere). ;This may be obvious, but in case it helps:Let me note that, as a first-person camera may be more likely than a third-person camera to draw very close to geometry, it likely makes some sense to have a smaller near-plane distance for the former than the latter.Now, this only ameliorates the problem, it doesn't remove it entirely: it means that the problem will still appear, but only if the player gets very close indeed to a surface. It's intended to be used in conjunction with one or another means of preventing the camera from approaching quite so near to a surface (such as the sphere-approach mentioned by others above).;Thaumaturge said:This may be obvious, but in case it helps:Let me note that, as a first-person camera may be more likely than a third-person camera to draw very close to geometry, I'm not sure that's so true. I mean in both cases you have to take care of the problem somehow. The case of a first-person camera is a bit easier because it should always be in the collision boundary of the player (sphere(s), ellipsoid, capsule etc.). As along as the near plane is also within that boundary, the problem should never occur. So if you have a 10cm radius sphere and put the camera in the back of it, that gives you maybe a 10 to 15 cm camera to near clipping plane distance to play with depending on the field of view you are going for. With a 3rd person camera, you can also get very close to terrain, in fact your camera can end up within terrain or some object if you don't do anything to solve that problem, and this will happen very often without separate camera collision. One typical way to handle this is just implement your following camera, ignoring terrain considerations. Then to figure out your camera's actual position, project a line back from the head of the avatar to the camera's ostensible position, and see if it intersects anything to get the camera's true position. In reality you should project a cylinder and not a line since your camera will need its own bounding sphere to contain the near clipping plane. In any case this means that as you move around your camera can jump forward to clear terrain and objects. I've seen this in a few MMOs. However, when you leave blocking terrain you have the option of implementing smooth movement back to the cameras desired location. If you want to get really fancy, I guess you could try to predict when your camera will need to jump forward ahead of time and try to do smooth moment forward too. Maybe you can have a second camera bounding sphere which is somewhat larger, that would trigger smooth movement, but I think you would still need a fallback camera jump routine to be safe. |
Mesh access without DirectX | Graphics and GPU Programming;Programming | I am setting up my server and I do not use DirectX on it (performance issues),I access the mesh for use with PhysX as follows, I wonder whether we can do this without using DirectX:///////////////////////////////////////////////////////// Generate(cooking) a convex physics object from a DX mesh///////////////////////////////////////////////////////void PhysicsLevel::cookingMesh(ID3DXMesh* Mesh, NxVec3 pos){typedef struct {D3DXVECTOR3 VertexPos;D3DXVECTOR3 Normal;D3DXVECTOR2 TexCoord;} Mesh_FVF;//Used to copy indicestypedef struct {short IBNumber[3];} IndexBufferStruct;int NumVerticies = Mesh->GetNumVertices();int NumTriangles = Mesh->GetNumFaces();DWORD FVFSize = D3DXGetFVFVertexSize(Mesh->GetFVF());//Create pointer for verticesNxVec3* verts = new NxVec3[NumVerticies];char *DXMeshPtr;Mesh->LockVertexBuffer(D3DLOCK_READONLY, (void**)&DXMeshPtr);for(int i = 0; i < NumVerticies; i++){Mesh_FVF *DXMeshFVF = (Mesh_FVF*)DXMeshPtr;verts = NxVec3(DXMeshFVF->VertexPos.x, DXMeshFVF->VertexPos.y, DXMeshFVF->VertexPos.z);DXMeshPtr += FVFSize;}Mesh->UnlockVertexBuffer();//Create pointer for indicesIndexBufferStruct *tris = new IndexBufferStruct[NumTriangles];IndexBufferStruct *DXMeshIBPtr;Mesh->LockIndexBuffer(D3DLOCK_READONLY, (void**)&DXMeshIBPtr);for(int NumInd = 0; NumInd < NumTriangles; NumInd++){tris[NumInd].IBNumber[0] = DXMeshIBPtr[NumInd].IBNumber[0];tris[NumInd].IBNumber[1] = DXMeshIBPtr[NumInd].IBNumber[1];tris[NumInd].IBNumber[2] = DXMeshIBPtr[NumInd].IBNumber[2];}Mesh->UnlockIndexBuffer();// Build physical modelNxTriangleMeshDesc TriMeshDesc;TriMeshDesc.numVertices = NumVerticies;TriMeshDesc.numTriangles = NumTriangles;TriMeshDesc.pointStrideBytes = sizeof(NxVec3);TriMeshDesc.triangleStrideBytes = 3*sizeof(short);TriMeshDesc.points = verts;TriMeshDesc.triangles = tris;TriMeshDesc.flags = NX_MF_16_BIT_INDICES;NxTriangleMeshShapeDesc ShapeDesc;ShapeDesc.group=GROUP_COLLIDABLE_NON_PUSHABLE;if(0){// Cooking from filebool status = NxCookTriangleMesh(TriMeshDesc, UserStream("c:\\tmp.bin", false));ShapeDesc.meshData = m_PhysicsSDK->createTriangleMesh(UserStream("c:\\tmp.bin", true));}else{// Cooking from memoryMemoryWriteBuffer buf;bool status = NxCookTriangleMesh(TriMeshDesc, buf);ShapeDesc.meshData = m_PhysicsSDK->createTriangleMesh(MemoryReadBuffer(buf.data));}NxActorDesc actorDesc;actorDesc.shapes.pushBack(&ShapeDesc);actorDesc.globalPose.t = pos;PhysXLevel = m_Scene->createActor(actorDesc);PhysXLevel->userData = (void*)1;PhysXLevel->raiseBodyFlag(NX_BF_KINEMATIC);delete[] verts;delete[] tris;} | |
XNA 4: Enable/Disable mipmaps on the backbuffer? | Graphics and GPU Programming;Programming | How do you enable/disable mipmaps on the backbuffer?You enable/disable mipmaps on a RenderTarget2D when you create it. But the creation of the backbuffer is buried somewhere in the framework....you never create it, you just draw to with SetRenderTarget(null). So how do I enable/disable mipmaps if I'm drawing directly to the backbuffer?THANKS | Mipmaps are a per texture setting.The reason you can set them on rendertargets is that you can use rendertargets as textures.You can't use the backbuffer as texture directly (in XNA at least) so you can't set mipmapping on it.To enable/disable mipmapping on your textured models you need to change the settings on a per texture/texture sampler basis. |
[HLSL] [DX11] 3D texture trilinear interpolation | Graphics and GPU Programming;Programming | Hi all, I'm playing with a compute-shader-implemented raycaster right now and have some questions on trilinear interpolation. First, I know a lot of hardware supports trilinear interpolation, and I'm using a sampler state which includes D3D11_FILTER_MIN_MAG_MIP_LINEAR in the sampler desc. The result, however, does not look very interpolated. Zoomed out, you can't really tell:But you get closer and can see very stark edges, which are usually the product of no interpolation.So i tried to do manual trilinear interpolation in hlsl, and ended up with an even worse result:The code i'm using is:float TrilinearInterpolatedSample( float3 SampleUVW ){// find closest actual voxels (g_vDim is the size of the volume, delta is 1/g_vDim)float3 negdelta = floor(SampleUVW*g_vDim)*delta;float3 posdelta = ceil(SampleUVW*g_vDim)*delta;// get the cornersfloat3 c000 = SampleUVW + float3(negdelta.x,negdelta.y,negdelta.z);float3 c001 = SampleUVW + float3(negdelta.x,negdelta.y,posdelta.z);float3 c010 = SampleUVW + float3(negdelta.x,posdelta.y,negdelta.z);float3 c011 = SampleUVW + float3(negdelta.x,posdelta.y,posdelta.z);float3 c100 = SampleUVW + float3(posdelta.x,negdelta.y,negdelta.z);float3 c101 = SampleUVW + float3(posdelta.x,negdelta.y,posdelta.z);float3 c110 = SampleUVW + float3(posdelta.x,posdelta.y,negdelta.z);float3 c111 = SampleUVW + float3(posdelta.x,posdelta.y,posdelta.z);float3 weights = frac(SampleUVW*g_vDim);float trilinearTaps[] = {t3dVolume.SampleLevel(samLinear,c000,0),t3dVolume.SampleLevel(samLinear,c001,0),t3dVolume.SampleLevel(samLinear,c010,0),t3dVolume.SampleLevel(samLinear,c011,0),t3dVolume.SampleLevel(samLinear,c100,0),t3dVolume.SampleLevel(samLinear,c101,0),t3dVolume.SampleLevel(samLinear,c110,0),t3dVolume.SampleLevel(samLinear,c111,0)};float result =lerp(lerp(lerp(trilinearTaps[0],trilinearTaps[1],weights.z),lerp(trilinearTaps[2],trilinearTaps[3],weights.z),weights.y),lerp(lerp(trilinearTaps[4],trilinearTaps[5],weights.z),lerp(trilinearTaps[6],trilinearTaps[7],weights.z),weights.y),weights.x);return result;}So my questions are:Am I correctly using hardware interpolation in the first screenshots? If so, why am i still getting these artifacts?Can anyone tell me why I'm getting such a bad result with the manual interpolation? What am i doing wrong here? Thanks! | Basically linear filtering works is it un-normalizes your texture coordinate (converts to the range [0, TexSize]) and uses the fractional portion of X and Y to determine how much to lerp with between the texel and the next texel over. So if you pick your coordinates such that they always hit exactly on a texel, your results are going to look exactly like point filtering. Same goes for mip interpolation...using a mip level of 0 means you're always going to sample only the largest mip level. ; The errors in your second image look to me more like precision problems. My guess is depth precision areas. You may have to tighten up your frustum, or make some change to maintain higher precision values. There are a number of resource available on how to improve this. There's one on shadows from a GameDev magazine a few months back. Your picture has artifacts almost exactly like theirs. ;Quote:Original post by MJPBasically linear filtering works is it un-normalizes your texture coordinate (converts to the range [0, TexSize]) and uses the fractional portion of X and Y to determine how much to lerp with between the texel and the next texel over. So if you pick your coordinates such that they always hit exactly on a texel, your results are going to look exactly like point filtering. Yea that's what I was trying to implement with the manual function. I pick the texel and use frac() to find the fractional portions, an interpolate with those weights.If hardware already does interpolation this way, then why am I getting those edges? Shouldn't the interpolation guarantee a smooth sample and not these slices in between?;Quote:Original post by DieterVWThe errors in your second image look to me more like precision problems. My guess is depth precision areas. You may have to tighten up your frustum, or make some change to maintain higher precision values. There are a number of resource available on how to improve this. There's one on shadows from a GameDev magazine a few months back. Your picture has artifacts almost exactly like theirs.I'll try to find that resource, thanks! ; Found the article you mentioned, DieterVW. "Rendering geometries at the near clip plane is analogous to rolling a coin along a razor's edge; the coin can drop down both sides easily." This makes sense, interpolation precision can only go so far.Tried upping the precision by using doubles, but that made things go EXTREMELY slow (ATI 5870 here) and didn't even improve the result. Texture3D::SampleLevel takes as input a float, so in passing the higher-precision sample location, it gets casted to a float. I suppose this is as good as it will get, which isn't bad at all (unless i get the manual trilinear interpolation working with doubles, in which case I'd be glad to share the code for anyone in need of high-precision interpolation).Any ideas as far as why the manual trilinear interpolation function is giving me such wrong results? ; The fix won't be converting to doubles. Though doubles do provide more precision, they still have the same problem and as you've noted, it's pretty damn slow. Also, most graphics hardware flushes float32 denorms to zero, though I doubt that is the problem here.Read: A Matter of PrecisionOne of the Game Programming Gems books has a solution. I don't have my books on me but it should be one or more of the following. You can probably modify their solution for your needs if it comes to that.GameGems4 : Solving Accuracy Problems in Large World CoordinatesGameGems6 : Geographic Grid Registration of Game ObjectsGameGems7 : Using Projective Space to Improve Precision of Geometric Computations |
FAST Way of checking whether sprites are on screen, near each other... | General and Gameplay Programming;Programming | Hello,are there any ways you can check sprites, for example if they are on screen or if they are near each other? I'm currently doing it like this:void CSceneGame::SetItemsOnScreen(void){for( map<int, int>::iterator ii=m_ItemsAvailable.begin(); ii!=m_ItemsAvailable.end();++ii){int i = m_ItemsAvailable[ii->first];if(m_Collision->Collision(-256, 0, 1536, 768, m_Items[ii->first].Sprite())){m_ItemsOnScreen[ii->first] = 1;}else{m_ItemsOnScreen.erase(ii->first);}}}To explain some (maybe a bit) confusing parts: m_ItemsAvailable is an array storing the IDs of all Items that aren't already deleted (for some purpose I'm doing kinda "soft-delete". The other parts should be mostly clear. Whenever the screen moved, I iterate through all available Items, colliding their sprites position with a slightly bigger screen), and eigther adding their ID to the m_ItemsOnScreen-Map or deleting it.So, are there any faster ways than that? It seems a bit odd.. I've always got to check all Items, no matter if they are 20000 pixels away or in the middle of the screen and won't out-move the screen in the near time.. I quess the way I do it would be accurate if I only had Items, but.. I've got tiles (currently, going to change that), enemys, obstacles, .. , so that means a lot of iterating and collision-detection.. Any Ideas how to do that in a faster way? Next point is the determination whether objects like enemys are near each other. Thats my current code for that:void CSceneGame::GetEnemysInRange(void){map<int, int> TempEnemys;TempEnemys = GetEnemySprites();map<int, int> TempEnemys2;TempEnemys2 = GetEnemySprites(); CSprite *Sprite;for(map<int, int>::iterator ii=TempEnemys.begin(); ii!=TempEnemys.end(); ++ii){TempEnemys2.erase(ii->first);Sprite = GetEnemySprite(ii->first);for(map<int, int>::iterator jj=TempEnemys2.begin(); jj!=TempEnemys2.end(); ++jj){if(m_Collision->Collision(Sprite->GetPosition().x - 16, Sprite->GetPosition().y - 16, Sprite->GetWidth() + 48, Sprite->GetHeight() + 48, GetEnemySprite(jj->first))){m_EnemysInRange[ii->first][jj->first] = true;m_EnemysInRange[jj->first][ii->first] = true;}}}}So, that's where things are really getting ugly and I could need some "wonder-method". Because, actually I'm checking each and every enemy against each other. And thats just insane, imagine 100 enemys, that would be 10000 loop-runs, each consisting of a collison-check. I've made some improvements, so that no enemys are unneccesarly checked twice, but that doesn't seem to be enough. I get huge lags if there are 100 enemys on the screen. It's as bad that somehow having this check slows the game down, even if I use the values for the collision-check of the enemys. The code works nice for the player, simply because there are not that many checks, and the actual detection for a collision with anything can sometimes be executed 6 times (because I use some ray-casting-thing).Long explanation, but short question: Is there any way to make do that in a simplier and/or faster way?Last thing, what about the code for collision-detection itself? Maybe there are some possibilities of improvements here? I quess that would all be some small optimizations, but as that method is the most-called in my code, I wonder if that wouldn't give me at least some ms less to process.bool CCollision::Collision(CSprite *Sprite1, CSprite *Sprite2){int left1, left2; int right1, right2; int top1, top2; int bottom1, bottom2;left1 = Sprite1->GetPosition().x; left2 = Sprite2->GetPosition().x; right1 = Sprite1->GetPosition().x + Sprite1->GetWidth(); right2 = Sprite2->GetPosition().x + Sprite2->GetWidth(); top1 = Sprite1->GetPosition().y; top2 = Sprite2->GetPosition().y; bottom1 = Sprite1->GetPosition().y + Sprite1->GetHeight(); bottom2 = Sprite2->GetPosition().y + Sprite2->GetHeight(); if (bottom1 < top2) return false; if (top1 > bottom2) return false; if (right1 < left2) return false; if (left1 > right2) return false; return true;}Well, I hope someone got some solutions/ideas here. PLS do not tell me about Quad-Trees, I already know about that and am going to implent it sometimes, but first of all I want that the existing code works better.. | Ok, so think about this. You're doing a spatial check for collisions, right?(space based)... How would you optimize this? Well the easiest way is by pruning unneeded checks right? I mean why do N^2 checks when you only need to do a very small set of checks?The key to optimizing this is doing higher level spatial checks to allow you to intelligently not check things that could not possibly be intersecting. Why not use QuadTrees? What is your aversion to this VERY simple solution?If you're to not use QuadTrees you will need to think up your own hierarchical spatial checking algorithm that will prune unnecessary checks (e.g. bounding circle hierarchy or something, but that could be harder than just using QuadTrees, depending on your application/requirements).Essentially a quadtree check is just asking if two items are in the same quad, if they are go one level deeper to the 4 sub quads and ask if these items are still in the same quad (etc) down to the lowest level check that makes sense. It's really easy! Don't let it scare you, just go for it!EDIT: FYI: In one of my GBA homebrew apps I just checked the Hero character against all enemies on the screen, wasn't slow at all, but not that many enemies at a time (10 at most). If I checked all enemies against one another brute force? Well, this might suffer.[Edited by - RazzleGames on November 17, 2010 5:42:13 PM]; The other thing I noticed here is you hinted at checking against all tiles with all items. Well if you have the states of the items as being within a certain tile, and the previous state (tile before) you shouldn't even need a spatial hierarchy for those checks (if I understand your requirements correctly). The exception would be if the map tiles were moving around and all that, then QuadTrees might be the best solution (but if you have a map structure at index[N] that just goes from being TILE1=don't care to TILE2=COLLISION_STUFF, then checking is still just a map structure check, even with moving tiles. No need for Quadtree). I mean you can easily know what tile the item/character/etc is intersecting by knowing it's screen coordinates. Most tile systems are a set size (e.g. 8 pixel by 8 pixel tiles), you just do some mod math to find out which tile the item intersects based on the map space coords of the item (screen space to map space coordinate conversion). Of course I can see quad trees handling most of this for you also, but anyhow... either way keep the state from the previous frame. This way you know what to do when you find a collision.Let me know if this makes sense.[Edited by - RazzleGames on November 17, 2010 6:34:42 PM];Quote:Original post by The King2To explain some (maybe a bit) confusing parts: m_ItemsAvailable is an array storing the IDs of all Items that aren't already deletedEh? I don't see an array; I see a std::map. What do the keys represent, and what do the values represent? ; @RazzleGames: Thanks a lot, you gave me some very constructive points. Well, let's go into detail:Quote:The key to optimizing this is doing higher level spatial checks to allow you to intelligently not check things that could not possibly be intersecting.Ok, well the point that I found kinda disturbing here was that to get less checks, you need to do other checks first. I already did so, for example determaining if objects are on screen (Thats like a quad-tree but without any childs, just the first parent is checked to determine if objects are on screen). But for anything else I would need to do a lot of other if-statement-checks.. seemed to me like I was doing something wrong oOQuote:Why not use QuadTrees? What is your aversion to this VERY simple solution?Uhm... its some facts that irritated me about that. But now from reading a tutorial on gamedev.net I think I figured it out.. The main problem was that despite of but anyway, I don't see any certain use of "real" quadtrees here. I think I go better with a custom algorythm. I already came up with another idea, could this work?DON'T READ THAT; except you want to see how hardly you can fail; see next post for an expansion of that idea that should really work.To compare this to the original idea of quadtrees, I'm coming up with an example, having 100 Enemys on the screen at timeSo bascially, before checking the enemys for collisions with each other, I would do some Kinda-like-quadtree-thing. I would split the screen into 4 areas, but instead of checking in which part of the screen a certain enemy lies, I check WHERE all the enemys lie. I sort that values so they are set in any form of container, representing the four parts of the screen. I do the check using the screen-parts position (0|0 for the first, 512|0 for the second) and the coordinate of the enemys sprite in a quite complicated way I came up with, but I think it should work fine. Some brief explainations:I devide the sprites x and y position seperatly without remainder through the screen-parts sizes. That values tell me in which screen part the sprite is (636|200 through screen parts size 512 | 384 should give me back 1 | 0 -> sprite is in upper right sprite part for resolution 1024*768). I also do that again, first adding the sprites size (for the case the sprite is in multiple parts. The results are stored in a map<xID, map<yID, vector<EnemyID>> which I work on.So, here, that would be 100 "checks" (i don't check a damn thing, just math!) in total. Let's say in every screens area there are exactly 25 sprites. So I would now go on quartering the remaining screen parts using the map from before (empty parts aren't used further), doing the check again, but with some modified conditions. The logic coordinates of the sprites are stored, and modified depending on which part of the screen they are in (posx - 512; posy - 0 for the upper right part of the screen). Now I do exactly the same as before, but with the new values for screen parts positions (0|0, 256|0, 512|0 , ..) and size (256|192). Our example from before: Position 636|200 in Screen Part 1 | 0 would now logically be 124|192. Devide it through screen parts size will give me 0 | 0 for the new child screen part position. Add the parent position 1*4 | 0*4 would give me position 4*4 (so its in the 5th screen part from left and 1st from aboth). Storing these values in a temporary map, similar to the first one, and using this new map further on will now follow (or maybe a copy to the original map if I find a quick way to do so). Again, 100 "checks".That will now go on another 2 or 3 times. The number of "checks" will stay constantly at 100 per time, which is a good value compared checking 100 enemys against each of themself (10000 REAL checks would follow).At the end I got a map, containing pairs of enemy-ids that are in the same "leaf". When doing the actual enemys collision detection, I search for the screen-leafes in which the enemy appears, and can now easily collide only the enemys that are on the same part of the screen. I might even store any collisions between enemys so I don't have to collide enemys twice( remember, I'm iterating through my map<> of enemys. if enemy 1 collides with enemy 20 than logically enemy 20 also collides with enemy 1).Soo.. what do you think about this? I hope it is somehow clear and not too long.. Do you think that could work or will be fast? I't somewhat theoretically, actuall I'm sure I know how to implement that but I don't have access to a pc with a compiler right now.I've got to go, but I'm going to respond to the rest of the answers to that topic later..[Edited by - The King2 on November 18, 2010 10:34:26 AM]; Gosh, sports can sometimes make you really creativ - I just found out that my idea from the last post was kinda redundant. The principal was right, but the actual version should work less complicated:I devide the screen into "cols" and "rows" with a certain size (I think I'm going to choose 32*32), so no f**king around with quartering the screen anymore. Next, I iterate through all the sprites of my enemys that are on screen. I devide the sprites coordinates through the width and height of the fields without remainders (638|200 should return now 19 and 6 -> sprite is at field (19|6)). I than add the ID of the sprite to a map<xID, map<yID, vector<EnemyID>>. Now I devide the width and height of the sprite through the size of the fields, the value I get from that calculation tells me how many additional fields the sprite is at and I add the sprites ID to that fields. After the iteration, I go once through the whole map, deleting all fields where only one enemy is on. So, here is another question: How is that done the best way? Do I need to iterata using a loop again or is there any command or "trick" to allocate map<> with size 1 inside another map? After each iterate, if the field hasn't been deleted, I handle field x/y to the enemys that are on it. While colission detection, I only need to go through the fields that are shared, which shouldn't be very much, too.So, that should do it here. I haven't had the possibility to built it or test it out, but that looks just so promising (except I made some logical mistake) and so damn fast.. there seems to be as less checks as possible while collision detection and the algorythm itself appears to be very fast. Appears to be no need for a quad-tree anymore. Well, I'll try it out as soon as I come home. Ok, let's move on:Quote:}The other thing I noticed here is you hinted at checking against all tiles with all items. Well if you have the states of the items as being within a certain tile, and the previous state (tile before) you shouldn't even need a spatial hierarchy for those checks (if I understand your requirements correctly).Won't work properly, as my objects are moving with non-static speed, they can move 1 pixel, but also 2.5, and so on.. to align my objects to the ground flawless (I've seen many *bad* games having an issue that the characters are always 1-2 pixels above the ground, isn't destroying the gameplay but looks ugly) I can't simply use the last state before the collision, because that could be 2-3 pixels away from the ground. I don't really see any other possibilies to spatial checking.[qoute]The exception would be if the map tiles were moving around and all that, then QuadTrees might be the best solution (but if you have a map structure at index[N] that just goes from being TILE1=don't care to TILE2=COLLISION_STUFF, then checking is still just a map structure check, even with moving tiles. No need for Quadtree).I mean you can easily know what tile the item/character/etc is intersecting by knowing it's screen coordinates. Most tile systems are a set size (e.g. 8 pixel by 8 pixel tiles), you just do some mod math to find out which tile the item intersects based on the map space coords of the item (screen space to map space coordinate conversion).[/qoute]Hm, I need to anyway rebuild my tile system. I currently used a flexible one where the tiles are represented by sprites, which is somewhat not really usefull. I did that because working with some smw-rom-editor the tiles seemed to behave the same way.. but i think the performance on "standard"-methods is better, so i gotta take a look at some other systems for that.Eh? I don't see an array; I see a std::map. What do the keys represent, and what do the values represent?@Zahlman:Quote:Eh? I don't see an array; I see a std::map. What do the keys represent, and what do the values represent?Oh, sry, std::map was what i meant.. the first int represents the ID of an item refering to its position in the vector m_Items (so, m_Items[ii->first] will access the item). The second has not much use yet, but might be useful later on for setting certain states to special items on the screen. ; What you're describing sounds like a grid. Whether or not that's the best data structure to use depends on the situation.For a small number of items, checking every item in the list is just fine as long as it's fast enough for your needs.But search time increases linearly as the number of items increases, so that doesn't scale well. If you're working with more items than the naive approach can handle, you'll need something better. So, let's divide the scene into a grid and store references to items in grid cells. Determining which cells to check is a quick check that reduces the number of items to check by a certain factor.There's a few caveats, though: you'll need to filter duplicate references (due to items that overlap multiple cells), which adds overhead. So choose the cell-size wisely: if it's too fine, you'll have a lot of duplicate checking to do, but if it's too large, you won't be able to cull as many items.Also, some cells may be empty, while others may be overpopulated. So sometimes you're wasting parts of your grid on empty cells, and sometimes you'll still be checking a lot of items that could have been culled.If items are spread irregularly across the scene, a quadtree may be better. It's essentially a hierarchy of grids. It's like dividing overcrowded cells into smaller cells - so cells themselves can also contain grids. You'll have few cells in sparsely populated areas, but more in areas where items are clustering together. Each layer adds an additional check, but can reduce the number of items to check by yet another factor.Again, which structure works best for you depends on the situation. Personally, I would hide the actual implementation under a well-defined interface. Say, a class that supports the following functions:- getItemsInArea(rectangle)- addItem(item)- removeItem(item)- updateItem(item)A SimpleList class could use a simple container under the hood - so adding an item adds it to a list, and getItemsInArea would iterate over all items in that list.A Grid class could store item references in a 2D list of cells, so it's getItemsInArea function only has to check the content of the cells that touch the given area.A Quadtree class would do something similar, except that it can call the getItemsInArea function recursively on it's child nodes until all items have been found.Variations on the above or totally different data structures could still adhere to the above interface.You can then easily swap the data structure for another and see how that affects performance. Be sure to make them configurable - for the grid, you should be able to specify the size of the world and the cell-size. For the quadtree, the world size and the number of items at which a node should split into child-nodes. ;Quote:Original post by The King2Won't work properly, as my objects are moving with non-static speed, they can move 1 pixel, but also 2.5, and so on.. to align my objects to the ground flawless (I've seen many *bad* games having an issue that the characters are always 1-2 pixels above the ground, isn't destroying the gameplay but looks ugly) I can't simply use the last state before the collision, because that could be 2-3 pixels away from the ground. I don't really see any other possibilies to spatial checking.I still have to parse through the rest of your posts, but this (before and after state tracking) should not be discounted. I am fairly sure most sprites don't move one pixel at a time ;). This is not an issue though, but some care is needed. Let's say you're sprite is on one side of a "wall tile", next frame it's on the other side. You check the path of the sprite given it's before and after position and if it was supposed to be able to pass through that "wall tile" that it clearly passed through.Also think of this: You have two very fast moving sprites that are on a collision course, one frame they are heading towards each other, the next they have skipped over each other. What should you do? Well you should detect the collision and correct the sprite/character states, that's what ;)No amount of Quadtrees or spatial checks will grab this one, you have to know if the paths crossed given the before and after states. But: Spatial checks will help you prune the amount of "path intersection" tests.(I exaggerate slightly, since this issue will only come about if your sprite can potentially move faster than a collision box per frame. Or, well 1/2-ish a collision box per frame if they are headed straight for each other). ; @Captain P:Ok, I think I get what you want to tell me, but..There are some important facts unclear to me. Quote:So, let's divide the scene into a grid and store references to items in grid cells. Determining which cells to check is a quick check that reduces the number of items to check by a certain factor.Yeah, thats basically the way I do it right now. But determining to check what? If you mean what cells, or their items, to use for collision-detection, I'm already doing this. Or do you mean something else?Thats the code I use right now btw. I quess it won't be clear at all, but it should show the basic functionality:void CSceneGame::GetEnemyFields(void){map<int, int> TempEnemys;TempEnemys = GetEnemySprites();int FieldX;int FieldY;int WidthF;int HeightF;for(map<int, int>::iterator ii=TempEnemys.begin(); ii!=TempEnemys.end(); ++ii){FieldX = GetEnemySprite(ii->first)->GetPosition().x / 32 + 1;FieldY = GetEnemySprite(ii->first)->GetPosition().y / 32 + 1;WidthF = GetEnemySprite(ii->first)->GetWidth() / 32;HeightF = GetEnemySprite(ii->first)->GetHeight() / 32;m_EnemyFields[FieldX][FieldY].push_back(ii->first);m_Enemys[ii->first].AddField(FieldX, FieldY);while(WidthF > 0){m_EnemyFields[FieldX + WidthF][FieldY].push_back(ii->first);WidthF--;m_Enemys[ii->first].AddField(FieldX, FieldY);}while(HeightF > 0){m_EnemyFields[FieldX][FieldY + HeightF].push_back(ii->first);HeightF--;m_Enemys[ii->first].AddField(FieldX, FieldY);}}}So, I store all grids that are used (I use standard values of 32 in the code right now) containing the Enemy IDs on it into the earlier described map. I also handle the coordinates of every Cell each enemy is in them, and use that values later on during the collision detection to get the IDs of the other enemys that are on the same grid.Quote:There's a few caveats, though: you'll need to filter duplicate references (due to items that overlap multiple cells), which adds overhead. So choose the cell-size wisely: if it's too fine, you'll have a lot of duplicate checking to do, but if it's too large, you won't be able to cull as many items.Items overlapping multiple cells shouldn't be a problem, or, at least nothing that I have to filter.. right? I think the only thing to filter is when 2 items are sharing more than 1 cell. Did you mean that? Plus, whats the way to check a map for duplicates with the most performance? There must be something better than just iterating through the whole map..Well, using the code above has made a big improve on to the performance. While I wasn't able to display more than 40 enemys on the screen at the same time without FPS slipping down to <30 FPS from 60, I can now have about ~200 fully functional enemys walking around at the same time at the screen, while my FPS only drop to 50. The code isn't totally finished yet, it might eigther improve or get worse.. but I thinkt here is still a huge space for improvements.The main problem that I'm facing is that every frame, I have to determine the cell of every enemy AGAIN. Thats due to the fact that nearly every enemy on the screen is constantly moving. Can you give me a hint what to do here? I run the function GetEnemyFields() again every frame, and it is always running through the same algorythm, determining the grid-position of the enemy. Isn't there any faster way to determine if an enemy moved and move him to the new grid if he left the last one he was at? It can't figure out how I could simply MOVE the enemy inside of the 32*32-sized grid instead of DETERMINING the grid every frame..I mean, the grid and quad-tree-thing would work so nice for static objects (for example for tiles) but as far as more than half of the objects move around every frame, things get ugly.. - getItemsInArea(rectangle)[/source]Ehm, I wonder where I could use that thing? I wouldn't need to check a rectangular area, because I tell every enemy which grid(s) he on and then find out if there are enemy on that grids and if yes, what enemys that are. So it seems like my method is even more valid and having a better performance, because at least I only have to check the grid position of all enemys on screen 1 time and then everything works mostly on its own. Or am I mistaken?@RazzleGames:Ah, I get it. Actually I think I'm already doing this in a certain type.. I'm doing the collision detection before the sprites are actually moved, so I use the position (before?) and check the collision adding the speed (after?). Then I'm recursivly reducing the move speed 1 px per step as long as there is still a collision. Thats done first for x-movement until there is no collision, and then for added x (now correctet within the first check) and y-movement - that might occour strange at first but I came to the conclusion that adding the modified x-movement to the second check for the vertical movement would help avoiding some issues.Err, I know thats not exactly what you meant. But as you see I would be able to do what you submitted easily without much modification. But nah, objects are never moving more than a bounding-box. Ah yeah, when I said 1 px I meant per FRAME, not per SECOND, because thats the way my game is handling it. So said at a average bounding-box size of 32*54 I highly doubt that any of my objects moves more than 960 px per second xD I think that would be more an issue if I was making a sonic than a mario game.; Hey I have a few questions for ya: 1) Are you just checking collisions with?: Hero - EnemyHero - TilesEnemy - Tiles(So mainly I am asking, are you doing enemy - enemy collisions?)2) Why all the map structures and such? Is there some compelling reason for a hash like structure? I may have missed some details, I will have to reread, but I am a bit confused as to why that added complexity is needed.Why not just use a dynamic array to fill with screen objects (e.g. std::vector etc)?I am not trying to stifle creative coding, just curious. |
Timer over multiple thread | For Beginners | Say I would like to time the total time taken for each of my boost thread. Can I safely use a timer class in each thread to record the time?? Or would such a scenario occur:1.thread A run, start timer2.midway, the OS reschedule thread A and start thread B3.thread B completes4.thread A resume5.thread A finishes but the timer gave the wrong timing since it didn't account for the time where the OS paused itwould such a problem occur?? if so, is there anyway to poll the correct time taken for each thread?regards | If you use GetThreadTimes() (if you're on Windows) then you won't have that problem. ; hmm thanks for the replies. But I would like to work on other platform other than windows too. Maybe something that is compatible with boost threads, since I am using boost threads |
[.net] Call internal Method on a structure | General and Gameplay Programming;Programming | Hi!I'm trying to call an internal method in a structure - but without generating any garbage. The internal method modifies the structure, so I want to avoid copying the structure around.The problem is that I've got zero experience with MSIL and never used IlGenerator.Emit() before. This is what the method I'm trying to call looks like:public enum TouchLocationState { Pressed, Moved, Released };public struct TouchCollection { internal void AddTouchLocation(int id, TouchLocationState state);}and this is my attempt at calling it:private delegate void DynamicMethodDelegate( ref TouchCollection touchCollection, int id, TouchLocationState state);void test() { Type byrefTouchCollection = typeof(TouchCollection).MakeByRefType(); var dynamicMethod = new DynamicMethod( "AddTouchLocation", null, new Type[] { byrefTouchCollection, typeof(int), typeof(TouchLocationState) } ); MethodInfo addTouchLocationMethod = typeof(TouchCollection).GetMethod( "AddTouchLocation", BindingFlags.Instance | BindingFlags.NonPublic ); ILGenerator ilGenerator = dynamicMethod.GetILGenerator(); ilGenerator.Emit(OpCodes.Ldarg_1); // thisptr ilGenerator.Emit(OpCodes.Ldarg_2); // id ilGenerator.Emit(OpCodes.Ldarg_3); // state ilGenerator.EmitCall(OpCodes.Call, addTouchLocationMethod, null); ilGenerator.Emit(OpCodes.Ret); DynamicMethodDelegate addTouchLocationDelegate = (DynamicMethodDelegate)dynamicMethod.CreateDelegate( typeof(DynamicMethodDelegate) );}The result is a VerificationException with the message "Operation could destabilize the runtime."I think it's most likely that I did something wrong with the this pointer (which I passed by reference so the structure isn't copied). I'm not even sure how the OpCodes.Call gets the this pointer (I came up with this code by looking at a plain method call in reflector).Can anyone fix my probably stupid mistake? ;) | I have never tried to use IL to call methods on structs, it is easy for reference types, but things get a little weird when you start working with non-primitive value types. There is some interesting discussion here (stackoverflow) that might help you, the second answer looks pretty relevant. ; For instance methods, "this" is loaded via ldarg_0, not ldarg_1.I think the method AddTouchLocation should be static and accepting an explicit ref param - forcing a "this" byref into an instance method feels like looking for troubles. I also seem to recall that unbound delegates should perform faster than their instance counterparts, but it's totally speculative. |
Point on a 3D line at a specific Z coordinate | Math and Physics;Programming | Hey guys, I have a 3D line defined by two points. I need some way to find the X and Y coordinates of the line at a specific Z coordinate. I am pretty sure this isnt very hard I am just being retarted and need a few pointers. Any ideas? | If your two points are (x0, y0, z0) and (x1, y1, z1), and you want to find (x, y, z) for a given z, then you simply do:x = x0 + (x1 - x0) * (z - z0) / (z1 - z0)y = y0 + (y1 - y0) * (z - z0) / (z1 - z0)It works since (z - z0) / (z1 - z0) is the relative distance from z0 to z compared to the distance from z0 to z1.So for x, you start at x0 and add the distance to x1 multiplied by how large percentage of that distance you need to move to reach z. ; Thanks works great. |
Need 3d artist for mmorpg game | Old Archive;Archive | Team name:Putrid Panda, just a working name until we can come up with something better.Project name: Untitled, want your input.Brief description:A third person/first person? MMORPG (we will see about the MM part) that has been in development for about 6 months. Its still in the early stages but most of the early early foundation work has been already done.We are not aiming to compete with WoW or anything stupid like that. We are just adding small things to it now and then and then will see how far with can take it technology wise.Target aim:Cash shop business model.Compensation:We are inviting you to be part of the permanent team. And hopefully we can become good friends. Whatever profits we get will be divided equally. We have no 'NDA' or anything like that, feel free to build your portfolio up using the game's models.Technology:In house built engine using mostly free middleware. RakNet (network) is the only library so far that has any license cost and that is only when a company is earning above a certain amount (much more than the actual license cost).The engine uses OpenGL and is being programmed in C++.Has basic working collision, animation, flexible collidable camera system which supports first person too. Plays videos and much more. Server is already under development and has advanced security checks, chat, logging on and authentication. Working on server collision, and mysql database integration in the near future.Talent needed:We need 1 person only, maybe 2 max.We need a 3d modeller who can also draw (optional). We also need some GUI designs and possibly website designs. We need someone who can speak English well.Team structure:Currently its just a programmer and my real life friend (Modeller/Artist) working on it casually.I have been programming for about 4 years, know C++, OpenGL, DirectX10+11 pretty well.The artist is still learning and needs some guidance.We are based in London, UK.We are very friendly people and communicate via msn or teamspeak/ventrillo at times and ofcourse in real life.Website:No website, not rushing things.Contacts:PM me in this [email protected] <- my email.Previous Work by Team:None.Additional Info:Some screenshots: (These are very early screenshots which do not represent the final quality in any way, they are pretty much shaderless)Feedback:ANY | bump, still looking for 3d artist/gui designer ; Looks nice, keep the good work!BTW, is there some port for linux? ; Linux port is not planned but who knows.I recently added a networking system which resembles the source engine networking model.Collision has been moved to server side to avoid any kind of sneaky hacks.Working very smoothly so far, working on some extrapolation in case of dropped packets.Each entity in the game world makes appropriate sounds/footsteps sounds based on distance/impact.-Still looking for 3D modeller/concept artist/gui artist. Preferably all in one package :) ; I'd like to help, I've just finished a 3.5 year project on 2 games + server intergration for an online casino. Full 3D interactive custom engine. I'm also building my own engine, much like your own. I'm taking a break from coding and would love to help out with any 3D modeling animation etc.;Quote:Original post by mixmasterI'd like to help, I've just finished a 3.5 year project on 2 games + server intergration for an online casino. Full 3D interactive custom engine. I'm also building my own engine, much like your own. I'm taking a break from coding and would love to help out with any 3D modeling animation etc.sounds great, sent you a pm.; Still looking so bump |
Float packing | Graphics and GPU Programming;Programming | Most of my data are in the [-2, 2] range, such as pixel 154 109 -0.007666 -0.002736 0.032422 0.508851pixel 154 110 0.060688 -0.113596 0.179429 0.849869pixel 154 111 -0.138292 -0.330974 0.462604 1.451673...So it's convenient to renormalize the data to [0,1] and store in RGBA texture.But I can't do that because about 10% of the data have large signed values in at least one channel:pixel 164 119 2846.726463 -0.197024 0.378962 0.904985pixel 96 103 -0.112487 128469.656514 -212368.296140 1.364759I estimate the bounds are [-250000, 250000], though other sets of data may change.I am willing to devote four bytes instead of one to represent each float, hence creating more textures.I thought of using integer math. But to accommodate for the large signed values, the float part will have small precision.Also there is that convert to base 256 method. Not sure how that copes with large values.Any ideas? Must I use hdr format? | You can store the floats in any number of formats. It depends on your needs: what you are using it for? Storing normals? Colors?How much of that range [-250000, 250000] is actually covered. How many components do you need to store? one, two, three, or four? Your best bet is to get to work :P Start testing different formats and see the results. ;Quote:Original post by smasherprogYou can store the floats in any number of formats. It depends on your needs: what you are using it for? Storing normals? Colors?How much of that range [-250000, 250000] is actually covered. How many components do you need to store? one, two, three, or four? Your best bet is to get to work :P Start testing different formats and see the results.Those are test function parameters to brdfs, so I must store all of them.90% are within [-2,2]. So anything above that would appear as outliers if the data is graphed.Maybe I should try RGBE, though for the pixels where there is much dynamic range in between the channels, the accuracy would tank I assume? And in pixel shaders, especially for old cards, is pow() or exp() very expensive as part of decoding process? ; get the max of the 3 channelsmaxVal=max(abs(c.r),max(abs(c.g),abs(c.b)));normalize them by this valuec=c/maxVal;encode those 3 as bytesout.rgb=c*0.5f+0.5f;store the power of two exponent of maxval in alphaout.a = log(maxVal)/log(2.f);reconstruction should bec = (in.rgb*2.f-1.f)*pow(2.f,in.a);just an idea, didn't validate it (and there is quite some room for optimization).; Half-precision floats only have a range of +/-65K, but they are otherwise exactly what you want. Here are a couple of 32->16->32 bit converters:http://stackoverflow.com/questions/1659440/32-bit-to-16-bit-floating-point-conversion/3542975#3542975http://cellperformance.beyond3d.com/articles/2006/07/update-19-july-06-added.html |
Battery - Old School Space Shooter in Flash | Your Announcements;Community | game test 0.6again pretty serious core modificationSU wavesboss! | Level 1 is too easy, level 2 is grossly unfair (you cannot dodge bullets because the hitbox is huge). ;game test 0.7rainbow bonusnew enemies imagesplankton ; The hitbox remains far too large compared to the bullet patterns in level 2.Moreover, the ship is slower than in the previous version, making dodging even harder. ;Quote:Original post by LorenzoGattiThe hitbox remains far too large compared to the bullet patterns in level 2.Moreover, the ship is slower than in the previous version, making dodging even harder.thank you for the commentbut are you sure you mean a hitbox of a round bullet of the boss and not the boss itself?a hitbox of a round bullet of the waves are really very close to it's actual shape ; "Hitbox" has a very narrow meaning in shoot'em up design: the part of the player's craft that can be hit by enemy bullets and obstacles, usually a rectangle.With the sort of tight bullet patterns featured in level 2, the normal choice is reducing the hitbox to a small portion in the middle of the ship (usually the cockpit); the player is expected to weave between bullet streams that pass above the wings of the ship.Alternatively, the player's ship can be fast enough and the curtain fire zones small enough to allow dodging on a much coarser scale (flying away from bullets into empty screen areas without being trapped).Of course, you do neither: the ship is too large to dodge individual bullets, too slow to run away, and too weakly armed to shoot down enough bullets and clear a path (which would be boring anyway). ; Basically he meansYOURSHIP oooooooooooooYOURSHIPYOURSHIP oooooooooooooYour ship, can't fit through the middle of those beams of bullets, nor can it go around it... maybe cuz of boundaries, or another layer of bullets. ; Great game. :) Love the graphics. It will be even better with weapon upgrades etc.Thought about making submittable high scores? ;game test 0.8plankton lives!new images almost for all objectsseparate params for each ufo wavelevel label animationsuper weapons![Edited by - MseMseM on September 12, 2010 6:57:32 PM];game test 0.9bats!upgraded behavior of the Bossmachine gun of the Bossnew space backgroundsnow superweapons stay foreverlifebarlifeslevel refactoringnot flyable through decorationshey, the number is closing to 1.0there is not so far till release and selling the gamebut with continue work on improving the gamei am ready to share revenue with a good artist or ActionScript coder |
Artist and Programmer for Oldschool Space Shooter in Flash | Old Archive;Archive | Team name:M77 EntertainmentProject name: BATTERYBrief description:we seriosly plan to make the bast 2D space scrolling shooteractually we have plans the game is only for 70% just a game but for 30% a collection of interesting graphical objects with procedural animation (graphical demos that are harmoniously built into decorations)the complete game is gonna look like ">this.Target aim:we create it because of joy but we think about money toothe game test with dirty (made by me) graphics is here.the old Java version (in all directions tinier but FINISHED) is available here.as a proof that we are ready to finish the projectwe are gonna release the first minimum but complete version in the end of Augustthen we are gonna sale it for about 500$then we plan to continue developing and selling new versions for a bigger moneyCompensation. Talent needed:are you interested in collaboration as an artist or designer or AS programmer for interest (like we) and % from the future gain?Technology:Flash, ActionScript, FlexTeam structure:We are 4:I (the one who actively works on the game every day) - a strong programmerthe guy from Australia - a good programmer, excellent knowledge of Flash, before joining the project has been done 2 space shooters2 artists with (by now) very low performanceWebsite:Battery - Space Shooting GameContacts:[email protected][Edited by - MseMseM on August 29, 2010 4:54:33 AM] | game test 0.5 is out:another serious core modificationintro screenscorescombo scores for defeated wavespeed optimization based on collide targetingall images has been refactored by me ; Your demo was a lot of fun, keep up the great work! ;game test 0.6again pretty serious core modificationSU wavesboss! ;game test 0.7rainbow bonusnew enemies imagesplankton ;game test 0.8plankton lives!new images almost for all objectsseparate params for each ufo wavelevel label animationsuper weapons! ;game test 0.9bats!upgraded behavior of the Bossmachine gun of the Bossnew space backgroundsnow superweapons stay foreverlifebarlifeslevel refactoringnot flyable through decorationshey, the number is closing to 1.0there is not so far till release and selling the gamebut with continue work on improving the gamei am ready to share revenue with a good artist or ActionScript coder ;Battery 0.91dragon-snake!the new upgraded images for almost all objectsno more - strict old school pixel arttotaly different mechanics of level genrationmany small bugfixes and changes ;Battery 0.92The new cosmos background.The flying stars.The asteroid shower.Background music!!!.;Battery 0.93main menunew backgrounda new way of level creationthe unit heli is backthe now explosions fade and are more like 3dsound effectspausecredits screenhigh score table |
Collision detection and response Routine | Math and Physics;Programming | Hi.I am having a hard time with the routine of checking collisions and then response to it. What i have is a basic FPS-game with camera as the player.in psuedo-code i would like it to be like this:A -> Check if the player can move where it wants to go. (lastSafePosition to new ocation)If Nothing is hit then moveIf something is hit A Check Intersectionpoint and move player there B Give new velocity vector C Check everything again recursivly with the new velocity vector.But i have a hard time of getting this to work. What i have now is:Vector3 GetClosestPointOnTriangle(mPos,a,b,c);float length_to_closest = (mPos-closest).length;i have a global D3dXVECTOR3 that is my move vector.When pressing 'W' the movevector get a certain velocity and the camera moves.But i don´t know how to break it down so that i check the collision routine BEFORE i move the player?My problem now is if i set MIN_DISTANCE_TO_WALLS = 1, i always end up with smaller distance than 1 due to speed.With my method now i am getting closer to the wall then i should because i lack of intersection point and not checking recursivly.What is the best approach for:A, you want to move hereB, check if you can and to recursive stuffC, based on the result move or don´t moveBecuase of everything i happening in a loop i have trouble with this problem. | A very simplistic approach would be to consider the time it takes for each movement.Given a time-slice DT for movement:New Position = old position + velocity*DTIf nothing is hit, done.If something is hitA Check Intersectionpoint and move player there. DT -= time_to_intersectionB Give new velocity vectorC Check everything again recursivly with the new velocity vector and revised DT.; Hi, and thanks for your answer, this is what i have got now. But i can´t solve the intersection point clearly. My function is recursive and returns a velocity vector after checking all triangles for collision. If hit then slide och check the new position and velocity again. If too many recursions then just stop, set velocity to (0,0,0).But i end up to close and i think this is beacuse i don´t move the sphere close with a small distance to spare from radius before sliding. When i slide i am allready to close to triangle. This is what ive got so far.It is the middle part that is the problem. Any suggestions?//This function clips the velicity and give a new slide velocity if we hit any triangle.D3DXVECTOR3 Collide(const D3DXVECTOR3 &position, const D3DXVECTOR3 &velocity, const float radius, const int recursionDepth){//if we test too many times, we are in a corner or some tricky place, just stop (this is the problem)if (recursionDepth==0) return D3DXVECTOR3(0,0,0);//Find out where the position is after the player moved with the velocity that is given.D3DXVECTOR3 new_pos = position+velocity;//The length to closest point on ANY triangle in the world.float distance = D3DXVec3Length(&(new_pos-ClosestPtPointAllTriangle(new_pos)));/*DbgPrintf(distance);DbgPrintf(recursionDepth);*///if length is over radius of sphere then just return the velocity, the player is free to move. otherwise, send player off with new velocity//that is the "sliding" velocity.if (distance>radius){return velocity;}//We have a hit somewherefloat veryCloseDistance = 0.05f;//DbgPrintf(recursionDepth);float delta = radius - distance;float velocityLength = D3DXVec3Length(&velocity);//cut_percent = how much we must cut velocity so we don´t overshoot our radius.float cut_percent = delta / velocityLength;//Check how much margin we have.float collision_distance = D3DXVec3Length(&(velocity * cut_percent));DbgPrintf(collision_distance);////if player not as close as veryCloseDistance, we have to move player closer without braking radius.if (collision_distance >= veryCloseDistance){//This is the part i don´t solve, i always end up to tight to sliding plane.D3DXVECTOR3 dir = velocity;D3DXVec3Normalize(&dir,&dir);D3DXVECTOR3 newPos = position + dir * (collision_distance - veryCloseDistance);D3DXVECTOR3 closest_point = ClosestPtPointAllTriangle(newPos);D3DXVECTOR3 n = (newPos - closest_point);D3DXVec3Normalize(&n,&n);D3DXVECTOR3 newVelocity = newPos;newVelocity = (n * (D3DXVec3Dot(&newVelocity,&n)));return Collide(newPos,newVelocity,radius,recursionDepth-1);}//v -= n * (v . n)D3DXVECTOR3 closest_point = ClosestPtPointAllTriangle(position);D3DXVECTOR3 n = (position - closest_point);D3DXVec3Normalize(&n,&n);D3DXVECTOR3 newVelocity = velocity;newVelocity -= (n * (D3DXVec3Dot(&velocity,&n)));return Collide(position,newVelocity,radius,recursionDepth-1);}[Edited by - Meshboy on November 19, 2010 5:06:41 PM]; First, it would help tremendously if you would use [code][/code] or [source][/source] tags and format your code. See the faq.I didn't look through your code for the math aspects (it's a bit difficult to look at unformatted code, I'm afraid). However, it appears you didn't read my previous post.D3DXVECTOR3 new_pos = position+velocity;Unless you're setting some small velocity related to the update time, that line tests for a position one second later. Does it help your results if you use a smaller time increment?; i think i need to know the intersectionpoint before i move my sphere.If it intersencts then set it exactly close to plane minus the radius (and a small value).Either i use ray tracing or some sweep test, but thats my problem.I don´t really know the best way of testing if my sphere is going to intersect and at what point.I think if i can solve that and move my sphere close then my problems would be solved. (of course something else will come up in the end though! =) |
modifying created mesh | Graphics and GPU Programming;Programming | Hello,I am using MDX9 for my final project, and I have a problem I would like to have an option to edit created meshes, right now I am using it's build-in mesh types, like polygon, box etc. What I would like to do, is to be able to edit for instance a polygon and change its shapes by changing each point position, I am not quite sure how it can be done, maybe I could use Mesh.IndexBuffer, to get all the indices which sounds quite reasonable but, how I will be sure which one I am editing. I don't want to make another 3d editor, but I want to have the basic functions for editing them.The other problem I have is it possible to instead of using multiple lights and be sure that something is lighted up properly, light up whole scene? I am making live video mapping application, and on every mesh i will be streaming different video, so i was wondering if i can make the whole scene lighted up?thanks! | First, I'm not familiar with MDX. However, one general approach to editing existing meshes is to "pick" one or more faces of the mesh. That's most often done by creating ray and ray direction vectors using the screen position where the mouse is clicked.Another approach is to draw the mesh and then draw points at each of the mesh vertex positions. The user can draw a select rectangle around a vertex or vertices to select them for dragging or editing in some other fashion.MDX should have some support functions for testing intersections of a ray with a mesh, and for projecting vertex positions and unprojecting screen positions.That should give you some terms to search for, either in the MDX documenation or with google. ; Thanks, I managed to modify mesh by creating customvertex from mesh, and then put the modyfied data back to mesh, still didn't figure out how to catch right verticles from screen cords public Mesh getVerticles(Mesh mesh) { verts =(CustomVertex.PositionNormalColored[])mesh.VertexBuffer.Lock(0,typeof(CustomVertex.PositionNormalColored),LockFlags.None,mesh.NumberVertices); verts[2].X = 2.0f; // example mesh.VertexBuffer.SetData(verts, 0, LockFlags.None); return mesh; }; Modifying the mesh vertices themselves is how its done. Good job.With regard to selecting a particular face or vertex, that's usually done by getting user input via the mouse - by clicking on a face or dragging a rectangle around one or more vertices on-screen.Perhaps someone more familiar with MDX can provide more information, but you'll have to learn about picking, unprojecting mouse positions and projecting vertex positions. You can google or search this site for information on "picking," "unproject mouse" and "project world position" to get an idea of the principles that are involved. ; Hey,thanks, it helped me to find the right topic, I got it kind of working but I have some strange problemsthat's the code that does the job public IntersectInformation[] unprojectMouse(int x, int y) { Vector3 near = new Vector3((float)x,(float)y,0); Vector3 far = new Vector3((float)x, (float)y, 1); near.Unproject(this._device.Viewport, this._device.Transform.Projection, this._device.Transform.View, this._device.Transform.World); far.Unproject(this._device.Viewport, this._device.Transform.Projection, this._device.Transform.View, this._device.Transform.World); IntersectInformation[] ii = new IntersectInformation[MeshList.Count]; foreach (MeshView mesh in MeshList) { mesh.mesh.Intersect(near, far, out ii); } return ii; }but in the foreach section, which iterates through all meshes, it only returns intersection with the mesh that is last in the collection, for ex. i have 2 polygons named polygon1 and polygon2, and it returns intersection of the second one only, when i add the second one to the collection first, and then second, if catches the other one, I hope my explanation was understandable... anybody know what the heck is going on there? ; Did you forget to provide an index to the info you wanted filled in? Something like:int idx = 0;foreach (MeshView mesh in MeshList){ mesh.mesh.Intersect(near, far, out ii[idx]); idx++;}; Hey,thats not a issue I changed this one but it doesn't matter I belive the problem is somewhere else, because intersect returns true/false if it intersects or no, and in this case it return false, what's even more strange, when i am creating meshes they are initialy at 0,0,0 i have a function so i can move the meshes around scene, when i move them on sides, and i click the one on the one that was added last and it returns true, for all 3. its mind blowing why is thatthis is the code i changedpublic int unprojectMouse(int x, int y) { Vector3 near = new Vector3((float)x,(float)y,0); Vector3 far = new Vector3((float)x, (float)y, 1); bool ret = false; near.Unproject(this._device.Viewport, this._device.Transform.Projection, this._device.Transform.View, this._device.Transform.World); far.Unproject(this._device.Viewport, this._device.Transform.Projection, this._device.Transform.View, this._device.Transform.World); far.Subtract(near); int idx=0; ii = new IntersectInformation[MeshList.Count]; foreach (MeshView mesh in MeshList) { ret = mesh.mesh.Intersect(near,far, out ii[idx++]); if (ret) { MessageBox.Show(mesh.meshName); } } return -1; }for moving the meshes i have something like this its in the MeshView class, which trough i am iterating with the foreach public void DrawMe() { device.Transform.World = Matrix.Translation(this._positionXYZ); this._mesh.DrawSubset(0); }; I realize English is probably your second language, but your posts are very difficult to read. When describing a technical issue or asking a technical question, perhaps using a few more periods and appropriate captital letters here and there would help.Try using the mesh transform instead of the device's world transform to unproject your near/far vectors. Consider what unprojecting does: your mesh vertices are located at the origin, but draw to the screen using a transform. When you click on the screen, that position is interpreted as being at that translated world position. To do the intersection, the vectors created for the mouse position need to be translated back to the origin where testing of the intersections is done. ;Quote:Original post by BuckeyeI realize English is probably your second language, but your posts are very difficult to read. When describing a technical issue or asking a technical question, perhaps using a few more periods and appropriate captital letters here and there would help.no doubts about that :), sorry... I will try harder :)Quote:Try using the mesh transform instead of the device's world transform to unproject your near/far vectors. I tought that world transform is the right way for positioning meshes, other thing is that Mesh class does not have any method for what are you talking about, I could convert it to customvertex and from there change all vertices position by some value, is this what you mean?Quote:Consider what unprojecting does: your mesh vertices are located at the origin, but draw to the screen using a transform. When you click on the screen, that position is interpreted as being at that translated world position. To do the intersection, the vectors created for the mouse position need to be translated back to the origin where testing of the intersections is done.I understand what you mean, but I tought that when I make a transformation to the world matrix, it is kind of saved in the device.transform.world... because if this would not be true, I would not be able to position all the meshes separately, I belive you are right, it's my first MDX project and all the 3D transformations and thinking in 3 dimensions makes me dizzy; I checked the thing about transform.matrix, and once I make the change to the matrix, the change is there so when I am unprojecting far, and near vector it has the changed world matrix, so I guess It should work fine, as the unproject is working in the same world matrix[Edited by - azjata on November 19, 2010 3:35:46 PM] |
[win32] WM_SETTEXT doesn't work? | For Beginners | Hi, I am using an edit control made with:HWND myEdit = CreateWindow(WC_EDIT,"1.0",ES_RIGHT|WS_BORDER|WS_VISIBLE|WS_CHILD,140,400,100,20,window,0,0,0);However, if I send a WM_SETTEXT message:SendMessage(myEdit,WM_SETTEXT,0,(LPARAM)"testing");It changes the text properly.... until I actually click the textbox, then it reverts back to 1.0.What is going on? | I can't duplicate the problem with just the info you posted. Can you post your parent window creation code and in what context you create the child and where you send the message? ; Ahh, I figured it out. I was calling the SendMessage right after the edit control was created. I am guessing that it has some kind of an internal WM_SETTEXT that gets sent only the first time it gets focus. ;Quote:I am guessing that it has some kind of an internal WM_SETTEXT that gets sent only the first time it gets focus.I don't think so. But if it's working, don't fix what ain't broke, I guess.FYI, the following code works for me with either SendMessage position.myEdit = CreateWindow(WC_EDIT,"1.0",ES_RIGHT|WS_BORDER|WS_VISIBLE|WS_CHILD,140,400,100,20,hWnd,0,0,0);SendMessage(myEdit,WM_SETTEXT,0,(LPARAM)"sample");ShowWindow(hWnd, nCmdShow);UpdateWindow(hWnd);//SendMessage(myEdit,WM_SETTEXT,0,(LPARAM)"sample"); |
(C++) Memory leak in pathfinding code. | General and Gameplay Programming;Programming | Code located here: http://paste.bradleygill.com/index.php?paste_id=65293I modified this from a homework assignment I had awhile ago, which was... based on some pseudocode from a Peter Norvig textbook and I'm inclined to think it was written with a garbage collected language in mind.Anyway, in terms of outward behavior, it seems to work correctly, but I have a sizable memory leak thanks to passing in new Node(toCopy) objects to the Node constructor for the parent argument. Normally I'd just put in a destructor that delete the Node* parent objects in each Node; however doing that sort of causes the deletion to cascade upwards, wiping out the path I'm trying to generate.Additionally deleting the parent pointers later while I generate a path from the goal node, while apparently possible, is sort of fruitless since I don't catch all the nodes that are otherwise never used in the goal path.So, any ideas? I was thinking of flagging Nodes that point to parents used by the path so that they wouldn't their parents but I'm not sure how to do that or if it's even the right course of action. | Why are you generating new nodes? you can't run more than 1 A* at a time, typically, so just have one fixed set of nodes each with a parent pointer. While pathfinding, just set the pointers. At the end you reconstruct a path by back iterating the parent links and stuffing pointers into a std::vector or some other dynamic container and pass that to the AI that's going to do the path following. When that entity is done, they just deallocate the container of pointers (not the nodes themselves). You definitely don't need to copy the entire node, that's wasteful.-me ; Okay so I have to admit I didn't entirely understand your solution. I still generate new nodes for the priority queue since I'm not really sure how to get around that. Anyway, it did give me an idea, though. Instead of generate new nodes and passing those to the parent pointer, I just copy expanded nodes from the priority queue to a stable structure (in this case a list), pop them, and pass the stored Nodes from the list as arguments to the parent pointer.http://paste.bradleygill.com/index.php?paste_id=65318Anyway it's not leaking as badly but it's still leaking and now I'm really not sure why since I believe I got rid of every explicit new statement.[Edited by - MeshGearFox on November 19, 2010 5:10:13 PM] |
[MMO] Azareal Online | Old Archive;Archive | Team name:Azareal OnlineProject name: Azareal Online(Azareal means "whom god helps")Brief description:This MMO will be widely open, with availability to do what you wish when you want to. I'm hoping for regular updates and possibly monthly quests added. Also, the player will be able to level up multiple skills (their total skills added up /2 = their level visible to other players). Some skills I have in mind are HP, Power, Accuracy, Defense, Magic, Archery (the HP+Power+Accuracy+Defense+Magic+Archery = Combat level), Stealth, Agility (the stealth+agility levels = Evasiveness level). I have some more, but it states "brief" in this title.Target aim:This will be a free online game and as it grows add paid benefits.Compensation:When the game starts getting paid benefits, the pay will be as such:2% saved for development/website upkeep80% to pay helpers (divided by the number of team members)18% other costs (possibly to keep a mobile service running, partnerships, etc)If anyone can come up with a better budget (most people probably can) let me know.Technology:This game will be client-based, currently only for windows. Mac and Linux with first full release.Talent needed:I am in desperate need of a 3D modeler, artist and pixel artist.Team structure:Will Keller (CEO): Team Leader, Concept Artist, Storyline DevelopmentJonathan Gorard (CTO): Website Developer, Engine Programmer, Client CodingTun (CBO): 2D Concept ArtPedro:ServerWebsite:azareal-online.comuv.comazareal-online.darkbb.comBoth are temporaryContacts:Contact me at [email protected] Work by Team:This is a brand new team.Feedback:ANY[Edited by - wkeller on November 19, 2010 5:04:54 PM] | Hey!Welcome to the forums.I think it would do your project good if you posted some sample concept art at least.Just to make more developers interested...That aside, the skill system looks really interesting, althoughI'd add archery to the total combat level too.I hope this game is going to turn out amazing,but sadly there are many lone creative minds coming by for a complete team,that don't get any. :(Good luck with the team, though. Remember to include appetizers, own work so that you can expect others to deliver likewise. :) ;Quote:Original post by SuperVGAHey!Welcome to the forums.I think it would do your project good if you posted some sample concept art at least.Just to make more developers interested...That aside, the skill system looks really interesting, althoughI'd add archery to the total combat level too.I hope this game is going to turn out amazing,but sadly there are many lone creative minds coming by for a complete team,that don't get any. :(Good luck with the team, though. Remember to include appetizers, own work so that you can expect others to deliver likewise. :)Thanks for the tips.I'm setting up & uploading a few things to my DeviantArt as I type. Well, as I work in the background.Anyways, Thanks again. ; Hi there!I'm Jonathan, and I would love to join your development team! I am a programmer and web developer, and I specialize in client-side and graphics programming for games. I could contribute to the team by creating and maintaining the website (for an example of a website I previously made for a game development team, go to http://biomass-studios.com ) I am familiar with most web languages (HTML, javascript, PHP, CSS) as well as C, C++, Java, Lua etc. I am confident in my ability to code almost of all of the client-side game engine, but I do not have much experience with server development.I also do quite a lot of meta-programming for games, as I have embedded a real time XML and scripting engine into a previous game I have worked on called Reggae Speed. I could also contribute by creating scripting systems and similar tools for content management in the MMO, as obviously you would need a set of comprehensive tools for managing such a large data model in an MMO. I will need to know more about the type of technology you are planning on using before I can say more about what I might be able to contribute.Basically, I am capable of doing any one of the following jobs:System Administration/MaintenanceWebsite Development/DesignEngine ProgrammingClient-side CodingContent ManagementWeb ToolsI hope to hear from you soon. My email address is [email protected][Edited by - JGorard159 on October 25, 2010 3:24:08 PM]; I am in need great need of a few positions; read the initial post. ; Still need help with some things. |
Glew and SFML linker issues with MinGW in windows :( | Graphics and GPU Programming;Programming | I am finally getting back to maintaining my project (Project Website) in windows, and eventually osx too. But I've run into some linker errors. I had a slew of issues with VC++ express in general, so I switched to MinGW and feel I am very close but I have a few linker errors left. Note: I have compiled or collected everything in .a files as needed for mingw and the library files are found (like libsfml-graphics.a), but I am still getting these linker errors. I am using a few other libraries like bullet and assimp which seem to be linking fine, so I suspect it's the order in which I'm linking or maybe I need to use the static libraries, I'm honestly not sure...here's my link order:glew32 sfml-graphics sfml-window sfml-audio sfml-network sfml-system assimp opengl32 glu32 glut32 BulletDynamics BulletCollision LinearMathhere's my linker output:Linking CXX executable sfml_test.exeC:\PROGRA~1\CODEBL~1\MinGW\bin\G__~1.EXE CMakeFiles\sfml_test.dir\Sources\main.cpp.obj -o sfml_test.exe -Wl,--out-implib,libsfml_test.dll.a -Wl,--major-image-version,0,--minor-image-version,0 -LDependencies\win32\library\debug -L..\..\Dependencies\win32\library\debug ..\..\ElementGames\Base\libegbase.a ..\..\ElementGames\Engine\libegengine.a -lglew32 -lsfml-graphics -lsfml-window -lsfml-audio -lsfml-network -lsfml-system -lassimp -lopengl32 -lglu32 -lglut32 -lBulletDynamics -lBulletCollision -lLinearMath ..\..\ElementGames\Base\libegbase.a -lkernel32 -luser32 -lgdi32 -lwinspool -lshell32 -lole32 -loleaut32 -luuid -lcomdlg32 -ladvapi32 Info: resolving vtable for sf::String by linking to __imp___ZTVN2sf6StringE (auto-import)Info: resolving vtable for sf::Drawable by linking to __imp___ZTVN2sf8DrawableE (auto-import)c:/progra~1/codebl~1/mingw/bin/../lib/gcc/mingw32/4.4.1/../../../../mingw32/bin/ld.exe: warning: auto-importing has been activated without --enable-auto-import specified on the command line.This should work unless it involves constant data structures referencing symbols from auto-imported DLLs...\..\ElementGames\Base\libegbase.a(SceneManagerBase.cpp.obj):SceneManagerBase.cpp:(.text+0x50c): undefined reference to `glewInit'..\..\ElementGames\Base\libegbase.a(SceneManagerBase.cpp.obj):SceneManagerBase.cpp:(.text+0x57d): undefined reference to `glPushAttrib@4'..\..\ElementGames\Base\libegbase.a(SceneManagerBase.cpp.obj):SceneManagerBase.cpp:(.text+0x587): undefined reference to `glPopAttrib@0'..\..\ElementGames\Base\libegbase.a(Console.cpp.obj):Console.cpp:(.text+0x398): undefined reference to `sf::Unicode::Text::Text(char const*)'..\..\ElementGames\Base\libegbase.a(Console.cpp.obj):Console.cpp:(.text+0xa3a): undefined reference to `sf::Unicode::Text::Text(char const*)'..\..\ElementGames\Base\libegbase.a(Console.cpp.obj):Console.cpp:(.text+0x1131): undefined reference to `sf::String::GetText() const'..\..\ElementGames\Base\libegbase.a(Console.cpp.obj):Console.cpp:(.text+0x1143): undefined reference to `sf::Unicode::Text::operator std::string() const'..\..\ElementGames\Base\libegbase.a(Console.cpp.obj):Console.cpp:(.text+0x25a5): undefined reference to `glVertex2i@8'..\..\ElementGames\Base\libegbase.a(Console.cpp.obj):Console.cpp:(.text+0x2600): undefined reference to `glVertex2i@8'..\..\ElementGames\Base\libegbase.a(Console.cpp.obj):Console.cpp:(.text+0x2663): undefined reference to `glVertex2i@8'..\..\ElementGames\Base\libegbase.a(Console.cpp.obj):Console.cpp:(.text+0x26c6): undefined reference to `glVertex2i@8'..\..\ElementGames\Base\libegbase.a(Console.cpp.obj):Console.cpp:(.text+0x2777): undefined reference to `glVertex2i@8'..\..\ElementGames\Base\libegbase.a(Console.cpp.obj):Console.cpp:(.text+0x27da): more undefined references to `glVertex2i@8' follow..\..\ElementGames\Base\libegbase.a(Console.cpp.obj):Console.cpp:(.text+0x2adb): undefined reference to `sf::Unicode::Text::Text(char const*)'..\..\ElementGames\Base\libegbase.a(Audio.cpp.obj):Audio.cpp:(.text+0x539): undefined reference to `sf::SoundBuffer::SoundBuffer()'..\..\ElementGames\Base\libegbase.a(Audio.cpp.obj):Audio.cpp:(.text+0x588): undefined reference to `sf::SoundBuffer::LoadFromFile(std::string const&)'..\..\ElementGames\Base\libegbase.a(Audio.cpp.obj):Audio.cpp:(.text+0x5dc): undefined reference to `sf::SoundBuffer::GetSampleRate() const'..\..\ElementGames\Base\libegbase.a(Audio.cpp.obj):Audio.cpp:(.text+0x5f0): undefined reference to `sf::SoundBuffer::GetChannelsCount() const'..\..\ElementGames\Base\libegbase.a(Audio.cpp.obj):Audio.cpp:(.text+0x604): undefined reference to `sf::SoundBuffer::GetDuration() const'..\..\ElementGames\Base\libegbase.a(Audio.cpp.obj):Audio.cpp:(.text+0xa89): undefined reference to `sf::Sound::Sound()'..\..\ElementGames\Base\libegbase.a(Audio.cpp.obj):Audio.cpp:(.text+0xaf0): undefined reference to `sf::Sound::Sound()'..\..\ElementGames\Base\libegbase.a(Audio.cpp.obj):Audio.cpp:(.text+0xb48): undefined reference to `sf::Sound::SetBuffer(sf::SoundBuffer const&)'..\..\ElementGames\Base\libegbase.a(Audio.cpp.obj):Audio.cpp:(.text+0xb63): undefined reference to `sf::Sound::SetLoop(bool)'..\..\ElementGames\Base\libegbase.a(Audio.cpp.obj):Audio.cpp:(.text+0xb7b): undefined reference to `sf::Sound::SetPitch(float)'..\..\ElementGames\Base\libegbase.a(Audio.cpp.obj):Audio.cpp:(.text+0xb93): undefined reference to `sf::Sound::SetVolume(float)'..\..\ElementGames\Base\libegbase.a(Audio.cpp.obj):Audio.cpp:(.text+0xbf6): undefined reference to `sf::Sound::Play()'..\..\ElementGames\Base\libegbase.a(Audio.cpp.obj):Audio.cpp:(.text+0xc0c): undefined reference to `sf::Sound::Pause()'..\..\ElementGames\Base\libegbase.a(Audio.cpp.obj):Audio.cpp:(.text+0xc22): undefined reference to `sf::Sound::Stop()'..\..\ElementGames\Base\libegbase.a(Audio.cpp.obj):Audio.cpp:(.text+0xc4b): undefined reference to `sf::Sound::SetVolume(float)'..\..\ElementGames\Base\libegbase.a(Audio.cpp.obj):Audio.cpp:(.text+0xc75): undefined reference to `sf::Sound::SetPitch(float)'..\..\ElementGames\Base\libegbase.a(Audio.cpp.obj):Audio.cpp:(.text+0xca8): undefined reference to `sf::Sound::SetLoop(bool)'..\..\ElementGames\Base\libegbase.a(Audio.cpp.obj):Audio.cpp:(.text+0xcf2): undefined reference to `sf::Sound::GetStatus() const'..\..\ElementGames\Base\libegbase.a(Audio.cpp.obj):Audio.cpp:(.text+0xd38): undefined reference to `sf::Sound::GetPlayingOffset() const'..\..\ElementGames\Base\libegbase.a(Audio.cpp.obj):Audio.cpp:(.text+0xdb1): undefined reference to `sf::Sound::SetPosition(float, float, float)'..\..\ElementGames\Base\libegbase.a(Audio.cpp.obj):Audio.cpp:(.text+0xe0b): undefined reference to `sf::Sound::SetAttenuation(float)'..\..\ElementGames\Base\libegbase.a(Audio.cpp.obj):Audio.cpp:(.text+0x14ef): undefined reference to `sf::Music::Music(unsigned int)'..\..\ElementGames\Base\libegbase.a(Audio.cpp.obj):Audio.cpp:(.text+0x1517): undefined reference to `sf::Music::OpenFromFile(std::string const&)'..\..\ElementGames\Base\libegbase.a(Audio.cpp.obj):Audio.cpp:(.text+0x1571): undefined reference to `sf::SoundStream::SetLoop(bool)'..\..\ElementGames\Base\libegbase.a(Audio.cpp.obj):Audio.cpp:(.text+0x158c): undefined reference to `sf::Sound::SetVolume(float)'..\..\ElementGames\Base\libegbase.a(Audio.cpp.obj):Audio.cpp:(.text+0x15a7): undefined reference to `sf::Sound::SetPitch(float)'..\..\ElementGames\Base\libegbase.a(Audio.cpp.obj):Audio.cpp:(.text+0x15b5): undefined reference to `sf::SoundStream::GetSampleRate() const'..\..\ElementGames\Base\libegbase.a(Audio.cpp.obj):Audio.cpp:(.text+0x15c9): undefined reference to `sf::SoundStream::GetChannelsCount() const'..\..\ElementGames\Base\libegbase.a(Audio.cpp.obj):Audio.cpp:(.text+0x15dd): undefined reference to `sf::Music::GetDuration() const'..\..\ElementGames\Base\libegbase.a(Audio.cpp.obj):Audio.cpp:(.text+0x170c): undefined reference to `sf::SoundStream::GetStatus() const'..\..\ElementGames\Base\libegbase.a(Audio.cpp.obj):Audio.cpp:(.text+0x1752): undefined reference to `sf::SoundStream::GetPlayingOffset() const'..\..\ElementGames\Base\libegbase.a(Audio.cpp.obj):Audio.cpp:(.text+0x17ce): undefined reference to `sf::Sound::SetPosition(float, float, float)'..\..\ElementGames\Base\libegbase.a(Audio.cpp.obj):Audio.cpp:(.text+0x1836): undefined reference to `sf::SoundStream::Play()'..\..\ElementGames\Base\libegbase.a(Audio.cpp.obj):Audio.cpp:(.text+0x184f): undefined reference to `sf::Sound::Pause()'..\..\ElementGames\Base\libegbase.a(Audio.cpp.obj):Audio.cpp:(.text+0x1866): undefined reference to `sf::SoundStream::Stop()'..\..\ElementGames\Base\libegbase.a(Audio.cpp.obj):Audio.cpp:(.text+0x25cf): undefined reference to `sf::Listener::SetPosition(float, float, float)'..\..\ElementGames\Base\libegbase.a(Audio.cpp.obj):Audio.cpp:(.text+0x2606): undefined reference to `sf::Listener::SetTarget(float, float, float)'..\..\ElementGames\Base\libegbase.a(Audio.cpp.obj):Audio.cpp:(.text+0x2631): undefined reference to `sf::Listener::SetGlobalVolume(float)'..\..\ElementGames\Base\libegbase.a(Texture.cpp.obj):Texture.cpp:(.text+0x2ca): undefined reference to `glGenTextures@8'..\..\ElementGames\Base\libegbase.a(Texture.cpp.obj):Texture.cpp:(.text+0x41f): undefined reference to `glTexParameterf@12'..\..\ElementGames\Base\libegbase.a(Texture.cpp.obj):Texture.cpp:(.text+0x43d): undefined reference to `glTexParameterf@12'..\..\ElementGames\Base\libegbase.a(Texture.cpp.obj):Texture.cpp:(.text+0x462): undefined reference to `sf::Image::GetPixelsPtr() const'..\..\ElementGames\Base\libegbase.a(Texture.cpp.obj):Texture.cpp:(.text+0x471): undefined reference to `sf::Image::GetHeight() const'..\..\ElementGames\Base\libegbase.a(Texture.cpp.obj):Texture.cpp:(.text+0x480): undefined reference to `sf::Image::GetWidth() const'..\..\ElementGames\Base\libegbase.a(Texture.cpp.obj):Texture.cpp:(.text+0x4c0): undefined reference to `glTexImage2D@36'..\..\ElementGames\Base\libegbase.a(Texture.cpp.obj):Texture.cpp:(.text+0x4d2): undefined reference to `sf::Image::GetPixelsPtr() const'..\..\ElementGames\Base\libegbase.a(Texture.cpp.obj):Texture.cpp:(.text+0x4e1): undefined reference to `sf::Image::GetHeight() const'..\..\ElementGames\Base\libegbase.a(Texture.cpp.obj):Texture.cpp:(.text+0x4f0): undefined reference to `sf::Image::GetWidth() const'..\..\ElementGames\Base\libegbase.a(Texture.cpp.obj):Texture.cpp:(.text+0x520): undefined reference to `gluBuild2DMipmaps@28'..\..\ElementGames\Base\libegbase.a(Texture.cpp.obj):Texture.cpp:(.text+0x5a5): undefined reference to `sf::Image::Image()'..\..\ElementGames\Base\libegbase.a(Texture.cpp.obj):Texture.cpp:(.text+0x5c8): undefined reference to `sf::Image::LoadFromFile(std::string const&)'..\..\ElementGames\Base\libegbase.a(Texture.cpp.obj):Texture.cpp:(.text+0xceb): undefined reference to `glGenTextures@8'..\..\ElementGames\Base\libegbase.a(Texture.cpp.obj):Texture.cpp:(.text+0xe40): undefined reference to `glTexParameterf@12'..\..\ElementGames\Base\libegbase.a(Texture.cpp.obj):Texture.cpp:(.text+0xe5e): undefined reference to `glTexParameterf@12'..\..\ElementGames\Base\libegbase.a(Texture.cpp.obj):Texture.cpp:(.text+0xee4): undefined reference to `sf::Image::GetPixelsPtr() const'..\..\ElementGames\Base\libegbase.a(Texture.cpp.obj):Texture.cpp:(.text+0xef3): undefined reference to `sf::Image::GetHeight() const'..\..\ElementGames\Base\libegbase.a(Texture.cpp.obj):Texture.cpp:(.text+0xf02): undefined reference to `sf::Image::GetWidth() const'..\..\ElementGames\Base\libegbase.a(Texture.cpp.obj):Texture.cpp:(.text+0xf42): undefined reference to `glTexImage2D@36'..\..\ElementGames\Base\libegbase.a(Texture.cpp.obj):Texture.cpp:(.text+0xf53): undefined reference to `sf::Image::GetPixelsPtr() const'..\..\ElementGames\Base\libegbase.a(Texture.cpp.obj):Texture.cpp:(.text+0xf63): undefined reference to `sf::Image::GetHeight() const'..\..\ElementGames\Base\libegbase.a(Texture.cpp.obj):Texture.cpp:(.text+0xf73): undefined reference to `sf::Image::GetWidth() const'..\..\ElementGames\Base\libegbase.a(Texture.cpp.obj):Texture.cpp:(.text+0xfb3): undefined reference to `glTexImage2D@36'..\..\ElementGames\Base\libegbase.a(Texture.cpp.obj):Texture.cpp:(.text+0xfc4): undefined reference to `sf::Image::GetPixelsPtr() const'..\..\ElementGames\Base\libegbase.a(Texture.cpp.obj):Texture.cpp:(.text+0xfd4): undefined reference to `sf::Image::GetHeight() const'..\..\ElementGames\Base\libegbase.a(Texture.cpp.obj):Texture.cpp:(.text+0xfe4): undefined reference to `sf::Image::GetWidth() const'..\..\ElementGames\Base\libegbase.a(Texture.cpp.obj):Texture.cpp:(.text+0x1024): undefined reference to `glTexImage2D@36'..\..\ElementGames\Base\libegbase.a(Texture.cpp.obj):Texture.cpp:(.text+0x1035): undefined reference to `sf::Image::GetPixelsPtr() const'..\..\ElementGames\Base\libegbase.a(Texture.cpp.obj):Texture.cpp:(.text+0x1045): undefined reference to `sf::Image::GetHeight() const'..\..\ElementGames\Base\libegbase.a(Texture.cpp.obj):Texture.cpp:(.text+0x1055): undefined reference to `sf::Image::GetWidth() const'..\..\ElementGames\Base\libegbase.a(Texture.cpp.obj):Texture.cpp:(.text+0x1095): undefined reference to `glTexImage2D@36'..\..\ElementGames\Base\libegbase.a(Texture.cpp.obj):Texture.cpp:(.text+0x10a6): undefined reference to `sf::Image::GetPixelsPtr() const'..\..\ElementGames\Base\libegbase.a(Texture.cpp.obj):Texture.cpp:(.text+0x10b6): undefined reference to `sf::Image::GetHeight() const'..\..\ElementGames\Base\libegbase.a(Texture.cpp.obj):Texture.cpp:(.text+0x10c6): undefined reference to `sf::Image::GetWidth() const'..\..\ElementGames\Base\libegbase.a(Texture.cpp.obj):Texture.cpp:(.text+0x1106): undefined reference to `glTexImage2D@36'..\..\ElementGames\Base\libegbase.a(Texture.cpp.obj):Texture.cpp:(.text+0x1117): undefined reference to `sf::Image::GetPixelsPtr() const'..\..\ElementGames\Base\libegbase.a(Texture.cpp.obj):Texture.cpp:(.text+0x1127): undefined reference to `sf::Image::GetHeight() const'..\..\ElementGames\Base\libegbase.a(Texture.cpp.obj):Texture.cpp:(.text+0x1137): undefined reference to `sf::Image::GetWidth() const'..\..\ElementGames\Base\libegbase.a(Texture.cpp.obj):Texture.cpp:(.text+0x1177): undefined reference to `glTexImage2D@36'..\..\ElementGames\Base\libegbase.a(Texture.cpp.obj):Texture.cpp:(.text+0x118c): undefined reference to `sf::Image::GetPixelsPtr() const'..\..\ElementGames\Base\libegbase.a(Texture.cpp.obj):Texture.cpp:(.text+0x119b): undefined reference to `sf::Image::GetHeight() const'..\..\ElementGames\Base\libegbase.a(Texture.cpp.obj):Texture.cpp:(.text+0x11aa): undefined reference to `sf::Image::GetWidth() const'..\..\ElementGames\Base\libegbase.a(Texture.cpp.obj):Texture.cpp:(.text+0x11da): undefined reference to `gluBuild2DMipmaps@28'..\..\ElementGames\Base\libegbase.a(Texture.cpp.obj):Texture.cpp:(.text+0x11eb): undefined reference to `sf::Image::GetPixelsPtr() const'..\..\ElementGames\Base\libegbase.a(Texture.cpp.obj):Texture.cpp:(.text+0x11fb): undefined reference to `sf::Image::GetHeight() const'..\..\ElementGames\Base\libegbase.a(Texture.cpp.obj):Texture.cpp:(.text+0x120b): undefined reference to `sf::Image::GetWidth() const'..\..\ElementGames\Base\libegbase.a(Texture.cpp.obj):Texture.cpp:(.text+0x123b): undefined reference to `gluBuild2DMipmaps@28'..\..\ElementGames\Base\libegbase.a(Texture.cpp.obj):Texture.cpp:(.text+0x124c): undefined reference to `sf::Image::GetPixelsPtr() const'..\..\ElementGames\Base\libegbase.a(Texture.cpp.obj):Texture.cpp:(.text+0x125c): undefined reference to `sf::Image::GetHeight() const'..\..\ElementGames\Base\libegbase.a(Texture.cpp.obj):Texture.cpp:(.text+0x126c): undefined reference to `sf::Image::GetWidth() const'..\..\ElementGames\Base\libegbase.a(Texture.cpp.obj):Texture.cpp:(.text+0x129c): undefined reference to `gluBuild2DMipmaps@28'..\..\ElementGames\Base\libegbase.a(Texture.cpp.obj):Texture.cpp:(.text+0x12ad): undefined reference to `sf::Image::GetPixelsPtr() const'..\..\ElementGames\Base\libegbase.a(Texture.cpp.obj):Texture.cpp:(.text+0x12bd): undefined reference to `sf::Image::GetHeight() const'..\..\ElementGames\Base\libegbase.a(Texture.cpp.obj):Texture.cpp:(.text+0x12cd): undefined reference to `sf::Image::GetWidth() const'..\..\ElementGames\Base\libegbase.a(Texture.cpp.obj):Texture.cpp:(.text+0x12fd): undefined reference to `gluBuild2DMipmaps@28'..\..\ElementGames\Base\libegbase.a(Texture.cpp.obj):Texture.cpp:(.text+0x130e): undefined reference to `sf::Image::GetPixelsPtr() const'..\..\ElementGames\Base\libegbase.a(Texture.cpp.obj):Texture.cpp:(.text+0x131e): undefined reference to `sf::Image::GetHeight() const'..\..\ElementGames\Base\libegbase.a(Texture.cpp.obj):Texture.cpp:(.text+0x132e): undefined reference to `sf::Image::GetWidth() const'..\..\ElementGames\Base\libegbase.a(Texture.cpp.obj):Texture.cpp:(.text+0x135e): undefined reference to `gluBuild2DMipmaps@28'..\..\ElementGames\Base\libegbase.a(Texture.cpp.obj):Texture.cpp:(.text+0x136f): undefined reference to `sf::Image::GetPixelsPtr() const'..\..\ElementGames\Base\libegbase.a(Texture.cpp.obj):Texture.cpp:(.text+0x137f): undefined reference to `sf::Image::GetHeight() const'..\..\ElementGames\Base\libegbase.a(Texture.cpp.obj):Texture.cpp:(.text+0x138f): undefined reference to `sf::Image::GetWidth() const'..\..\ElementGames\Base\libegbase.a(Texture.cpp.obj):Texture.cpp:(.text+0x13bf): undefined reference to `gluBuild2DMipmaps@28'..\..\ElementGames\Base\libegbase.a(Texture.cpp.obj):Texture.cpp:(.text+0x1535): undefined reference to `sf::Image::Image()'..\..\ElementGames\Base\libegbase.a(Texture.cpp.obj):Texture.cpp:(.text+0x155b): undefined reference to `sf::Image::LoadFromFile(std::string const&)'..\..\ElementGames\Base\libegbase.a(Texture.cpp.obj):Texture.cpp:(.text+0x1582): undefined reference to `sf::Image::Image()'..\..\ElementGames\Base\libegbase.a(Texture.cpp.obj):Texture.cpp:(.text+0x15d4): undefined reference to `sf::Image::LoadFromFile(std::string const&)'..\..\ElementGames\Base\libegbase.a(Texture.cpp.obj):Texture.cpp:(.text+0x15fb): undefined reference to `sf::Image::Image()'..\..\ElementGames\Base\libegbase.a(Texture.cpp.obj):Texture.cpp:(.text+0x164d): undefined reference to `sf::Image::LoadFromFile(std::string const&)'..\..\ElementGames\Base\libegbase.a(Texture.cpp.obj):Texture.cpp:(.text+0x1674): undefined reference to `sf::Image::Image()'..\..\ElementGames\Base\libegbase.a(Texture.cpp.obj):Texture.cpp:(.text+0x16c6): undefined reference to `sf::Image::LoadFromFile(std::string const&)'..\..\ElementGames\Base\libegbase.a(Texture.cpp.obj):Texture.cpp:(.text+0x16ed): undefined reference to `sf::Image::Image()'..\..\ElementGames\Base\libegbase.a(Texture.cpp.obj):Texture.cpp:(.text+0x173f): undefined reference to `sf::Image::LoadFromFile(std::string const&)'..\..\ElementGames\Base\libegbase.a(Texture.cpp.obj):Texture.cpp:(.text+0x1760): undefined reference to `sf::Image::Image()'..\..\ElementGames\Base\libegbase.a(Texture.cpp.obj):Texture.cpp:(.text+0x17af): undefined reference to `sf::Image::LoadFromFile(std::string const&)'..\..\ElementGameundefineds\Base\libegbase.a(Camera.cpp.obj):Camera.cpp:(.text+0x1303): reference to `glGetDoublev@8'..\..\ElementGameundefineds\Base\libegbase.a(Camera.cpp.obj):Camera.cpp:(.text+0x131e): reference to `glGetDoublev@8'..\..\ElementGameundefineds\Base\libegbase.a(Shader.cpp.obj):Shader.cpp:(.text+0x19cc): reference to `__glewCreateShader'..\..\ElementGameundefineds\Base\libegbase.a(Shader.cpp.obj):Shader.cpp:(.text+0x19e9): reference to `__glewCreateShader'..\..\ElementGameundefineds\Base\libegbase.a(Shader.cpp.obj):Shader.cpp:(.text+0x1a0a): reference to `__glewCreateShader'..\..\ElementGameundefineds\Base\libegbase.a(Shader.cpp.obj):Shader.cpp:(.text+0x1d16): reference to `__glewShaderSource'..\..\ElementGameundefineds\Base\libegbase.a(Shader.cpp.obj):Shader.cpp:(.text+0x1d4e): reference to `__glewShaderSource'..\..\ElementGameundefineds\Base\libegbase.a(Shader.cpp.obj):Shader.cpp:(.text+0x1d8a): reference to `__glewShaderSource'..\..\ElementGameundefineds\Base\libegbase.a(Shader.cpp.obj):Shader.cpp:(.text+0x1dbc): reference to `__glewCompileShader'..\..\ElementGameundefineds\Base\libegbase.a(Shader.cpp.obj):Shader.cpp:(.text+0x1dd6): reference to `__glewCompileShader'..\..\ElementGameundefineds\Base\libegbase.a(Shader.cpp.obj):Shader.cpp:(.text+0x1df4): reference to `__glewCompileShader'..\..\ElementGameundefineds\Base\libegbase.a(Shader.cpp.obj):Shader.cpp:(.text+0x1e07): reference to `__glewCreateProgramObjectARB'..\..\ElementGameundefineds\Base\libegbase.a(Shader.cpp.obj):Shader.cpp:(.text+0x1e1c): reference to `__glewAttachShader'..\..\ElementGameundefineds\Base\libegbase.a(Shader.cpp.obj):Shader.cpp:(.text+0x1e39): reference to `__glewAttachShader'..\..\ElementGameundefineds\Base\libegbase.a(Shader.cpp.obj):Shader.cpp:(.text+0x1e61): reference to `__glewAttachShader'..\..\ElementGameundefineds\Base\libegbase.a(Shader.cpp.obj):Shader.cpp:(.text+0x1e89): reference to `__glewProgramParameteriEXT'..\..\ElementGameundefineds\Base\libegbase.a(Shader.cpp.obj):Shader.cpp:(.text+0x1eb4): reference to `__glewProgramParameteriEXT'..\..\ElementGameundefineds\Base\libegbase.a(Shader.cpp.obj):Shader.cpp:(.text+0x1ed8): reference to `__glewProgramParameteriEXT'..\..\ElementGameundefineds\Base\libegbase.a(Shader.cpp.obj):Shader.cpp:(.text+0x1efc): reference to `__glewLinkProgram'..\..\ElementGameundefineds\Base\libegbase.a(Shader.cpp.obj):Shader.cpp:(.text+0x1f17): reference to `__glewUseProgram'..\..\ElementGameundefineds\Base\libegbase.a(Shader.cpp.obj):Shader.cpp:(.text+0x1f3d): reference to `__glewUseProgram'..\..\ElementGameundefineds\Base\libegbase.a(Shader.cpp.obj):Shader.cpp:(.text+0x1fbe): reference to `__glewGetUniformLocation'..\..\ElementGameundefineds\Base\libegbase.a(Shader.cpp.obj):Shader.cpp:(.text+0x1fe9): reference to `__glewGetAttribLocation'..\..\ElementGameundefineds\Base\libegbase.a(Shader.cpp.obj):Shader.cpp:(.text+0x209c): reference to `__glewUniform1i'..\..\ElementGameundefineds\Base\libegbase.a(Shader.cpp.obj):Shader.cpp:(.text+0x2184): reference to `__glewUniform2i'..\..\ElementGameundefineds\Base\libegbase.a(Shader.cpp.obj):Shader.cpp:(.text+0x2274): reference to `__glewUniform3i'..\..\ElementGameundefineds\Base\libegbase.a(Shader.cpp.obj):Shader.cpp:(.text+0x236a): reference to `__glewUniform4i'..\..\ElementGameundefineds\Base\libegbase.a(Shader.cpp.obj):Shader.cpp:(.text+0x2468): reference to `__glewUniform1iv'..\..\ElementGameundefineds\Base\libegbase.a(Shader.cpp.obj):Shader.cpp:(.text+0x2595): reference to `__glewUniform1f'..\..\ElementGameundefineds\Base\libegbase.a(Shader.cpp.obj):Shader.cpp:(.text+0x25bc): reference to `__glewVertexAttrib1f'..\..\ElementGameundefineds\Base\libegbase.a(Shader.cpp.obj):Shader.cpp:(.text+0x26b3): reference to `__glewUniform2f'..\..\ElementGameundefineds\Base\libegbase.a(Shader.cpp.obj):Shader.cpp:(.text+0x26e1): reference to `__glewVertexAttrib2f'..\..\ElementGameundefineds\Base\libegbase.a(Shader.cpp.obj):Shader.cpp:(.text+0x27df): reference to `__glewUniform3f'..\..\ElementGameundefineds\Base\libegbase.a(Shader.cpp.obj):Shader.cpp:(.text+0x2814): reference to `__glewVertexAttrib3f'..\..\ElementGameundefineds\Base\libegbase.a(Shader.cpp.obj):Shader.cpp:(.text+0x2919): reference to `__glewUniform4f'..\..\ElementGameundefineds\Base\libegbase.a(Shader.cpp.obj):Shader.cpp:(.text+0x2955): reference to `__glewVertexAttrib4f'..\..\ElementGameundefineds\Base\libegbase.a(Shader.cpp.obj):Shader.cpp:(.text+0x2a61): reference to `__glewUniform1fv'..\..\ElementGameundefineds\Base\libegbase.a(Shader.cpp.obj):Shader.cpp:(.text+0x2a8f): reference to `__glewVertexAttrib1fv'..\..\ElementGameundefineds\Base\libegbase.a(Shader.cpp.obj):Shader.cpp:(.text+0x2b48): reference to `__glewUniformMatrix2fv'..\..\ElementGameundefineds\Base\libegbase.a(Shader.cpp.obj):Shader.cpp:(.text+0x2c40): reference to `__glewUniformMatrix3fv'..\..\ElementGameundefineds\Base\libegbase.a(Shader.cpp.obj):Shader.cpp:(.text+0x2d38): reference to `__glewUniformMatrix4fv'..\..\ElementGameundefineds\Base\libegbase.a(Shader.cpp.obj):Shader.cpp:(.text+0x2dbc): reference to `__glewProgramParameteriEXT'..\..\ElementGameundefineds\Base\libegbase.a(Shader.cpp.obj):Shader.cpp:(.text+0x2ddf): reference to `__glewProgramParameteriEXT'..\..\ElementGameundefineds\Base\libegbase.a(Shader.cpp.obj):Shader.cpp:(.text+0x2e02): reference to `__glewLinkProgram'..\..\ElementGameundefineds\Base\libegbase.a(Shader.cpp.obj):Shader.cpp:(.text+0x2e1e): reference to `__glewUseProgram'..\..\ElementGameundefineds\Base\libegbase.a(Shader.cpp.obj):Shader.cpp:(.text+0x2e41): reference to `__glewUseProgram'..\..\ElementGameundefineds\Base\libegbase.a(Shader.cpp.obj):Shader.cpp:(.text+0x2e7b): reference to `__glewGetShaderiv'..\..\ElementGameundefineds\Base\libegbase.a(Shader.cpp.obj):Shader.cpp:(.text+0x2eb8): reference to `__glewGetShaderInfoLog'..\..\ElementGameundefineds\Base\libegbase.a(Shader.cpp.obj):Shader.cpp:(.text+0x2f5a): reference to `__glewGetProgramiv'..\..\ElementGameundefineds\Base\libegbase.a(Shader.cpp.obj):Shader.cpp:(.text+0x2f97): reference to `__glewGetProgramInfoLog'..\..\ElementGameundefineds\Base\libegbase.a(Shader.cpp.obj):Shader.cpp:(.text+0x3063): reference to `__glewDetachShader'..\..\ElementGameundefineds\Base\libegbase.a(Shader.cpp.obj):Shader.cpp:(.text+0x3080): reference to `__glewDeleteShader'..\..\ElementGameundefineds\Base\libegbase.a(Shader.cpp.obj):Shader.cpp:(.text+0x30a6): reference to `__glewDetachShader'..\..\ElementGameundefineds\Base\libegbase.a(Shader.cpp.obj):Shader.cpp:(.text+0x30c4): reference to `__glewDeleteShader'..\..\ElementGameundefineds\Base\libegbase.a(Shader.cpp.obj):Shader.cpp:(.text+0x30ec): reference to `__glewDetachShader'..\..\ElementGameundefineds\Base\libegbase.a(Shader.cpp.obj):Shader.cpp:(.text+0x310a): reference to `__glewDeleteShader'..\..\ElementGameundefineds\Base\libegbase.a(Shader.cpp.obj):Shader.cpp:(.text+0x3132): reference to `__glewDeleteShader'..\..\ElementGames\Base\libegbase.a(Graphics.cpp.obj):Graphics.cpp:(.text+0x2e9): undefined reference to `glEnableClientState@4'..\..\ElementGames\Base\libegbase.a(Graphics.cpp.obj):Graphics.cpp:(.text+0x332): undefined reference to `glVertexPointer@16'..\..\ElementGames\Base\libegbase.a(Graphics.cpp.obj):Graphics.cpp:(.text+0x350): undefined reference to `glEnableClientState@4'..\..\ElementGames\Base\libegbase.a(Graphics.cpp.obj):Graphics.cpp:(.text+0x38a): undefined reference to `glNormalPointer@12'..\..\ElementGames\Base\libegbase.a(Graphics.cpp.obj):Graphics.cpp:(.text+0x3a8): undefined reference to `glEnableClientState@4'..\..\ElementGames\Base\libegbase.a(Graphics.cpp.obj):Graphics.cpp:(.text+0x3ea): undefined reference to `glColorPointer@16'..\..\ElementGames\Base\libegbase.a(Graphics.cpp.obj):Graphics.cpp:(.text+0x423): undefined reference to `glEnableClientState@4'..\..\ElementGames\Base\libegbase.a(Graphics.cpp.obj):Graphics.cpp:(.text+0x46c): undefined reference to `glTexCoordPointer@16'..\..\ElementGames\Base\libegbase.a(Graphics.cpp.obj):Graphics.cpp:(.text+0x4a5): undefined reference to `glEnableClientState@4'..\..\ElementGames\Base\libegbase.a(Graphics.cpp.obj):Graphics.cpp:(.text+0x4ee): undefined reference to `glTexCoordPointer@16'..\..\ElementGames\Base\libegbase.a(Graphics.cpp.obj):Graphics.cpp:(.text+0x527): undefined reference to `glEnableClientState@4'..\..\ElementGames\Base\libegbase.a(Graphics.cpp.obj):Graphics.cpp:(.text+0x570): undefined reference to `glTexCoordPointer@16'..\..\ElementGames\Base\libegbase.a(Graphics.cpp.obj):Graphics.cpp:(.text+0x5a9): undefined reference to `glEnableClientState@4'..\..\ElementGames\Base\libegbase.a(Graphics.cpp.obj):Graphics.cpp:(.text+0x5f2): undefined reference to `glTexCoordPointer@16'..\..\ElementGames\Base\libegbase.a(Graphics.cpp.obj):Graphics.cpp:(.text+0x641): undefined reference to `glDrawArrays@12'..\..\ElementGames\Base\libegbase.a(Graphics.cpp.obj):Graphics.cpp:(.text+0x66c): undefined reference to `glDrawArrays@12'..\..\ElementGames\Base\libegbase.a(Graphics.cpp.obj):Graphics.cpp:(.text+0x697): undefined reference to `glDrawArrays@12'..\..\ElementGames\Base\libegbase.a(Graphics.cpp.obj):Graphics.cpp:(.text+0x6c2): undefined reference to `glDrawArrays@12'..\..\ElementGames\Base\libegbase.a(Graphics.cpp.obj):Graphics.cpp:(.text+0x6ed): undefined reference to `glDrawArrays@12'..\..\ElementGames\Base\libegbase.a(Graphics.cpp.obj):Graphics.cpp:(.text+0x718): more undefined references to `glDrawArrays@12' follow..\..\ElementGames\Base\libegbase.a(Graphics.cpp.obj):Graphics.cpp:(.text+0x7e5): undefined reference to `glDisableClientState@4'..\..\ElementGames\Base\libegbase.a(Graphics.cpp.obj):Graphics.cpp:(.text+0x7f4): undefined reference to `glDisableClientState@4'..\..\ElementGames\Base\libegbase.a(Graphics.cpp.obj):Graphics.cpp:(.text+0x803): undefined reference to `glDisableClientState@4'..\..\ElementGames\Base\libegbase.a(Graphics.cpp.obj):Graphics.cpp:(.text+0x81e): undefined reference to `glDisableClientState@4'..\..\ElementGames\Base\libegbase.a(Graphics.cpp.obj):Graphics.cpp:(.text+0x839): undefined reference to `glDisableClientState@4'..\..\ElementGames\Base\libegbase.a(Graphics.cpp.obj):Graphics.cpp:(.text+0x854): more undefined references to `glDisableClientState@4' follow..\..\ElementGames\Base\libegbase.a(Graphics.cpp.obj):Graphics.cpp:(.text+0x87f): undefined reference to `__glewActiveTexture'..\..\ElementGames\Base\libegbase.a(Graphics.cpp.obj):Graphics.cpp:(.text+0x895): undefined reference to `__glewClientActiveTexture'..\..\ElementGames\Base\libegbase.a(Graphics.cpp.obj):Graphics.cpp:(.text+0x8b3): undefined reference to `glGetError@0'..\..\ElementGames\Base\libegbase.a(Graphics.cpp.obj):Graphics.cpp:(.text+0x22f1): undefined reference to `glNormal3f@12'..\..\ElementGames\Base\libegbase.a(Graphics.cpp.obj):Graphics.cpp:(.text+0x25e0): undefined reference to `glNormal3f@12'..\..\ElementGames\Base\libegbase.a(Graphics.cpp.obj):Graphics.cpp:(.text+0x278f): undefined reference to `glVertex2i@8'..\..\ElementGames\Base\libegbase.a(Graphics.cpp.obj):Graphics.cpp:(.text+0x27c3): undefined reference to `glVertex2i@8'..\..\ElementGames\Base\libegbase.a(Graphics.cpp.obj):Graphics.cpp:(.text+0x27ff): undefined reference to `glVertex2i@8'..\..\ElementGames\Base\libegbase.a(Graphics.cpp.obj):Graphics.cpp:(.text+0x2835): undefined reference to `glVertex2i@8'..\..\ElementGames\Base\libegbase.a(Graphics.cpp.obj):Graphics.cpp:(.text+0x28ab): undefined reference to `glOrtho@48'..\..\ElementGames\Base\libegbase.a(Graphics.cpp.obj):Graphics.cpp:(.text+0x2913): undefined reference to `__GLEW_ARB_draw_buffers'..\..\ElementGames\Base\libegbase.a(Graphics.cpp.obj):Graphics.cpp:(.text+0x291f): undefined reference to `__glewDrawBuffers'..\..\ElementGames\Base\libegbase.a(Graphics.cpp.obj):Graphics.cpp:(.text+0x2a83): undefined reference to `glPushAttrib@4'..\..\ElementGames\Base\libegbase.a(Graphics.cpp.obj):Graphics.cpp:(.text+0x2b68): undefined reference to `glDrawBuffer@4'..\..\ElementGames\Base\libegbase.a(Graphics.cpp.obj):Graphics.cpp:(.text+0x2b77): undefined reference to `glReadBuffer@4'..\..\ElementGames\Base\libegbase.a(Graphics.cpp.obj):Graphics.cpp:(.text+0x2cc3): undefined reference to `glDrawBuffer@4'..\..\ElementGames\Base\libegbase.a(Graphics.cpp.obj):Graphics.cpp:(.text+0x2cd2): undefined reference to `glReadBuffer@4'..\..\ElementGames\Base\libegbase.a(Graphics.cpp.obj):Graphics.cpp:(.text+0x2dba): undefined reference to `glDrawBuffer@4'..\..\ElementGames\Base\libegbase.a(Graphics.cpp.obj):Graphics.cpp:(.text+0x2dc9): undefined reference to `glReadBuffer@4'..\..\ElementGames\Base\libegbase.a(Graphics.cpp.obj):Graphics.cpp:(.text+0x2eb1): undefined reference to `glDrawBuffer@4'..\..\ElementGames\Base\libegbase.a(Graphics.cpp.obj):Graphics.cpp:(.text+0x2ec0): undefined reference to `glReadBuffer@4'..\..\ElementGames\Base\libegbase.a(Graphics.cpp.obj):Graphics.cpp:(.text+0x2fa8): undefined reference to `glDrawBuffer@4'..\..\ElementGames\Base\libegbase.a(Graphics.cpp.obj):Graphics.cpp:(.text+0x2fb7): undefined reference to `glReadBuffer@4'..\..\ElementGames\Base\libegbase.a(Graphics.cpp.obj):Graphics.cpp:(.text+0x354f): undefined reference to `glPushAttrib@4'..\..\ElementGames\Base\libegbase.a(Graphics.cpp.obj):Graphics.cpp:(.text+0x3d84): undefined reference to `glPopAttrib@0'..\..\ElementGames\Base\libegbase.a(Graphics.cpp.obj):Graphics.cpp:(.text+0x4183): undefined reference to `glPopAttrib@0'..\..\ElementGames\Base\libegbase.a(Graphics.cpp.obj):Graphics.cpp:(.text+0x4501): undefined reference to `glLightfv@12'..\..\ElementGames\Base\libegbase.a(Graphics.cpp.obj):Graphics.cpp:(.text+0x4524): undefined reference to `glLightfv@12'..\..\ElementGames\Base\libegbase.a(Graphics.cpp.obj):Graphics.cpp:(.text+0x4547): undefined reference to `glLightfv@12'..\..\ElementGames\Base\libegbase.a(Graphics.cpp.obj):Graphics.cpp:(.text+0x456a): undefined reference to `glLightfv@12'..\..\ElementGames\Base\lFrameBufferObject.cppibegbase.a(FrameBufferObject.cpp.obj)::(.text+0x2af): undefined reference to `__GLEW_EXT_framebuffer_object'..\..\ElementGames\Base\lFrameBufferObject.cppibegbase.a(FrameBufferObject.cpp.obj)::(.text+0x2f4): undefined reference to `__glewGenFramebuffersEXT'..\..\ElementGames\Base\lFrameBufferObject.cppibegbase.a(FrameBufferObject.cpp.obj)::(.text+0x3c0): undefined reference to `glGenTextures@8'..\..\ElementGames\Base\lFrameBufferObject.cppibegbase.a(FrameBufferObject.cpp.obj)::(.text+0x5de): undefined reference to `glTexImage2D@36'..\..\ElementGames\Base\lFrameBufferObject.cppibegbase.a(FrameBufferObject.cpp.obj)::(.text+0x61c): undefined reference to `glGenTextures@8'..\..\ElementGames\Base\lFrameBufferObject.cppibegbase.a(FrameBufferObject.cpp.obj)::(.text+0x689): undefined reference to `glTexImage2D@36'..\..\ElementGames\Base\lFrameBufferObject.cppibegbase.a(FrameBufferObject.cpp.obj)::(.text+0x6df): undefined reference to `__glewBindFramebufferEXT'..\..\ElementGames\Base\lFrameBufferObject.cppibegbase.a(FrameBufferObject.cpp.obj)::(.text+0x70b): undefined reference to `__glewFramebufferTexture2DEXT'..\..\ElementGames\Base\lFrameBufferObject.cppibegbase.a(FrameBufferObject.cpp.obj)::(.text+0x76a): undefined reference to `__glewFramebufferTexture2DEXT'..\..\ElementGames\Base\lFrameBufferObject.cppibegbase.a(FrameBufferObject.cpp.obj)::(.text+0x7b4): undefined reference to `glDrawBuffer@4'..\..\ElementGames\Base\lFrameBufferObject.cppibegbase.a(FrameBufferObject.cpp.obj)::(.text+0x7c3): undefined reference to `glReadBuffer@4'..\..\ElementGames\Base\lFrameBufferObject.cppibegbase.a(FrameBufferObject.cpp.obj)::(.text+0x7cb): undefined reference to `__glewCheckFramebufferStatusEXT'..\..\ElementGames\Base\lFrameBufferObject.cppibegbase.a(FrameBufferObject.cpp.obj)::(.text+0x86e): undefined reference to `__glewBindFramebufferEXT'..\..\ElementGames\Base\lFrameBufferObject.cppibegbase.a(FrameBufferObject.cpp.obj)::(.text+0x8c5): undefined reference to `__glewBindFramebufferEXT'..\..\ElementGames\Base\lFrameBufferObject.cppibegbase.a(FrameBufferObject.cpp.obj)::(.text+0x8e9): undefined reference to `__glewBindFramebufferEXT'..\..\ElementGames\Base\lFrameBufferObject.cppibegbase.a(FrameBufferObject.cpp.obj)::(.text+0x90b): undefined reference to `glDrawBuffer@4'..\..\ElementGames\Base\lFrameBufferObject.cppibegbase.a(FrameBufferObject.cpp.obj)::(.text+0x91c): undefined reference to `glReadBuffer@4'..\..\ElemeundefinedntGames\Base\libegbase.a(Font.cpp.obj):Font.cpp:(.text+0xab): reference to `sf::Font::Font()'..\..\ElemeundefinedntGames\Base\libegbase.a(Font.cpp.obj):Font.cpp:(.text+0xbc): reference to `sf::Font::ourDefaultCharset'..\..\ElemeundefinedntGames\Base\libegbase.a(Font.cpp.obj):Font.cpp:(.text+0xce): reference to `sf::Unicode::Text::Text(unsigned int const*)'..\..\ElemeundefinedntGames\Base\libegbase.a(Font.cpp.obj):Font.cpp:(.text+0xf8): referenceUnicode to `sf::Font::LoadFromFile(std::string const&, unsigned int, sf::::Text const&)'..\..\ElemenundefinedtGames\Base\libegbase.a(Font.cpp.obj):Font.cpp:(.text+0x1c1): reference to `sf::Font::Font()'..\..\ElemenundefinedtGames\Base\libegbase.a(Font.cpp.obj):Font.cpp:(.text+0x1d2): reference to `sf::Font::ourDefaultCharset'..\..\ElemenundefinedtGames\Base\libegbase.a(Font.cpp.obj):Font.cpp:(.text+0x1e4): reference to `sf::Unicode::Text::Text(unsigned int const*)'..\..\ElemenundefinedtGames\Base\libegbase.a(Font.cpp.obj):Font.cpp:(.text+0x20e): reUnicode to `sf::Font::LoadFromFile(std::string const&, unsigned int, sf::::Text const&)'..\..\ElementGames\Batext$_ZN2sf4FontD1Evse\libegbase.a(Font.cpp.obj):Font.cpp:(.[sf::Font::~Font()]+0x5b): undefined reference to `sf::Image::~Image()'..\..\ElementGames\Batext$_ZN2sf4FontD1Evse\libegbase.a(Font.cpp.obj):Font.cpp:(.[sf::Font::~Font()]+0x89): undefined reference to `sf::Image::~Image()'..\..\ElementGames\Base\libeVertexBufferObject.cppgbase.a(VertexBufferObject.cpp.obj)::(.text+0x116): undefined reference to `__glewGenBuffersARB'..\..\ElementGames\Base\libeVertexBufferObject.cppgbase.a(VertexBufferObject.cpp.obj)::(.text+0x139): undefined reference to `__glewBindBufferARB'..\..\ElementGames\Base\libeVertexBufferObject.cppgbase.a(VertexBufferObject.cpp.obj)::(.text+0x153): undefined reference to `__glewBindBufferARB'..\..\ElementGames\Base\libeVertexBufferObject.cppgbase.a(VertexBufferObject.cpp.obj)::(.text+0x249): undefined reference to `__glewGenBuffersARB'..\..\ElementGames\Base\libeVertexBufferObject.cppgbase.a(VertexBufferObject.cpp.obj)::(.text+0x26f): undefined reference to `__glewBindBufferARB'..\..\ElementGames\Base\libeVertexBufferObject.cppgbase.a(VertexBufferObject.cpp.obj)::(.text+0x28a): undefined reference to `__glewBindBufferARB'..\..\ElementGames\Base\libeVertexBufferObject.cppgbase.a(VertexBufferObject.cpp.obj)::(.text+0x380): undefined reference to `__glewGenBuffersARB'..\..\ElementGames\Base\libeVertexBufferObject.cppgbase.a(VertexBufferObject.cpp.obj)::(.text+0x3a6): undefined reference to `__glewBindBufferARB'..\..\ElementGames\Base\libeVertexBufferObject.cppgbase.a(VertexBufferObject.cpp.obj)::(.text+0x3c1): undefined reference to `__glewBindBufferARB'..\..\ElementGames\Base\libeVertexBufferObject.cppgbase.a(VertexBufferObject.cpp.obj)::(.text+0x4b7): undefined reference to `__glewGenBuffersARB'..\..\ElementGames\Base\libeVertexBufferObject.cppgbase.a(VertexBufferObject.cpp.obj)::(.text+0x4dd): undefined reference to `__glewBindBufferARB'..\..\ElementGames\Base\libeVertexBufferObject.cppgbase.a(VertexBufferObject.cpp.obj)::(.text+0x4f8): undefined reference to `__glewBindBufferARB'..\..\ElementGames\Base\libeVertexBufferObject.cppgbase.a(VertexBufferObject.cpp.obj)::(.text+0x5ee): undefined reference to `__glewGenBuffersARB'..\..\ElementGames\Base\libeVertexBufferObject.cppgbase.a(VertexBufferObject.cpp.obj)::(.text+0x614): undefined reference to `__glewBindBufferARB'..\..\ElementGames\Base\libeVertexBufferObject.cppgbase.a(VertexBufferObject.cpp.obj)::(.text+0x62f): undefined reference to `__glewBindBufferARB'..\..\ElementGames\Base\libeVertexBufferObject.cppgbase.a(VertexBufferObject.cpp.obj)::(.text+0x725): undefined reference to `__glewGenBuffersARB'..\..\ElementGames\Base\libeVertexBufferObject.cppgbase.a(VertexBufferObject.cpp.obj)::(.text+0x74b): undefined reference to `__glewBindBufferARB'..\..\ElementGames\Base\libeVertexBufferObject.cppgbase.a(VertexBufferObject.cpp.obj)::(.text+0x766): undefined reference to `__glewBindBufferARB'..\..\ElementGames\Base\libeVertexBufferObject.cppgbase.a(VertexBufferObject.cpp.obj)::(.text+0x85c): undefined reference to `__glewGenBuffersARB'..\..\ElementGames\Base\libeVertexBufferObject.cppgbase.a(VertexBufferObject.cpp.obj)::(.text+0x882): undefined reference to `__glewBindBufferARB'..\..\ElementGames\Base\libeVertexBufferObject.cppgbase.a(VertexBufferObject.cpp.obj)::(.text+0x89d): undefined reference to `__glewBindBufferARB'..\..\ElementGames\Base\libeVertexBufferObject.cppgbase.a(VertexBufferObject.cpp.obj)::(.text+0xa4b): undefined reference to `__glewBindBufferARB'..\..\ElementGames\Base\libeVertexBufferObject.cppgbase.a(VertexBufferObject.cpp.obj)::(.text+0xa6b): undefined reference to `__glewBindBufferARB'..\..\ElementGames\Base\libeVertexBufferObject.cppgbase.a(VertexBufferObject.cpp.obj)::(.text+0xa8c): undefined reference to `__glewBindBufferARB'..\..\ElementGames\Base\libeVertexBufferObject.cppgbase.a(VertexBufferObject.cpp.obj)::(.text+0xaad): more undefined references to `__glewBindBufferARB' follow..\..\ElementGames\Base\libeVertexBufferObject.cppgbase.a(VertexBufferObject.cpp.obj)::(.text+0xb46): undefined reference to `__glewBufferDataARB'collect2: ld returned 1 exit status | Don't know about SFML, but you need to add mingw32 before everything, and change glew32 to glew32s and add a definition of GLEW_STATIC before including GLEW (don't ask me why, it simply wont work without static linking in Windows).#define GLEW_STATIC#include <GL/glew.h>#include <other gl-related headers> ;Quote:and change glew32 to glew32s and add a definition of GLEW_STATIC before including GLEW (don't ask me why, it simply wont work without static linking in Windows).Not true, I have glew working with the dll on windows. Next to that, I'm also using glew in combination with sfml so that isn't a problem.The only thing I should note is that I'm using Visual studio 2008/2010 expressassainator ; I am trying to use libglew32s.a but I can't seem to find it. And glew doesn't provide mingw makefiles. Is there an easy way to compile the static version of the library? ; Not sure what issues you had with visual studio, but I can pretty much assure that you could get this working in 10 minutes on VC++. A lot more people around here use it and could probably help you too, more than mingw anyway.Up to you what you want to do though :\ ; In the mingw glew lib I downloaded that was precompiled, I found that libglew32.dll.a was actually the static lib, and to solve my other linker errors, I actually linked everything twice for now in my link line in the CMakeLists.txt file until I figure out the exact proper link order.Thanks for everyone's help. |
Can someone help me create a proper perspective matrix? | Graphics and GPU Programming;Programming | Hello. Basically, I have a situation where the person is not going to be sitting directly in front of the screen, but rather off to the side, viewing it at an angle. Here is a top-down view: So, the person would be facing 'up' in this image (although I'm not sure how much that matters).What I'd like to do is set up my projection matrix so that things look correct from this person's point of view. I basically want the TV screen to look like a window into the game world. I guess what I'm wondering is, if I have the measurements of where the person is sitting in relation to the TV, can I use them to construct a perspective matrix that represents the sort of skewed frustum like the red one in the image?I'm using OpenGL, incidentally. | I think you can make it work if you use something like what's described here: http://msdn.microsoft.com/en-us/library/bb205354%28VS.85%29.aspx. You'll just need to do a little trig to figure out the extents of the far clipping plane based on the angle. ; So would this be a proper way to visualize it, i.e. with the coordinate space oriented such that the x-axis is perpendicular to the screen, and the top/left/bottom/right coords are the corners of the far plane?; Yes, exactly. With that orientation you just need to figure out the X values of the two far corners, as well as the Y values. Then you can build your off-center projection. |
Perforce | For Beginners | I got Perforce yesterday to do version control. I've been using it all morning on a project I'm working on, and now I want to back up my changes. Is there an easy way to back up your Perforce database? I just want to e-mail myself a zip backup.I found this:http://www.perforce.com/perforce/r10.1/manuals/p4sag/02_backup.html#1043336However, it looks very complicated and uses a command-line interface. Isn't there something simpler that uses the GUI? | |
Visual Studio Projects directory | For Beginners | Oftentimes, I've wanted to take the important stuff in my Visual Studio Projects directory and back it up.However, Visual Studio mixes a lot of gunk in with your important stuff (i.e. gigantic NCB files).Then, if you try to zip the Projects dir, the gunk makes your zip large, and you can't e-mail it to yourself.Has anyone found a good solution? (i.e. a program that only zips .sln, .vcproj, .h, and .cpp files) | You can just delete the .ncb file, then zip it. It's something like the compiled intellisense database, and it will rebuild the next time you open the project.Or you could probably do some command line trickery, though I'm inexperienced with windows command line. Unix would be something like "find . | grep (\.sln|\.vcproj|\.h|\.cpp) > MyZipProgram " Maybe you can figure out what the windows equivalent of that would be. ; If you're using a version control system (you should!), then just add these files to the ignore list. If you need a backup, backup the repository itself. |
Cg or HLSL? | Graphics and GPU Programming;Programming | In the opnion of you which is better? Cg or HLSL?What should I study?I looked for the differences between them on google, but found nothing that answered my doubtsthanks | HLSL is used only for Direct3D, and hence is specific to DirectX. Cg is cross platform and can be used on Direct3D or OpenGL, which gives you more options.However, I'm not sure how up to date Cg is or what advanced features it has. The DXSDK is updated normally every 4 months or so, making it an attractive target for development. If you are using Direct3D you should probably stick with HLSL, if you are using OpenGL, you either need to use GLSL or Cg. ;Quote:Original post by Jason ZThe DXSDK is updated normally every 4 months or so, making it an attractive target for development. If you are using Direct3D you should probably stick with HLSLamazing :DThanksand what better book to learn HLSL? |
Recursive and iteration | For Beginners | Hi, a need some help on this. I need to use the recursive version to create an iteration version but I just cant get it right...Thanks you!#include <iostream>using namespace std;int recusion(int);int iteration(int);int main (){int n;cout << "Enter a integers: ";cin >> n;cout << recusion(n);cout << endl;cout << iteration(n);cout << endl;}int recusion(int n){if(n == 1)return 3;else if(n == 2)return 2;elsereturn recusion(n - 2) + recusion(n - 1);}int iteration(int n){int pCur = 0;int pNext = 0;int pOld = 0;int i = 2;while(i <= n){if(i == 1){pNext += 3;pCur = 3;if (n == 1)return pCur;}else if(i == 2){pNext += 2; pCur = 2;if (n == 2)return pCur;} elsepNext = pCur + pOld;pOld = pCur;pCur = pNext; i++;}return pCur;} [Edited by - Zahlman on November 20, 2010 2:30:12 AM] | Quote:Original post by TongieI need to use the recursive version to create an iteration versionWhat does that even mean?; I think he means he needs to change a recursive function into a non-recursive function. ; Well it's doubly-recursive, not simply tail-recursive so it's not as straightforward as converting the recursion into a loop.However by recognising that it is simply a variation of the fibonacci sequence, one can easily convert it to an iterative function.please use [source][/source] tags around your code. ; The first step is to identify what the recursive function is doing. In this case, it is returning the sum of itself being called on n-1 and n-2. Since we have two base cases, we know we're looking at a recursive sum function.Please look up http://en.wikipedia.org/wiki/Fibonacci_number ; This is very easy:int iteration(unsigned n) { int a = 1, b = 0, x = 0, y = 1; for (; n; n >>= 1) { if (n & 1) { int t = a*x + b*y; b = a*y + b*(x + y); a = t; } int t = x*x + y*y; y = x*y + y*(x + y); x = t; } return 3*b - a;} |
[C++, Win32] How to make buttons stay down | General and Gameplay Programming;Programming | Hey guys !I'm working on an application where I want certain buttons to stay down after I've pushed them, a sort of toggle effect which persists even when I go on to focus other windows in the application. I create the buttons using CreateWindowEx() with "button" as the class name as I guess most would expect, and I've tried to control the button state with Button_SetState() any time the button is identified in a WM_COMMAND message. However this doesn't work quite the way I had hoped as the button gets reset anytime I switch focus to another window (within the same window) and sometimes the button isn't pushable at all.Is there any straight-forward solution to my problem, I would much appreciate any advice.- Dave | Well, what you want is a the behavior of a checkbox but the appearance of a button. I have never tried this in pure Windows API but I would try to retrieve the WndProc for a button and checkbox class and write a new WndProc for my custom button class which forwards everything except painting related messages (not sure if WM_PAINT is enough) to the checkbox WndProc and the painting messages to the button WndProc. ;BS_PUSHLIKE will give a button that looks like a normal button but behaves like a checkbox. ; Ah, using the style BS_AUTOCHECKBOX | BS_PUSHLIKE | WS_CHILD | WS_VISIBLE did the trick. Thanks guys ! |
Newb with questions | For Beginners | I'm a newbie with some questions. I'll preface the rest of this post by saying that I'm a COMPLETE newbie and I get easily confused. Some of my questions might not make sense b/c I don't know what I'm talking about! I'm currently learning C++ and will move to beginning game programming after that. I know I'm probably jumping ahead of myself with all of this game stuff b/c I don't even know enough C++ yet, but the reason I'm asking now is that I'm about to purchase a new laptop and I'm trying to decide on the specs for it. I'm probably going to get a book like Jonathan Harbour's Beginning Game Programming to get an introduction into game programming and DirectX. My first question is: Would the DirectX code from an introductory book like this work with both DirectX 9.0c and DirectX 11? My current laptop is running XP and DirectX 9.0c. while my new one would run DirectX 11. I understand some features (code?) have been deprecated from 9.0c. I don't want to learn something that is obsolete.My next question is about Windows 7. 64 bit is being pushed pretty hard (at least by Dell and Best Buy) from what I can tell. How different is programming 32 bit Windows and 64 bit? Would 32 bit code work in 64 bit? Is 64 bit a lot harder to learn? Also, would 32bit code in XP work in 32bit Windows 7? My concern is about whatever books/tutorials I read. Since I know NOTHING about Windows programming, I would really prefer to make sure the books I get work with whatever OS my new laptop has.I guess to sum up my first few questions: Would Jonathan Harbour's Beginning Game Programming (or other similar beginning books) work with 64 bit Windows 7 running DirectX 11? Would they run with 32 bit Windows 7 running DirectX 11? Would I be better off sticking with XP? Are there "better" (I know it's subjective) learning resources than the aforementioned book? Thanks for any help, and sorry for the long post. | IMO it sounds like you are devoting too much attention to the graphics API you will be using. If you don't know anything about coding or graphics, than it really doesn't matter what API you use. 95% of graphics programming is exactly the same whether you're using DX9, DX11, OpenGL, or a software rasterizer. Once you learn the basics, you should be able to switch from one api to another with relative ease.Focus on the concepts, not the API. You can pick the one that you like based on what you've got to work with, but don't throw your book away because it uses DX9 and you wanted DX11. The fundamentals are the same, and no matter what API you work in you will be gaining valuable knowledge. ; Thank you for the reply. That is very helpful to know that the fundamentals are the same for DX. Also good to know other API's should be easy to grasp when I learn the basics. Do you know if "basic" code for 32bit Windows is the same for 64bit? I guess would an introductory book/tutorial for 32bit and 64bit be the same? ; Yes they should be essentially the same from a programming point of view. |
AABB - Sphere collisions | For Beginners | Hi,I've been playing around with this a bit and Im at a bit of a loss. Ive got my sphere - box collision and response working but the sphere will slip between 2 boxes that are next to each other and stop. I want it to roll smoothly over the top of the boxes. Here is some code - Collision Detection[Source]bool BoundingBox::Intersects(BoundingSphere* checkSphere){Vector3f circleDistance;circleDistance.x = fabs(checkSphere->GetPosition().x - position.x); circleDistance.y = fabs(checkSphere->GetPosition().y - position.y); if (circleDistance.x > (dimensions.x * 0.5f + checkSphere->radius)) { return false; } if (circleDistance.y > (dimensions.y * 0.5f + checkSphere->radius)) { return false; } if (circleDistance.x <= (dimensions.x * 0.5f)) { return true; }if (circleDistance.y <= (dimensions.y * 0.5f)) { return true; } float cornerDistance_sq = (circleDistance.x - dimensions.x * 0.5f) * (circleDistance.x - dimensions.x * 0.5f) +(circleDistance.y - dimensions.y * 0.5f) * (circleDistance.y - dimensions.y * 0.5f); return (cornerDistance_sq <= (checkSphere->radius * checkSphere->radius));}[/Source]Collision response[Source]float damping = 0.3f;//Collision occured - check which direction to bounce inif ((pMarble->GetPosition().x > pWall->GetPosition().x + pWall->GetDimensions().x * 0.5f && pMarble->GetVelocity().x < 0) || (pMarble->GetPosition().x < pWall->GetPosition().x - pWall->GetDimensions().x * 0.5f && pMarble->GetVelocity().x > 0)){//Collision in x direction pMarble->GetPosition().x -= (pMarble->GetVelocity().x * stepTime);pMarble->GetVelocity().x = -pMarble->GetVelocity().x * damping; }else if ((pMarble->GetPosition().y > pWall->GetPosition().y + pWall->GetDimensions().y * 0.5f && pMarble->GetVelocity().y < 0) || (pMarble->GetPosition().y < pWall->GetPosition().y - pWall->GetDimensions().y * 0.5f && pMarble->GetVelocity().y > 0)){//Collision in y directionpMarble->GetPosition().y -= (pMarble->GetVelocity().y * stepTime);pMarble->GetVelocity().y = -pMarble->GetVelocity().y * damping;}[/Source]Any help is much appreciated, thanks. | |
Team Positions and Proper Compensation | Games Business and Law;Business | Hi guys,(I want to clarify that I am no expert on this and I am not attempting to lay down any laws. Rather, I intend to provide food for thought or helpful hints. Nothing more. Nothing anyone has been doing here is wrong by any means, but some things could always afford to be tightened up - so to speak.)I have noticed that a large portion of companies/individuals posting their jobs request a considerable proportion of work from a prospective applicant but offer pittance or no compensation for their contribution. Those posting these job offers then have to bump their post dozens of times and never receive any real interest.I do understand this, as I am currently searching for a pixel artist for a multiplayer indie game. That condition makes it difficult to find proper candidates. However, I feel that a fair amount of these job postings could follow some simple guidlines to increase productivity and sucess rates.Hints:1. Use proper English - spelling, grammar, and punctuation. Nothing turns me off more than this, and I am very guilty of it. Read and reread your post and correct these errors or you may find yourself bumping... bumping... and bumping some more. This is especially heinous with all of the spell-checking programs available today. (P.S. I am attempting this post entirely without a program that can spell check. Hopefully I am practicing what I preach.)2. Follow the guidlines! I notice that a large number of job postings do not read the posting guidlines or use the template properly. This makes your position appear less desirable as it suggest a lack of discipline and therefore a lack of power in controlling a team or successfully being a part of a team.3. Be friendly - be an open book! Too many job postings are incredibly vague on what they require, the point of the game they are making, and the desired conclusion to their products completion. The more an applicant knows, the more they can be interested in joining your team.4. Sell yourself and your company! If you make it seem as if your game is wandering aimlessly in the general direction of "completion", then you will likely cause prospective applicants to wander aimlessly away from your job offer. Make sure your game appears as if there is a concrete an legitimate chance of it surviving "flaky devotion" and incosistent or unreliable teamates.Compensation:This is the most chronic issue I have encountered in job postings that I feel deserves its own breakdown.-This assumes that positions are not salaried and instead are justified by profits and royalties.-Small flash games that one would find on Addicting Games etc, do not require paying the involved parties. This makes sense as the scope of the product is limited and no profit will be made.Small Game for IPHONE: (Low Price/Medium Price; Free programs could be likened to the small flash games previously mentioned.)Programmer: This position most likely will require the greatest contribution in this kind of game. Since marketing will likely be non-existent. Expect to offer 35-50 percent of the profits.Artist/Animator: This postion will require the next chunk of work for a game of this type. Expect to offer up to 30 percent of the profits.Composer: The music for these games can be simple and repetitive. Obviously, you will get what you pay for, but expect to pay up to roughly 15 percent of the profits at most.Small Game for Computer: (Low Price/Free to Play)Programmer: These guys will likely require some form of compensation. Despite whether or not you are recieving funds for the game, do not expect much response to an ad that involves making a fairly complex game - offering nothing but credit in return.Artist/Animator: Very few skilled artists and animators offer their talent in exchange for nothing. This is because of the nature of what they do. They enjoy it, but it is very time consuming and often tedious. If they have a full-time job on the side, it is impossible to expect them to carry the work load of an entire game for free.Composer: These games often have insignificant SFX and Composition. This or they are of low quality. If you are alright with lower quality work, you can find a free composer for games like this. If you want more, you will need to pay something, royalties or out-of-pocket. Remember, you - the designer - are getting the majority of "biz credit" for completing the game successfully. The composer gets very little for this credit. Therefore, they will need something else to justify this work (namely a little of your cash).Writer: The writer often fills one of the previous positions as well. If you acquire a freelance writer, pittance for profit is acceptable. They gain most by the credit they recieve for a project such as this.Medium Sized Game involving Multiplayer or Extended Campaign for Computer or Xbox Live: (Fair Price on Product)Programmer: These guys will be doing a significant amount of work, but not as much in comparison to their counterparts working on smaller games. (Allow me to use an analogy. The reason a single cell can only be so large is because of its surface area to volume ratio. Pretend that the programmer is the cell membrane, and everybody else makes up the volume of the cell, kept in place by the programmer who packs everything together in neat, final package. As the volume of the team within the cell grows to accomodate a larger game, the cell membrane grows as well. HOWEVER, it grows at a much smaller pace than the volume. Therefore, while the team has expanded to become 4x as massive, the programmer [cell wall] has expanded only roughly 2x as large as it was originally to support the growing team [volume].) Therefore, the programmers can expect less of a percentage from his/her work on this type of game (But the game makes more money so it is a win-win situation). Expect to offer roughly 20 percent of the profits to a hard working programmer.Designer: The designer has done some considerable work on a project of this type and finally warrants notice. They will also be in charge of the finances and unit cohesion. They will command roughly 20% of the profit to give leeway in negotiations.Artist/Animator: They will be doing possibly the largest portion of work on a game such as this. They should expect 25-40 percent of the profits based on skill and experience.Composer: Music in these games is often a significantly more quality job than the previously listed conditions. Expect to pay an absolute minimum of 10% to a composer. Writer: A writer in this type of game is most often also the designer. If you hire a free lance writer, a low proportion of the profits in the single digits of percent is fair. They gain most from the credit recieved working on this project.RPG or MMORPG:Programmer: As with the previous instance, programmers will be doing a significant amount of work. For such a large game as this, expect to pay up to 25-40 percent to a single programmer or a portion of that to multiple ones.Designer: The designer has likely done considerable work on this project and devoted a lot of time to it. Expect him to demand up to 30% of the profits.Artist/Animator: A lot of the work done in these games by an animator is redundant, thus lowering their overall impact on the game. They should expect 20-35 percent of the profits based on skill and experience.Composer: Music in these games is often high quality work, but also redundant. The composer will still demand roughly 10-25 percent of the profits.Writer: The lead writer of this type of game is also a designer in most cases. Additional writers can expect to justify, at most, 10 percent of the profits. Under 5 percent is fair in most cases. The majority of the reward for writing in this type of project is credit.**********Hope some of this helps in representing yourself to the world and acquiring quality help on your project. Please let me know if I am in error on any of the points I have made.Thanks,Tim[Edited by - Assyranok on November 20, 2010 12:04:43 AM] | I understand where you're coming from and I agree with your hints; however, your compensation breakdowns are too full of generalities. You also aren't taking into account that, in most games (especially MMOs and larger projects), there are multiple people programming and developing assets.And what is wrong with teams seeking people to work for free if the workers are willing to do so (and aren't being deceived in any matter)?The major issue I see with the job requests here is that the companies and individuals don't attempt to sell themselves to prospective team members. I read a lot of the Help Wanted posts and all I see is a lack of directness and confidence. When they can't offer something (such as compensation or previous work), they play it defensively and try to appease the reader. My advice is to be direct and confident: "Compensation: This is an unpaid position. We provide benefits such as networking, references, <insert free/low-cost perks here>. You don't have to be rich, you don't have to have industry experience--just SELL yourself to the reader. ; You also aren't taking into account that, in most games (especially MMOs and larger projects), there are multiple people programming and developing assets.And what is wrong with teams seeking people to work for free if the workers are willing to do so (and aren't being deceived in any matter)?============================================================If you will notice, I do indeed take that into account. And I never said there was anything wrong with it at all. But some people seem to assume that searching for people in these positions with no compensation should be easier than it actually is. I post this just to help some understand that they shouldn't expect very many responses for what they might be looking for. Some people bump their post every few days because of this.Was hoping to supply some helpful hints, not lay down a law.Also, I like your comment. Mind if I add that to the list of general hints? (With credit of course.) ;Quote:Original post by AssyranokIf you will notice, I do indeed take that into account. And I never said there was anything wrong with it at all. But some people seem to assume that searching for people in these positions with no compensation should be easier than it actually is. I post this just to help some understand that they shouldn't expect very many responses for what they might be looking for. Some people bump their post every few days because of this.Was hoping to supply some helpful hints, not lay down a law.Also, I like your comment. Mind if I add that to the list of general hints? (With credit of course.)I see, I must have misunderstood you. I saw it as you're trying to give 50% to a programmer but there could be multiple programmers. I didn't consider splitting 50% between those programmers.You can add my comment to the list of hints and wherever else you feel like posting. However, I would prefer not to be credited. |
SVG in games | General and Gameplay Programming;Programming | I've sure have been posting questions on GDNet often lately. I must be failing as a programmer! ;) Anyway, I'm currently developing a 2D game on three major computer platforms (Win32, OSX/Cocoa, Unix/X11), but I may want to port it to mobile devices (Android, iPhone, PSP, etc) later on. Some of these systems, especially iPhone 4 at 326 DPI, have ridiculously high resolution. 32x32 tiles would be FAR too tiny on such screens! My first thought was to scale the same static graphics to a more managable size, which would result in blocky graphics.I've been considering using a vector format for in-game graphics, which would prevent ugliness on high DPI screens. I'm having trouble finding a suitable format. I've been studying W3C's SVG format, but it appears bloated and packed with thousands of features I would never use, even in the SVG Tiny profile. What I'm looking for is a static graphic without animation or interaction. One way around this could be using SVG, but prerendering graphics as they appear initially, before any sort of interaction.So it looks like I have 3 options:1. Use a minimal subset of SVG features.2. Find or develop a simpler format that suits my goal.3. Revert to my original plan of using pixmap graphics.What are your thoughts on the situation? Any help is appreciated.EDIT: Looks like I can't count to 3![Edited by - Daggerbot on November 17, 2010 10:30:49 AM] | Creating your own vectorial format is easier than using a complex one like SVG, especially since your probably want only a list of 2d points forming polygon shapes.What's harder is to use a good graphic library available on all those platforms which allow you to draw polygons, and not just rectangular surfaces. I had this problem before, SDL only allow rectangular surface and DirectX/OpenGL needs triangle list, not polygons, so you have to "triangulize" the polygons so they get rendered as a bunch of triangles. With SFML though, you can draw shapes directly the way you want it. ; If there is no animation or sizing at runtime, why not draw in a vectorformat (whatever format/drawing program fits you) and render these images to bitmaps for the platforms/DPIs? Implementing a vector format is a lot of work. ;Quote:Creating your own vectorial format is easier than using a complex one like SVG, especially since your probably want only a list of 2d points forming polygon shapes.What's harder is to use a good graphic library available on all those platforms which allow you to draw polygons, and not just rectangular surfaces. I had this problem before, SDL only allow rectangular surface and DirectX/OpenGL needs triangle list, not polygons, so you have to "triangulize" the polygons so they get rendered as a bunch of triangles. With SFML though, you can draw shapes directly the way you want it.What I was thinking is more along the lines of rendering the graphic to a texture a load time, then rendering the texture when the graphic is needed. Scaling wouldn't be possible, but that's not a huge problem.Quote:If there is no animation or sizing at runtime, why not draw in a vectorformat (whatever format/drawing program fits you) and render these images to bitmaps for the platforms/DPIs?Implementing a vector format is a lot of work.I was hoping to use a single data archive that would be used by the game on all platforms, but I will probably end up doing what you mentioned instead. Keeping a separate data profile for each system would be far more easy than writing a vector graphics renderer. ; You would still have a single data archive except that you generate different sets of bitmaps from it. Just like compiling the same C code for different platforms, one code base. ;Quote:Original post by DungeCreating your own vectorial format is easier than using a complex one like SVG, especially since your probably want only a list of 2d points forming polygon shapes.A custom format would make it easier to load assets into your game (I tried writing an SVG parser once; SVG is a monster). But now you have to create an export plugin for Illustrator or Inkscape or whatever you're using to create these vector images. Which would not be that unusual (most 3D games use their own model format) but it's still something you have to keep in mind.Best of luck to you. I would really like to see more 2D games that use vector graphics (without Flash). ;Quote:Original post by VideroBoyQuote:Original post by DungeCreating your own vectorial format is easier than using a complex one like SVG, especially since your probably want only a list of 2d points forming polygon shapes.A custom format would make it easier to load assets into your game (I tried writing an SVG parser once; SVG is a monster). But now you have to create an export plugin for Illustrator or Inkscape or whatever you're using to create these vector images. Which would not be that unusual (most 3D games use their own model format) but it's still something you have to keep in mind.Best of luck to you. I would really like to see more 2D games that use vector graphics (without Flash).Another option is instead of writing a plugin to programs, write a small command line program that parses the SVG tree and outputs a file in your format. |
[Win32] Get absolute path of current directory | Graphics and GPU Programming;Programming | Hi, you know how you can specify relative paths like "textFile.txt"?How do I get the absolute path that the relative path pulls from? (like "C:/MyProject/" or "C:/MyProject/textFile.txt") | For Win32, you can use GetCurrentDirectory or GetFullPathName. ;Quote:Original post by Erik RufeltFor Win32, you can use GetCurrentDirectory or GetFullPathName.Thanks :) |
[C++, DX9] Failed Bloom attempt | Graphics and GPU Programming;Programming | I tried to add Bloom based off DirectX sample. However for some reason it's badly pixelated (unlike in DirectX demo).Screenshots of bug:http://dl.dropbox.com/u/2637453/bloom/topview.jpghttp://dl.dropbox.com/u/2637453/bloom/rotated.jpgMy shader code:float2 PixelCoordsDownFilter[16] ={{ 1.5, -1.5 },{ 1.5, -0.5 },{ 1.5, 0.5 },{ 1.5, 1.5 },{ 0.5, -1.5 },{ 0.5, -0.5 },{ 0.5, 0.5 },{ 0.5, 1.5 },{-0.5, -1.5 },{-0.5, -0.5 },{-0.5, 0.5 },{-0.5, 1.5 },{-1.5, -1.5 },{-1.5, -0.5 },{-1.5, 0.5 },{-1.5, 1.5 },};float2 TexelCoordsDownFilter[16]<string ConvertPixelsToTexels = "PixelCoordsDownFilter";>;texture textureBloom;sampler2D textureBloomSampler = sampler_state{Texture = <textureBloom>;AddressU = Clamp;AddressV = Clamp;MINFILTER = Point;MIPFILTER = Linear;MAGFILTER = Linear;};texture textureScene;sampler2D textureSceneSampler = sampler_state{Texture = <textureScene>;AddressU = Clamp;AddressV = Clamp;MINFILTER = Point;MIPFILTER = Linear;MAGFILTER = Linear;};float4 DownFilter(in float2 Tex : TEXCOORD0) : COLOR0{float4 Color = 0;for (int i = 0; i < 16; i++){Color += tex2D(textureBloomSampler, Tex + TexelCoordsDownFilter.xy);}return Color / 16;}float Luminance = 0.08f;static const float fMiddleGray = 0.18f;static const float fWhiteCutoff = 0.8f;float4 BrightPassFilter(in float2 Tex : TEXCOORD0) : COLOR0{float3 ColorOut = tex2D(textureBloomSampler, Tex);;ColorOut *= fMiddleGray / (Luminance + 0.001f);ColorOut *= ( 1.0f + (ColorOut / (fWhiteCutoff * fWhiteCutoff)));ColorOut -= 5.0f;ColorOut = max(ColorOut, 0.0f);ColorOut /= (10.0f + ColorOut);return float4(ColorOut, 1.0f);}static const int g_cKernelSize = 13;float2 PixelKernel[g_cKernelSize] ={{ -6, 0 },{ -5, 0 },{ -4, 0 },{ -3, 0 },{ -2, 0 },{ -1, 0 },{ 0, 0 },{ 1, 0 },{ 2, 0 },{ 3, 0 },{ 4, 0 },{ 5, 0 },{ 6, 0 },};float2 TexelKernel[g_cKernelSize]<string ConvertPixelsToTexels = "PixelKernel";>;static const float BlurWeights[g_cKernelSize] = {0.002216,0.008764,0.026995,0.064759,0.120985,0.176033,0.199471,0.176033,0.120985,0.064759,0.026995,0.008764,0.002216,};float BloomScale = 1.5f;float4 BlurHFilter(float2 Tex : TEXCOORD0) : COLOR0{float4 Color = 0;for (int i = 0; i < g_cKernelSize; i++){Color += tex2D(textureBloomSampler, Tex + TexelKernel.xy) * BlurWeights;}return Color * BloomScale;}float4 BlurVFilter(float2 Tex : TEXCOORD0) : COLOR0{float4 Color = 0;for (int i = 0; i < g_cKernelSize; i++){ Color += tex2D(textureBloomSampler, Tex + TexelKernel.yx) * BlurWeights;}return Color * BloomScale;}float4 UpFilter(float2 Tex : TEXCOORD0) : COLOR0{return tex2D(textureBloomSampler, Tex);}float4 CombineFilter(float2 Tex : TEXCOORD0) : COLOR0{float3 ColorOrig = tex2D(textureSceneSampler, Tex);ColorOrig += tex2D(textureBloomSampler, Tex);return float4(ColorOrig, 1.0f);}technique Bloom{pass p0{VertexShader = null;ZEnable = false;PixelShader = compile ps_2_0 DownFilter();}pass p1{VertexShader = null;ZEnable = false;PixelShader = compile ps_2_0 BrightPassFilter();}pass p2{VertexShader = null;ZEnable = false;PixelShader = compile ps_2_0 BlurHFilter();}pass p3{VertexShader = null;ZEnable = false;PixelShader = compile ps_2_0 BlurVFilter();}pass p4{VertexShader = null;ZEnable = false;PixelShader = compile ps_2_0 UpFilter();}pass p5{VertexShader = null;ZEnable = false;PixelShader = compile ps_2_0 CombineFilter();}}Code to use the shader:void RenderBloom(){shader->SetTechnique("Bloom");const D3DSURFACE_DESC* desc = DXUTGetD3D9BackBufferSurfaceDesc();float Height = (float)desc->Height;float Width = (float)desc->Width;float verts[] = {-0.5f, -0.5f, 0, 0, 0, 0,Width - 0.5f, -0.5f, 0, 0, 1, 0,-0.5f, Height - 0.5f, 0, 0, 0, 1,Width - 0.5f, Height - 0.5f, 0, 0, 1, 1,};uint passes;device->SetFVF(D3DFVF_XYZRHW | D3DFVF_TEX1);{// down filter 4xdevice->SetRenderTarget(0, surfacePass2);device->Clear(0, 0, D3DCLEAR_TARGET | D3DCLEAR_ZBUFFER, D3DCOLOR_ARGB(0, 0, 0, 0), 1, 0);shader->SetTexture(shaderTextureBloom, textureScene);float verts[] = {-0.5f, -0.5f, 0, 0, 0, 0,Width * 0.25f - 0.5f, -0.5f, 0, 0, 1, 0,-0.5f, Height * 0.25f - 0.5f, 0, 0, 0, 1,Width * 0.25f - 0.5f, Height * 0.25f - 0.5f, 0, 0, 1, 1,};shader->Begin(&passes, 0);shader->BeginPass(0);device->DrawPrimitiveUP(D3DPT_TRIANGLESTRIP, 2, verts, sizeof(float) * 6);shader->EndPass();shader->End();}{// down filter 4xdevice->SetRenderTarget(0, surfacePass1);device->Clear(0, 0, D3DCLEAR_TARGET | D3DCLEAR_ZBUFFER, D3DCOLOR_ARGB(0, 0, 0, 0), 1, 0);shader->SetTexture(shaderTextureBloom, texturePass2);float verts[] = {-0.5f, -0.5f, 0, 0, 0, 0,Width * 0.25f - 0.5f, -0.5f, 0, 0, 1, 0,-0.5f, Height * 0.25f - 0.5f, 0, 0, 0, 1,Width * 0.25f - 0.5f, Height * 0.25f - 0.5f, 0, 0, 1, 1,};shader->Begin(&passes, 0);shader->BeginPass(0);device->DrawPrimitiveUP(D3DPT_TRIANGLESTRIP, 2, verts, sizeof(float) * 6);shader->EndPass();shader->End();}{// brightpassdevice->SetRenderTarget(0, surfacePass2);device->Clear(0, 0, D3DCLEAR_TARGET | D3DCLEAR_ZBUFFER, D3DCOLOR_ARGB(0, 0, 0, 0), 1, 0);shader->SetTexture(shaderTextureBloom, texturePass1);shader->Begin(&passes, 0);shader->BeginPass(1);device->DrawPrimitiveUP(D3DPT_TRIANGLESTRIP, 2, verts, sizeof(float) * 6);shader->EndPass();shader->End();}{// blur horizontaldevice->SetRenderTarget(0, surfacePass1);device->Clear(0, 0, D3DCLEAR_TARGET | D3DCLEAR_ZBUFFER, D3DCOLOR_ARGB(0, 0, 0, 0), 1, 0);shader->SetTexture(shaderTextureBloom, texturePass2);float verts[] = {-0.5f, -0.5f, 0, 0, 0, 0,Width * 0.0625f - 0.5f, -0.5f, 0, 0, 0.0625f, 0,-0.5f, Height * 0.0625f - 0.5f, 0, 0, 0, 0.0625f,Width * 0.0625f - 0.5f, Height * 0.0625f - 0.5f, 0, 0, 0.0625f, 0.0625f,};shader->Begin(&passes, 0);shader->BeginPass(2);device->DrawPrimitiveUP(D3DPT_TRIANGLESTRIP, 2, verts, sizeof(float) * 6);shader->EndPass();shader->End();}{// blur verticaldevice->SetRenderTarget(0, surfacePass2);device->Clear(0, 0, D3DCLEAR_TARGET | D3DCLEAR_ZBUFFER, D3DCOLOR_ARGB(0, 0, 0, 0), 1, 0);shader->SetTexture(shaderTextureBloom, texturePass1);float verts[] = {-0.5f, -0.5f, 0, 0, 0, 0,Width * 0.0625f - 0.5f, -0.5f, 0, 0, 0.0625f, 0,-0.5f, Height * 0.0625f - 0.5f, 0, 0, 0, 0.0625f,Width * 0.0625f - 0.5f, Height * 0.0625f - 0.5f, 0, 0, 0.0625f, 0.0625f,};shader->Begin(&passes, 0);shader->BeginPass(3);device->DrawPrimitiveUP(D3DPT_TRIANGLESTRIP, 2, verts, sizeof(float) * 6);shader->EndPass();shader->End();}{// blur horizontaldevice->SetRenderTarget(0, surfacePass1);device->Clear(0, 0, D3DCLEAR_TARGET | D3DCLEAR_ZBUFFER, D3DCOLOR_ARGB(0, 0, 0, 0), 1, 0);shader->SetTexture(shaderTextureBloom, texturePass2);float verts[] = {-0.5f, -0.5f, 0, 0, 0, 0,Width * 0.0625f - 0.5f, -0.5f, 0, 0, 0.0625f, 0,-0.5f, Height * 0.0625f - 0.5f, 0, 0, 0, 0.0625f,Width * 0.0625f - 0.5f, Height * 0.0625f - 0.5f, 0, 0, 0.0625f, 0.0625f,};shader->Begin(&passes, 0);shader->BeginPass(2);device->DrawPrimitiveUP(D3DPT_TRIANGLESTRIP, 2, verts, sizeof(float) * 6);shader->EndPass();shader->End();}{// blur verticaldevice->SetRenderTarget(0, surfacePass2);device->Clear(0, 0, D3DCLEAR_TARGET | D3DCLEAR_ZBUFFER, D3DCOLOR_ARGB(0, 0, 0, 0), 1, 0);shader->SetTexture(shaderTextureBloom, texturePass1);float verts[] = {-0.5f, -0.5f, 0, 0, 0, 0,Width * 0.0625f - 0.5f, -0.5f, 0, 0, 0.0625f, 0,-0.5f, Height * 0.0625f - 0.5f, 0, 0, 0, 0.0625f,Width * 0.0625f - 0.5f, Height * 0.0625f - 0.5f, 0, 0, 0.0625f, 0.0625f,};shader->Begin(&passes, 0);shader->BeginPass(3);device->DrawPrimitiveUP(D3DPT_TRIANGLESTRIP, 2, verts, sizeof(float) * 6);shader->EndPass();shader->End();}{// up filter 16xdevice->SetRenderTarget(0, surfacePass1);device->Clear(0, 0, D3DCLEAR_TARGET | D3DCLEAR_ZBUFFER, D3DCOLOR_ARGB(0, 0, 0, 0), 1, 0);shader->SetTexture(shaderTextureBloom, texturePass2);float verts[] = {-0.5f, -0.5f, 0, 0, 0, 0,Width * 16 - 0.5f, -0.5f, 0, 0, 1, 0,-0.5f, Height * 16 - 0.5f, 0, 0, 0, 1,Width * 16 - 0.5f, Height * 16 - 0.5f, 0, 0, 1, 1,};shader->Begin(&passes, 0);shader->BeginPass(4);device->DrawPrimitiveUP(D3DPT_TRIANGLESTRIP, 2, verts, sizeof(float) * 6);shader->EndPass();shader->End();}{// combinedevice->SetRenderTarget(0, surfaceBackbuffer);device->Clear(0, 0, D3DCLEAR_TARGET | D3DCLEAR_ZBUFFER, D3DCOLOR_ARGB(0, 0, 0, 0), 1, 0);shader->SetTexture(shaderTextureBloom, texturePass1);shader->SetTexture(shaderTextureScene, textureScene);shader->Begin(&passes, 0);shader->BeginPass(5);device->DrawPrimitiveUP(D3DPT_TRIANGLESTRIP, 2, verts, sizeof(float) * 6);shader->EndPass();shader->End();}}If anymore information needed - let me know.Thank you in advance. | Just glancing over your code, it could be that you have set the MINFILTER for each sampler to POINT. Usually that makes any texture look horrible and pixelated, try changing it to LINEAR. ; I tried to change to Linear but nothing changed. DirectX sample has same settings for sampler.Here are my samplers:texture textureBloom;sampler2D textureBloomSampler = sampler_state{Texture = <textureBloom>;AddressU = Clamp;AddressV = Clamp;MINFILTER = Point;MIPFILTER = Linear;MAGFILTER = Linear;};texture textureScene;sampler2D textureSceneSampler = sampler_state{Texture = <textureScene>;AddressU = Clamp;AddressV = Clamp;MINFILTER = Point;MIPFILTER = Linear;MAGFILTER = Linear;};; Bump |
Bloom/HDR Performance Issues | Graphics and GPU Programming;Programming | Hello fellow game developers! I am developing a RTS game called Galactic Vice using OpenGL, and it requires Bloom/HDR to be implemented for various reasons (like the Lava effects shown here:). It looks amazing, but causes a HUGE performance drop!I went ahead an implemented it using the following pseudocode: -- BEGIN CODE -- // Render the 3D scene to a FBO3dScene_FBO[0]->begin(); render3D(renderPass_NORMAL);3dScene_FBO[0]->end();3dScene_FBO[1]->begin(); // Render previous FBO, using a bright shader // Anything greater in luminance than 0.95 is kept,// Everything else is set to black (0.0.3dScene_FBO[1]->end();3dScene_FBO[2]->begin(); // Render previous FBO, using a vertical blur shader (kernelsize = 8)3dScene_FBO[2]->end();// Reuse the bright-FBO3dScene_FBO[1]->begin(); // Render the previous FBO, using a horizontal blur shader (kernelsize = 8)3dScene_FBO[1]->end();// Render the 3D scene with the new bloom-FBO overlayedglClear(...);// Bind the bloom-FBO and 3D-scene FBO3dScene_FBO[0]->bind(0);3dScene_FBO[1]->bind(1);// Render using a shader that adds the two FBO values// cleanup3dScene_FBO[0]->unBind(0);3dScene_FBO[1]->unBind(1); -- END CODE -- Everything seems to look great! But, the problem is that the Bloom/HDR causes a 72% drop in the frame-rate (~110 FPS to ~30 FPS). Adjusting the kernel size of the blur makes little difference... I am doing the vertical and horizontal blurs separately as I should.... I am really not sure what could be causing this.So, does anyone know what could cause such a drastic drop in performance? Perhaps some ways I could optimize this? Thanks beforehand for any help! Here are my Bright & Blur shaders:Blur Shader: -- BEGIN CODE -- uniform sampler2D texScreen;uniform vec2 size;uniform bool horizontal;uniform int kernel_size;void main() {vec2 pas = 1.0 / size;vec2 uv = gl_TexCoord[0].st;vec4 color = vec4(0.0, 0.0, 0.0, 1.0);if(horizontal) {int j = 0;int sum = 0;for(int i = -kernel_size; i <= kernel_size; i++) {vec4 value = texture2D(texScreen, uv + vec2(pas.x*i, 0.0));int factor = kernel_size+1 - abs((float)i);color += value * factor;sum += factor;}color /= sum;} else {int j = 0;int sum = 0;for(int i = -kernel_size; i <= kernel_size; i++) {vec4 value = texture2D(texScreen, uv + vec2(0.0, pas.y * i));int factor = kernel_size + 1 - abs((float)i);color += value * factor;sum += factor;}color /= sum;}gl_FragColor.rgb = color;gl_FragColor.a = 1.0;} -- END CODE -- Bright shader: -- BEGIN CODE -- uniform sampler2D texScreen;void main() {vec3 color = texture2D(texScreen, gl_TexCoord[0].xy).rgb;if(((color.r * 0.299) + (color.g * 0.587) + (color.r * 0.114)) > 0.75) {gl_FragColor.rgb = color;} else {gl_FragColor.rgb = vec3(0.0, 0.0, 0.0);}gl_FragColor.a = 1.0;} -- END CODE -- | I think that performance drop could be caused by if-conditions and loops in your fragment shader. Try using 2 different shaders - one for vertical pass and one for horizontal pass - both WITHOUT any conditions and with unrolled loops.This is how my "vertical pass" blur fragment shader looks like:uniform sampler2D p_ScreenTexture;uniform float p_BlurSize;void main(void){ vec4 sum = vec4(0.0); sum += texture2D(p_ScreenTexture, vec2(gl_TexCoord[0].x, gl_TexCoord[0].y - 4.0 * p_BlurSize)) * 0.05; sum += texture2D(p_ScreenTexture, vec2(gl_TexCoord[0].x, gl_TexCoord[0].y - 3.0 * p_BlurSize)) * 0.09; sum += texture2D(p_ScreenTexture, vec2(gl_TexCoord[0].x, gl_TexCoord[0].y - 2.0 * p_BlurSize)) * 0.12; sum += texture2D(p_ScreenTexture, vec2(gl_TexCoord[0].x, gl_TexCoord[0].y - p_BlurSize)) * 0.15; sum += texture2D(p_ScreenTexture, vec2(gl_TexCoord[0].x, gl_TexCoord[0].y)) * 0.16; sum += texture2D(p_ScreenTexture, vec2(gl_TexCoord[0].x, gl_TexCoord[0].y + p_BlurSize)) * 0.15; sum += texture2D(p_ScreenTexture, vec2(gl_TexCoord[0].x, gl_TexCoord[0].y + 2.0 * p_BlurSize)) * 0.12; sum += texture2D(p_ScreenTexture, vec2(gl_TexCoord[0].x, gl_TexCoord[0].y + 3.0 * p_BlurSize)) * 0.09; sum += texture2D(p_ScreenTexture, vec2(gl_TexCoord[0].x, gl_TexCoord[0].y + 4.0 * p_BlurSize)) * 0.05; gl_FragColor = sum;}; Well that's not really that surprising. You can render your scene in a single pass in 9ms, but then you want to rerender the entire screen space 4 more times. 33ms doesn't seem that unreasonable.Given that these are all screen space passes from what I can tell, if you have a high resolution this is a lot of work to keep reading in and writing out the entire framebuffer so many times, so you'll want to try to cut this out where you can.Couple thoughts:I think using multiple render targets in your first pass would be a lot more efficient than a two pass write-read-write. You have all the information you need in the first pass to calculate the luminance (and it's not an expensive calculation), so why not just dump this to a second texture during the original pass. Also any time you can reduce the resolution of any of these secondary targets is going to be a big win for you. Bloom is by nature a very blurry effect, so maybe you could cut dimensions of your brightness/blur textures in half and do half as many blur samples? Assuming you're running at 1280x1024, if you could drop all the secondary targets to maybe 640x480 you're reducing your memory bandwidth requirements by 75%. When you're really currently streaming in and writing out the entire frame what looks like about 10 times per frame, this is really going to add up. You can play with different values to see what you can achieve and still look good.Nice looking effect btw! ; This is kind of counter-intuitive, but when I saw this it reminded me of an old GLSL tip that is on OpenGL.org. Don't know if it might help you at all, but might be worth a try.gl_FragColor.rgb = color;gl_FragColor.a = 1.0;Quote:Assignment with MADAssume that you want to set the output value ALPHA to 1.0. Here is one method : myOutputColor.xyz = myColor.xyz; myOutputColor.w = 1.0; gl_FragColor = myOutputColor;The above code can be 2 or 3 move instructions, depending on the compiler and the GPU's capabilities. Newer GPUs can handle setting different parts of gl_FragColor, but older ones can't, which means they need to use a temporary to build the final color and set it with a 3rd move instruction.You can use a MAD instruction to set all the fields at once: const vec2 constantList = vec2(1.0, 0.0); gl_FragColor = mycolor.xyzw * constantList.xxxy + constantList.yyyx;This does it all with one MAD operation, assuming that the building of the constant is compiled directly into the executable. ;@void main: I will go ahead and make the blur shaders separate and unwrap the loops to see if that helps. That's definitely a very viable optimisation, Thanks!@karwosts: I tried reducing the framebuffer size(s) to 1/4 of the size. Essentially, having a framebuffer thats 1/4 of the screensize is ruffly equivalent to a 4x4-pixel blur, only OGL does all the work. Additionally, you then only have to do a 2x2 blur ontop of that to achieve a ruff estimate of what a 8x8 blur would have been.Theoretically that should increase the performance considerably. However, it only increased the performance marginally -- by ~15%. I think there is a bigger bottleneck here :)Although, using a secondary rendering target to replace the bright pass would definately speed things up. Thanks!@karwosts: That is a very handy trick! Thank you!I will go ahead and incorporate your suggestions -- hopefully it works! (said as I cross my fingers :P). If not I'll have to come back and post some more questions.Thank you again for everyone's help!; Please keep us posted ! I need to add a bloom to my engine soon and am very interested in your progress.;Quote:Original post by ConoktraI am developing a RTS game called Galactic Vice using OpenGL, and it requires Bloom/HDR to be implemented for various reasons (like the Lava effects shown here:).Not that it in any way invalidates your question, but it is perhaps worth noting that with clever texture blending, that effect could be implemented entirely without bloom/hdr. ; Alright, I was able to get better -- but not optimal -- performance. I rewrote my blur shader into two separate ones, one for the vertical and the other for the horizontal pass. I also reduced the blur FBO's resolution to half that of the window's resolution. From there I kept the kernel-size at 4 -- which results in a 8x8 blur. I also did some pretty standard optimisations, such as reciprocal multiplication rather than division. This is done by the variable "ratio" which is either 1.0 / ScreenWidth or 1.0 / ScreenHeight.I didn't unwrap the loops because the kernel-size needs to be variable. IMO, none these changes affected the visual quality of the bloom, which is excellent! Here are my new blur shaders, suggestions on how I could optimise these further are very welcome!-- BEGIN CODE -- // Vertical blur shaderuniform sampler2D texScreen;uniform float ratio;uniform int kernel_size;void main() { vec2 tc = gl_TexCoord[0].xy; vec3 total = vec3(0.0, 0.0, 0.0); for(int i = -kernel_size; i < kernel_size; ++i) { total += texture2D(texScreen, vec2(tc.x, tc.y + (i * ratio))); } total /= (kernel_size * 2); gl_FragColor = vec4(total.rgb, 1.0);}-- END CODE -- -- BEGIN CODE -- // Horizontal blur shaderuniform sampler2D texScreen;uniform float ratio;uniform int kernel_size;void main() { vec2 tc = gl_TexCoord[0].xy; vec3 total = vec3(0.0, 0.0, 0.0); for(int i = -kernel_size; i < kernel_size; ++i) { total += texture2D(texScreen, vec2(tc.x + (i * ratio), tc.y)); } total /= (kernel_size * 2); gl_FragColor = vec4(total.rgb, 1.0);}-- END CODE -- These new shaders only drop the performance by about ~20%, instead of the hideous 72% the previous ones caused. This is still not as optimal as I would like it to be -- but it would do if its the best it gets. Is there any way, short of unrolling the loops, that I could optimise this further?Thanks beforehand! |
What books did developer read for game development in the 1990s? | For Beginners | I want to make a game But I wonder how game developers worked in the 1990s, how they made games, how they learning before the Internet became as widespread as it is today. etc.how do they know how to build game mechanics as character ability power up system?how they know to reverse engineering game competitor company.what book I should read? | As far as I know (not being a programmer myself), books on the subject started appearing in the early 2000s. Up to that point, it was “learn by doing” and tips from one another. ;The first book that came to mind was Tricks of the Game-Programming Gurus: Lamothe, Andre, Ratcliff, John, Tyler, Denise: 9780672305078: Amazon.com: Books, which was geared toward beginners/students/amateurs. There were others, but that's the best selling pre-2000. After that point in time, game development became a hot topic in the book publishing world. Even GameDev.net has a series - Beginning Game Programming: A GameDev.net Collection (Course Technology Cengage Learning): 9781598638059: Computer Science Books @ Amazon.com.Otherwise, in the professional realm a lot was “learn by doing” as Tom said, or through word of mouth on early Usenet/IRC/websites (pre-GameDev.net in 1999 - see About GameDev.net). ;Computers in that era didn't have an OS like we have today. The machine booted, and you were dropped in a command shell or in an interactive BASIC interpreter. You basically programmed directly at the metal. Video memory was directly accessible, by writing in a known address range you could make pixels appear at the screen in various colors. The “OS” had a corner in the memory too for its data, but nothing prevented you from poking around there. Lua, Python, C#, C++ didn't exist, ANSI-C was just invented (K&R book about that was in 1989 iirc). Assembly language of course did exist (with books) and was used.Monthly computer magazines were published for all types of home computers. Tips and tricks were exchanged in that way, also program listings were printed in those magazines that you could then enter at your own computer. Studying those listings, and trying things for yourself is how you learned. There was also technical documentation about the computer.If you want to enjoy that stuff, today there is a retro-computing movement, that lives in that era, except with slight more modern hardware but still no OS, etc.;Alberth said:Computers in that era didn't have an OS like we have today.In the 1990s there was MSDOS, Several versions of Windows, and of MacOS. And that's not all the operating systems of the nineties, most likely.Like Linux, for instance.;Tom Sloper said:Alberth said:Computers in that era didn't have an OS like we have today.In the 1990s there was MSDOS, Several versions of Windows, and of MacOS. And that's not all the operating systems of the nineties, most likely.Like Linux, for instance.Yep. There were things like Windows 95, Win 98, and at the time I was still using a Commodore Amiga (AmigaOS) .To deal with the original question “what game dev books was I reading in the 90s?” Back in that era, one of my favorites was : The Black Art of 3D Game Programming by André LaMothe. ;Abrash was the guy who did the Windows NT graphics subsystem and worked on Quake.https://www.drdobbs.com/parallel/graphics-programming-black-book/184404919 ;There are a couple of" history of video games" books, that track the rise of the medium and genre.Just google for them. ;GeneralJist said:There are a couple of" history of video games" booksThat's not what the OP is looking for.;Thanks all |
Choosing a career in AI programmer? | Games Career Development;Business | Hello everyone, my name is Ramon Diaz; I am currently studying Game development and programming at SNHU. I have taken the initiative to learn about a professional career in AI programming. I have a lot of gaps in my development in the short term. I have blueprint experience with AI but not enough to choose a career in this profession. I would like to know how I can be competitive leaving the university in 5 months after finishing my studies. I am looking for knowledge from all of you who have been in the industry for years. | Entry level? Know your algorithms, it will help you at interviews. If you have made demos it can help you get jobs, but the market is wide open right now and should be relatively easy to find work for the foreseeable future. Overall, it reads like you are on the right path. When you graduate and start looking for work, be open to any positions rather than just an AI specialty. Once you have a job it is easier to transition into whatever specialty you prefer.;Thank you. ;I would like to know how I can be competitive leaving the university in 5 months after finishing my studies.Talk about last minute. Create AI projects? Or A game with character behaviors? Pathfinding examples. Crowd movements. Anything really. Learn how navigation meshes work.;@dpadam450 Character Behavior is what I doing in the project at this moment. Everything related to AI programming.;@dpadam450 Is it the same when learning C++ in AI as visual scripting Blueprint? If I were to make a demo, what kind of programming should I focus on my attention? ;@frob It is important to have a portfolio? ;Not for programming. You will need to show you know how to do the work, but it is usually some interview questions and writing some code of their choice. If you have something you want to share with them, you can do it if you want. Having done fancy demos can sometimes help get interviews, and can help show your interest and abilities, but it is generally not needed. It does not hurt, unless you do it badly and therefore becomes a cautionary warning. Build it if you want. I have interviewed and hired bunches of programmers without portfolios. ;I'm studying AI at the moment, in terms of statistical learning. I've learned so much about AI over the past few weeks. Check out: https://hastie.su.domains/ISLR2/ISLRv2_website.pdfandMachine Learning with R: Expert techniques for predictive modeling, 3rd Edition |
Newbie desperate for advice! | Games Business and Law;Business | Hi allI'm new to the game development community and need some advice.I've created 2 educational games with a simple idea but are sufficiently challenging for all ages. These could be played on pcs or phones.Is it worth patenting any parts of the games?What would be the best way to monetize?How should I market the games? | hendrix7 said:I'm new to the game development communityReally? Your profile shows that you've been a member here since 2004, and your last activity was in 2007, asking about raycasting.hendrix7 said:Is it worth patenting any parts of the games?Probably not. Expensive and there will be hurdles, and possible lawsuits after the patent is granted (if it is).hendrix7 said:What would be the best way to monetize? How should I market the games?There are several threads here in the Business and Law forum about that. While you wait for more replies from the community, you can read up on those previous answers to those questions. Mainly, “you should have thought about that before you finished your games.” (You wouldn't be “desperate” now.) Good luck with your sales!;@hendrix7 Filing for a patent can be expensive, and you need to document the solution and how it separates from anything else. I have developed software that solved problems in a way that no other software does, but there is only a very small portion of that that can actually be patented. Even though you can file an application yourself, I would recommend hiring an experienced IP attorney. This too is very expensive, though, so you are best off doing this if this idea can provide millions in income. If it can't, then it's actually not that harmful if anybody copies it.You could look at registering trademarks, design and other parts of the games. This is cheaper, but it will protect you brand more than your idea or solution.Again, if this is something that could turn a real profit, it might be worth looking into. If not, it's a very costly waste of time.As for marketing - my day job is actually creating videos and commercials etc., so naturally that's the first thing that comes to mind.Make videos for social media or other platforms where your target audience is likely to see it. Oh, and you need to define a target audience. Know where they are, what they respond to, what their struggles are and how your product will solve their problems, enhance their life experience or in other ways contribute positively to their life.There are several other ways to do this, but the list exceeds my level of expertise in the area.;patenting is costly, and time intensive. As said above, it depends on a lot if it's worth it. ;@hendrix7 Nothing is worth patenting unless you're willing and able to defend your patent. There is no patent police; you're responsible for finding and prosecuting infrigement.What you're patenting has to be novel and non-obvious to a person skilled in the art. You called your idea ‘simple’ which makes me wonder if it's obvious or already in use.;@Tom Sloper Thanks TomI have been programming for a while but not games until now.Thanks for getting back and your advice, particularly patents.;@scott8 Thanks for your reply.I see. The play of the game utilises basic maths skills so I'm guessing it'll be difficult to identify anything that's unique. I suppose, in a similar way, it would be difficult to patent something like ‘Wordle’. Am I right? |
Hi I'm new. Unreal best option ? | For Beginners | Hallo everyone. My name is BBCblkn and I'm new on this forum. Nice to virtually meet you 🙂. One of my biggest dreams is to make my own videogame. I love writing design as in text on how my dream game would be. Now I got no skills to create it. But who knows what life will bring. Is Unreal the best program to have fun with an experience ? Obviously I prefer a simple but capable program. Not pre designed auto drop. Why not install Unreal and roam into it and see if anything happens.My favorite games are in the genre of Fantasy, usually stone age with magic. Dota, Homm, Diablo and the odd one out is the genius Starcraft 1. But I played plenty of different games, especially when I way younger. I don't game currently at all but designing gets my creative juices flowing and is so inspiring and fun. Thanks for having me guys | BBCblkn said:My name is BBCblknI am truly sorry for you. Even Elons daughter has a better name than that.BBCblkn said:Is Unreal the best program to have fun with an experience ?Give it a try, but it's not meant for total beginners.Starting small always is a good idea. 2D is easier than 3D. You could try GameMaker, learn some programming language, learn some math, move on to more advanced engines like UE or Unity… ;There's honestly no perfect program for beginners. If I had to compare Unreal though at my skill level, I would probably pick Unity. However, It really comes down to your needs, and how much programming you want to learn. Furthermore, I would also keep in mind other engines.;@BBCblkn I'd recommend Gamemaker studio 2 as a first engine. It's easy to learn and I haven't had a problem making my game ideas in it yet.There are some good tutorials on YouTube to follow to learn it. Do note you'll be limited to 2D games with GMS2.Bit late to the post, but I hope it helps;gamechfo said:Bit late to the postTwo months late. Always consider whether you honestly believe that a question asked long in the past is still awaiting an answer. Thread locked. |
How to publish a book? | GDNet Lounge;Community | Hello, So, over the holidays I finished my 1st book. Do any of yall writer types know where I can find:an editorpublisherIt's like 99% done, just need to know what to do next. Also, it's cross genre, so it doesn't necessarily fit the standard model. | You've given nowhere near enough information to get a final answer, but I can suggest next steps for you. (For background, I've worked as an author, co-author, editor, and ghostwriter on 9 books so far.)Publishing is a business deal. You need to figure out what business services you need.Do you even need a publisher? Do you need a distributor? You already mention needing an editor. Do you need marketing? Do you need retail agreements? Digital or physical? If physical, POD or offset, how many each of hard or soft, what size of print run can you afford? What business services do you need? Publishers have an awful lot of potential features of what they can provide and what those services cost.Once you know the list of services you actually need, your favorite bookstore will have books that have listings of all the major publishers and hundreds of minor publishers, along with the services they provide and the specialties they work with. Work through the listings methodically, and talk to them all until you've got a deal. You'll also want to start shopping around for a lawyer at that point, both because they have connections and because they'll be working with the contracts you'll be signing.Once you know what you need and have talked with your lawyer the first few times, you will be ready to start shopping around. It's far better if you have more money and are using the publisher as a paid service. That is, you pay them for the services they provide up front. It will cost you many thousand dollars but you'll require far fewer sales to reach profitability. It can be better to do an online plus POD service starting out if you're self funded. If they need to front any of the money there will be two phases to the deal, one phase before it's profitable and another after a threshold is reached and it's profitable. The exact terms will depend on your needs and the services they'll be providing. Before you sign with anyone, you'll need to work back and forth more than once with your lawyer to help you negotiate what's fair in the agreement. Good lawyers understand the costs of the various services and can help you get fair rates.Just like publishing games, the more you need from them the harder your pitch becomes. If you need a lot of services the more it will cost you. If you're looking for them to invest in you, front you money, and pay for the books, don't expect a lot of money from the deal, and in addition your pitch needs to be amazing and you'll be rejected many times. If you've got the money to self-publish and are only looking for retail agreements that's rather easy. ;hmmmWell Self publish might work too. I'm looking for:an editor publishing distribution for ebookNo hard cover or physical book planned at this timemaking cover art. Future Audio book production. I think that's it. I'd be willing to do physical print if needed, but I don't really want to pay for that at this time. frob said:You've given nowhere near enough information to get a final answer The issue is I don't know what questions or criteria I should be asking or looking for. ;Have you considered publishing with Packt?https://www.packtpub.com/;GeneralJist said:2. publishing distribution for ebook 3. No hard cover or physical book planned at this timeFor distribution of an ebook there are plenty of options. Amazon is the biggest with kindle direct publishing requiring little more than an html file and an image for the title. If you are comfortable with software tools you can use that same document to build/compile every other format out there. You're on the hook for everything else with the business if you go that route, but it can work well if you are marketing through your own channels.There are many ebook publishers out there targeting specific platforms and specific readers or specific genres. I mentioned publisher lists, they also include electronic-only publishers. Understand the tools they use against piracy are also helpful since otherwise anybody with access to the file can make unlimited copies.Be careful of contracts, you almost certainly want something that has a non-exclusive agreement since you've done all the work yourself already. If a publisher wants an exclusive deal they need to be putting quite a lot on the negotiating table.GeneralJist said:4. making cover art.Find an artist with the style you like and contact them. Often it's in the range of a couple hundred bucks, especially for ‘unknown’ artists when they're starting with something that wouldn't have seen the light of day otherwise. Artist friends are best, and asking around at local art schools is inexpensive.GeneralJist said:5. Future Audio book production.If you don't need it now, it's something easily done later.GeneralJist said:1. an editorThis one is the most difficult. Skilled editors are amazing. If you go with a publishing house they'll provide professional editors, at professional rates. ;taby said:Have you considered publishing with Packt?https://www.packtpub.com/hmmm 1st time hearing of them.Looks like they are more of an educational option?My book is a mix of mental health journey auto bio, and Sci Fi elements. It's not really a standard “how to” for game dev. ;so I just heard back from my 1st publisher submission.https://triggerhub.org/And they essentially say they be willing to look at it deeper, and have extensive edits to focus on the mental health angle. but they would want me to cut a lot. From what they are hinting at, It sounds like they want to cut a lot of the Game dev and gaming journey, as they are a publisher focused on mental health.So, now I need to decide what to do.I sent them back an email saying I'm open to continued dialogue.Without knowing exactly what they want to cut, and edit, I don't know how to proceed.Also, would it be better to hold out, and find a publisher that is willing to accept most of the game dev journey, as I'm looking for a continued publisher to work with, aka accept most of the book as is. Any advice would be helpful.Thanks yall. ;GeneralJist said:Any advice would be helpful.Look into your own mind and heart.;hmmmok,So I've submitted to a few other places.We shall see.I submitted to this place called author House, and they got back to me really quick, but it looks like they want me to pay a couple thousand for a package:https://www.authorhouse.com/en/catalog/black-and-white-packagesI personally find that a bit frustrating.I mean, really, I wrote the book, I thought traditional publishers get paid from a % of sales?@frobWhat do you think?Is the above package a good deal?I was also a little put off, as it seems the person who called me didn't even read anything about my book, and asked me “so what's your book about?"beyond the above, how does this usually work? Edit: so, after a bit of basic research, it seems the above organization is a bit scamy. The hunt continues. ;You're unlikely to get a publisher deal, where the publisher pays you an advance and distributes your book to retail outlets.You'll have to self-publish, meaning you have to bear all the costs for printing, and nobody will distribute it for you. https://en.wikipedia.org/wiki/Vanity_press |
First-person terrain navigation frustum clipping problem | General and Gameplay Programming;Programming | I am trying to develop first-person terrain navigation. I am able to read a terrain and render it as well as to move around the terrain by interpolating the location of the camera every time I move around. The main problem I have is that depending on the terrain, i.e. moving on a sloping terrain, the near plane clips my view (see below). What is the best way to avoid this? Presumably, I can interpolate the heights for the bottom corners of the near plane … any help would be appreciated. | I believe this can aways be an issue. I mean if you are clipping to a near plane and that plane passes through geometry, it has to do something. That being said you technically don't have to clip to a near plane at all, however many graphics APIs require it. Another other thing to consider is once you have collision working, you can put your camera, including your near clipping plane inside a collidable object, for instance a sphere, such that this problem will never occur. If you are eventually going to make this a real first-person game, that should take care of the problem since your camera will be inside the players head. Even in a 3rd person game you can put them inside a floating sphere. ;Gnollrunner said:That being said you technically don't have to clip to a near plane at all, however many graphics APIs require it.The near clip plane is always needed, even if you use a software rasterizer. If you don't do the clipping, vertices would flip behind the camera, causing glitches way worse than what we get from clipping.mllobera said:What is the best way to avoid this? Presumably, I can interpolate the heights for the bottom corners of the near plane … any help would be appreciated.Yes, basically you want to ensure that the camera is in empty space (above the hightmap), not in solid space (below the heightmap).But in general you can not treat the camera as a simple point, because the front clip plane requires a distance larger than zero. So ideally you build a sphere around the camera which bounds the front clip rectangle of the frustum, and then you make sure the sphere is entirely in empty space, for example. In the specific case of your terrain not having too steep slopes however, it should work well enough to sample height below camera, add some ‘character height’, and place the camera there. That's pretty simple and usually good enough for terrain.It's quite a difficult problem mainly for 3rd person games in levels made from architecture. It's difficult to project the camera out of solid space in ways so the motion still feels smooth and predictable.Some games additionally fade out geometry which is too close, attempting to minimize the issue.Imo, the ‘true’ solution to the problem would be to let the clipping happen, but rendering the interior volume of the geometry as sliced by the clipping plane.That's pretty hard with modern rendering, which usually lacks a definition of solid or empty space. But it was easy to do in the days of Doom / Quake software rendering. When i did such engine, it was possible to render clipped solid walls in simple black color. This felt really robust and not glitchy, so while it does not solve all related problems, i wonder why no game ever did this. ;@undefinedJoeJ said:The near clip plane is always needed, even if you use a software rasterizer. If you don't do the clipping, vertices would flip behind the camera, causing glitches way worse than what we get from clipping.You can clip to a pyramid instead of a frustum. I used to do this many years ago on old hardware. So there is no near clipping plane. In fact you don't need a far clipping plane either.Edit: Just wanted to add as far as I know the near and far clipping planes mostly have to do with optimizing your Z resolution. If you are dealing with that in other ways, I think they aren't strictly necessary. I currently don't even deal with the far plane and let LOD solve Z-fighting issues.;Gnollrunner said:You can clip to a pyramid instead of a frustum.I see. You still have front clip. It is a point, formed indirectly as the intersection of the other other frustum planes.I've misunderstood your claim to be ‘you don't need a front clip’. But you didn't say say that. Sorry. But now i'm curious about the experience with z precision you have had. I guess it just worked? Which then would probably mean: All those painful compromises of ‘make front plane distant so you get acceptable depth precision for large scenes’, are a result of a bad convention being used by APIs?Or did you use no z-Buffer? ;@undefined My whole engine is based on aggressive LOD and culling. I don't do projection in the matrix. It's a post step. My Z coordinates are world distances. My current project does have a near clipping plane mainly because DirectX wants one, but it's not that relevant for my application.;Ah, so you use the pyramid for culling only. But for rasterization, the usual front clip plane at some distance i guess.Still an interesting question if ‘some distance’ is really needed, but i guess yes.I did some experiment about point splatting. It uses spherical projection, which is simple than planar projection:auto WorldToScreen = [&](Vec4 w){Vec4 local = camera.inverseWorld * w;if (local[2] < .1f) return (Vec3(-1)); // <- front clip at some distance of 0.1Vec3 screen = (Vec3&)local;screen[2] = length(screen); // if it was zero, i'd get NaN herescreen[0] = (1 + screen[0] / (screen[2] * camera.fov)) / 2;screen[1] = (1 + screen[1] / (screen[2] * camera.fov)) / 2;return screen;}; Planar projection would cause division by zero too, i guess.;Thanks for all your comments! I will need to investigate how to do what Gnollrunner proposed (about putting the camera inside of a sphere). ;This may be obvious, but in case it helps:Let me note that, as a first-person camera may be more likely than a third-person camera to draw very close to geometry, it likely makes some sense to have a smaller near-plane distance for the former than the latter.Now, this only ameliorates the problem, it doesn't remove it entirely: it means that the problem will still appear, but only if the player gets very close indeed to a surface. It's intended to be used in conjunction with one or another means of preventing the camera from approaching quite so near to a surface (such as the sphere-approach mentioned by others above).;Thaumaturge said:This may be obvious, but in case it helps:Let me note that, as a first-person camera may be more likely than a third-person camera to draw very close to geometry, I'm not sure that's so true. I mean in both cases you have to take care of the problem somehow. The case of a first-person camera is a bit easier because it should always be in the collision boundary of the player (sphere(s), ellipsoid, capsule etc.). As along as the near plane is also within that boundary, the problem should never occur. So if you have a 10cm radius sphere and put the camera in the back of it, that gives you maybe a 10 to 15 cm camera to near clipping plane distance to play with depending on the field of view you are going for. With a 3rd person camera, you can also get very close to terrain, in fact your camera can end up within terrain or some object if you don't do anything to solve that problem, and this will happen very often without separate camera collision. One typical way to handle this is just implement your following camera, ignoring terrain considerations. Then to figure out your camera's actual position, project a line back from the head of the avatar to the camera's ostensible position, and see if it intersects anything to get the camera's true position. In reality you should project a cylinder and not a line since your camera will need its own bounding sphere to contain the near clipping plane. In any case this means that as you move around your camera can jump forward to clear terrain and objects. I've seen this in a few MMOs. However, when you leave blocking terrain you have the option of implementing smooth movement back to the cameras desired location. If you want to get really fancy, I guess you could try to predict when your camera will need to jump forward ahead of time and try to do smooth moment forward too. Maybe you can have a second camera bounding sphere which is somewhat larger, that would trigger smooth movement, but I think you would still need a fallback camera jump routine to be safe. |
How do I change this orthographic projection into a perspective FOV? | Graphics and GPU Programming;Programming | Folks, I have a top-down spaceship shooter that is rendered in 3D using an orthographic projection. The camera is always centered on the player's ship. Because the projection is orthographic, all of the ships are flat on the screen as if it were a 2D game.I want to experiment with adding some perspective to ships that are distant from the player's ship. I cannot figure out how to make a perspective projection matrix and corresponding view matrix to achieve this effect.Here is my current view, and projection: Matrix worldMatrix = Matrix.Identity; Matrix view; Matrix viewInit = Matrix.CreateLookAt(new Vector3(0, 0, 500), new Vector3(0, 0, 0), Vector3.Up); Matrix projection = Matrix.CreateOrthographicOffCenter(0, 1280, 720, 0, -100000, 100000);I know I need a tight Field of View and a camera pulled back pretty far to achieve the same effect. How do I do that? | first off, i don't like the use of new in your CreateLookAt() function. If your not explicitly deleting these vectors you have a memory leak. the D3DX docs are a great resource for matrix related info. You can see how the persective matrices are created, and then use numbers that work for you. The screen size of your orthographic matrix is equivalent to the size of the near plane for a perspective projection. You can use trig to find a suitable FOV angle to give the desired width/height of the near plane, based on the distance the nearplane is from the origin of viewspace. ; First, as Burnt_Fyr implies, you'll just have create a perspective projection with some parameters you like.Quote:..to achieve the same effect. How do I do that?You can't, at least, not "the same." An orthographic projection maps a box in the world to the screen. A perspective projection maps a truncated pyramid in the world to the screen. They don't (and can't) represent the same volume of world space. The perspective volume can be smaller or larger than the box, but it can't be the same.E.g., if a ship wanders outside the box and disappears from the ortho view, it may still be in the perspective volume and be mapped to the screen. |
Need Very Small Random Numbers | General and Gameplay Programming;Programming | My question is rather simple. I need to know how to generate VERY VERY small random numbers in C++. They will be double's. I am sampling from a space ranging from a scale of 10^-1 in probability to a scale 10^-67 in probability. For example, the probability of one sample may be 40.1% while the next might be (1.2*10^-49)%. This is being used in a robotics project for monte carlo localization, so every generated probability must be taken into account regardless of how small it may be. I will be sampling with replacement and obtaining a large number of samples. When I try generating random doubles using something similar to:double X = XMin + rand() * (XMax - XMin) / RAND_MAX;It seems that the smallest generated number is never anywhere near the specified min. (usually smallest I get back is around 10^-3).If there is no easy/clean way to do this, I suppose I could multiply by 10 * log(min prob). Then I would have the same problem only with whole numbers (need random number between 1 and 10^67). Does anyone have any ideas on how to handle this. I feel like I am missing something very obvious but can't quite put my finger on it! | Have you looked at the rngs that come with the C++ standard library? There are several generators and probability distributions to choose from. Perhaps one of them (exponential comes to mind) will do the job for you.Look in <tr1/random> for the tr1 library and <random> for the C++0x library (they are different). ; Perhaps RAND_MAX is too small for your purposes. You can use a 64-bit PRNG or you can manufacture one by concatenating bits from several calls to rand(). You can then use the same type of formula you had before.You shouldn't worry that your event with probability 10^-49 will never be picked: Even if you did the absolutely correct thing, it wouldn't ever be picked in practice. ; Are these probabilities coming up when generating the candidate state, or when determining whether to accept the transition? In the latter case don't worry about it, beyond getting a PRNG of at least 32 bits. In the former case, it depends on your sample space. ; You aren't really trying to get small numbers; you're trying to get a high number of significant figures. Otherwise you could just divide the numbers you get by some large constant, but it does you no good if the range is 0..10^-30 since then all the 1% probability events always happen ;)You can synthesize the probability by just taking several RNG results in a row. Say for example that you get 16 random bits per call, and 2^-256 is the smallest probability you have to worry about. So you express every probability as X/2^256, except you store X as a series of 16 16-bit values - the first gives the most significant bits in the binary representation of X, etc. To check if the event occurred, you pull out an RNG result and compare it to the first number; if it's exactly equal, then you try the second etc. until you get something either higher (or equal, on the last one - reject) or lower (accept). ; Will this work?result = 1.0 / static_cast<double>(rand()) * static_cast<double>(rand())?Of course need to check to be sure the denominator is not zero. ; That won't give anything near a uniform distribution. ; Edit: Just realised you're not actually looking for a linear distribution. I kept getting numbers that were always much higher than the min in terms of exponent, but this is intentional. There should be a distribution function that can produce an even distribution when graphed on a logarithmic scale, which is what you need.Try this:std::tr1::uniform_real<double> dist(-67,-1);std::tr1::minstd_rand engine;double values[1000];for(int i=0; i<1000; i++)values = pow(10,dist(engine));[Edited by - taz0010 on November 18, 2010 12:45:26 AM];Quote:Original post by taz0010Edit: Just realised you're not actually looking for a linear distribution.I don't see why you think this. The purpose is to take an event probability P, and simulate an opportunity for the event to happen, and see whether it actually happens or not, right? We do this, conceptually, by generating a uniform distribution on [0..1) and seeing if it is less than P.;Quote:I don't see why you think this. The purpose is to take an event probability P, and simulate an opportunity for the event to happen, and see whether it actually happens or not, right? We do this, conceptually, by generating a uniform distribution on [0..1) and seeing if it is less than P.Oh, if that's what he's after then he can use the tr1::bernoulli_distribution generator.http://www.johndcook.com/cpp_TR1_random.html#bernoulliUsing rand() won't work with the probabilities he's specified because RAND_MAX is (usually) 32767. With only 32768 different possibilities, chances are something with a probability of say, 1/1000000 will never be picked. |
Java Image-Handling? | For Beginners | I'm unsure of which class I should instantiate. I've seen BufferedImage, ImageIcon, and Image with the getResource() method called. I'm not entirely sure of the differences between the classes, but it's crucial that I know how to proceed. My first guess would be that BufferedImage uses less memory, but I'm not quite sure. I'll be doing animation and such, by the way. Thanks in advance; I've searched a few sites but there seems to be contradiction. | Image is just the base class for all image types. It gives you the basic stuff like size and being able to use it for drawing. You can't create one directly, instead you create something like a BufferedImage (which is an Image).BufferedImage is 'an image with an accessible buffer of data'. Ie. it's an image where you can reach around and touch the raw pixel data in memory.ImageIcon is actually an Icon. You'll only use this if you want to put an image on a button or a menu. Sometimes you'll see people being lazy and use this instead of loading an image the proper way via ImageIO.Most of the time you want to use ImageIO to read() a BufferedImage. Then you can either hold it as an Image (if you just want to draw it) or as a BufferedImage if you want to tinker with the pixel data directly.HTH ; For future reference for handling tileset and spritesheet Images, would it be a safe assumption that I should use a BufferedImage not typed as an Image in order to access pixel data directly? It seems like getSubImage() is exactly what I'd need! Thanks a lot; I can make some good progress with this information :) ;Quote:Original post by FujiFor future reference for handling tileset and spritesheet Images, would it be a safe assumption that I should use a BufferedImage not typed as an Image in order to access pixel data directly? It seems like getSubImage() is exactly what I'd need! Thanks a lot; I can make some good progress with this information :)You wouldn't want to call getSubImage() in a tight loop (i.e., your rendering loop). If you break your tileset up into an array of all the individual tiles though, that would be fine, since it would only need to happen once for every time the tileset is loaded (which probably won't be too often). Another option is to use drawImage with source x/y/width/height parameters.[Edit]Actually, after reading the documentation, I should point out that getSubImage() isn't quite as bad in a tight loop as what I originally though because it shares the same data array rather than making a copy. Nevertheless, the instantiation of BufferedImages is probably going to have some impact if getSubImage() were called in a tight loop.[Another Edit]This link may be of interest too, although I've never dealt with volatile images before. |
questions about breaking into the industry | Games Career Development;Business | Hey guys, just got some questions about getting into the game industry.I also want to say hi to Tom because I know are probably reading this and I've probably missed a section on your site that probably helps big time in my questions.anyways to the point i'm going to school for an associated in game development and it's almost completed, the degree is outlined with the following courses math (specialized physics for game environments), coding (intro to c++, object orientated c++), ai programming, 2d and 3d programming (c# XNA) mobile phone (or) flash programming, tech writing, media writing, classic mythology, 2d drawing, 3d animation classes, game design, business of games, and finally a capstone class (we'll build a game from scratch).probably could have just gave you this link to explain it all in detail. http://www.jccc.edu/home/catalog.php/current/careerprograms/AAS-GAMEDEVso after looking at this, my question is broken into two parts, I'm currently and have been for a few years working in tech support, should i first go for a 4 year degree in computer science or should i attempt to break straight into the industry with a level design/scripting job then move into a programming position.any help on this would be great. | What do you want to do?Do you want to stay in school? Do you want to enter the work force?There is always a lot of competition for game jobs, so finding an entry level job isn't always easy. That's especially true in this economy. You will be competing against others with bachelor's degrees. In that regard, it may be better to stay in school until both the job market is better and you have finished to the bachelor's degree level. Having that traditional computer science degree can also help you get a job during when/if you ever have difficulty finding jobs in games. Or it may be better for you to start your job search and enter the long haul of work life.My general recommendation is a bachelor's degree in CS for programmers. It gives you a broader knowledge base and broader opportunities for the nearly-inevitable career changes later in life. ; >my question is broken into two parts, I'm currently and have been for a few years working in tech support, should i first go for a 4 year degree in computer science or should i attempt to break straight into the industry with a level design/scripting job then move into a programming position.That looks like only one question to me (a two-choices question).You can go ahead and try to break in through level design / scripting, if your portfolio is strong enough.In the meantime, you could go to college and get a degree in whatever you like. And hi back atcha. ;Quote:Original post by Tom Sloper>my question is broken into two parts, I'm currently and have been for a few years working in tech support, should i first go for a 4 year degree in computer science or should i attempt to break straight into the industry with a level design/scripting job then move into a programming position.That looks like only one question to me (a two-choices question).You can go ahead and try to break in through level design / scripting, if your portfolio is strong enough.In the meantime, you could go to college and get a degree in whatever you like. And hi back atcha.eh i guess i forgot to ask my second question whoops!the associates degree that i'm going for does this look like a good overall program for game development? it looks to me like i get a little bit of base knowledge in everything, programming (lots of it) writing, math, mythology, and art. |
HLSL: Samplers in pixel shaders | Graphics and GPU Programming;Programming | Hi,I'm using HLSL for my pixel shader without the effects framework, and I'm new to pixel shaders (Something I really should have used by now, but never mind...).Here's my very basic shader:struct PS_INPUT{float4 pos : POSITION;float4 diffuse : COLOR0;float2 uv : TEXCOORD0;};struct PS_OUTPUT{float4 colour : COLOR0;};sampler textureSampler = sampler_state{addressU = Clamp;addressV = Clamp;mipfilter = NONE;minfilter = LINEAR;magfilter = LINEAR;};PS_OUTPUT main(PS_INPUT In){PS_OUTPUT Out;Out.colour = tex2D(textureSampler, In.uv) * In.diffuse;return Out;}And fxc generates the assembly:// Name Reg Size// -------------- ----- ----// textureSampler s0 1 ps_2_0 dcl v0 dcl t0.xy dcl_2d s0 texld r0, t0, s0 mul r0, r0, v0 mov oC0, r0The tex2D instruction takes a sampler as its first parameter, where I pass textureSampler, but looking at the generated assembly, there's nowhere that the sampler is actually set up (bilinear filtering, clamp wrap mode).Am I supposed to still use SetSamplerState() when doing everything through shaders? If so, what's the point in the sampler_state that I need to pass to tex2D? And if not, why isn't the texture addressing and filtering being applied?Also, a different question - what's the usual way to output depth in the pixel shader? My Google-fu is weak and I couldn't find any references on what the depth output should be (And I presume that if I don't output a depth value, some default value is used)?I feel like I'm missing something obvious here [smile]. Does anyone have any good references for HLSL without the effects framework?Cheers,Steve | Quote:Original post by Evil SteveHi,I'm using HLSL for my pixel shader without the effects framework, and I'm new to pixel shaders (Something I really should have used by now, but never mind...).Are you sure you're not a Visual Basic MVP or something? :PQuote:Original post by Evil SteveHere's my very basic shader:*** Source Snippet Removed ***And fxc generates the assembly:// Name Reg Size// -------------- ----- ----// textureSampler s0 1 ps_2_0 dcl v0 dcl t0.xy dcl_2d s0 texld r0, t0, s0 mul r0, r0, v0 mov oC0, r0The tex2D instruction takes a sampler as its first parameter, where I pass textureSampler, but looking at the generated assembly, there's nowhere that the sampler is actually set up (bilinear filtering, clamp wrap mode).Quote:Original post by Evil SteveAm I supposed to still use SetSamplerState() when doing everything through shaders? If so, what's the point in the sampler_state that I need to pass to tex2D? And if not, why isn't the texture addressing and filtering being applied?Okay so at the lowest level (no effects), shaders don't have any concept of sampler states. You set those states on the device using SetSamplerState, for a specified sampler index. Then in the pixel shader profile you're compiling to, there are sampler registers that map directly to the sampler/texture index you use for SetSamplerState/SetTexture. Looking at your assembly, you're doing a texture load on s0 which means index 0. So if wanted to bind a texture to sampler you would call SetTexture and pass 0, and for any sampler states you would call SetSamplerState and also pass 0.When you declare some HLSL type that's mapped to a register (samplers, constants, etc.), the HLSL compiler will automatically assign that variable to a register for you. Usually it's just done in ascending order. Your C++ code can obtain reflection data for a shader via ID3DXConstantTable that includes all constants and samplers used in a shader, as well as which register they were mapped to. You could then use that data to set appropriate states on the device. As an alternative to that, you can also explicitly map a constant or a sampler to a register. The syntax is like this:sampler2D someSampler : register(s0);float4 someConstant : register(c0);If you're not using effects, you can remove all of that sampler_state stuff. That information is parsed by the effect framework, so that at runtime it can call SetSamplerState with the appropriate values when you use the effect. Without effects it's useless.Quote:Original post by Evil SteveAlso, a different question - what's the usual way to output depth in the pixel shader? My Google-fu is weak and I couldn't find any references on what the depth output should be (And I presume that if I don't output a depth value, some default value is used)?You output depth with the "DEPTH" semantic. Basically whatever value you output gets used directly in the depth test and written to the depth buffer, which means you want post-projection z/w in the range [0.0, 1.0]. If you don't output a depth value, the interpolated z/w from the position output by your vertex shader is used.Be careful though with depth output...it will totally break early z-cull optimizations used on GPU's to prevent occluded pixels from being shaded, which can seriously degrade performance if you're running heavy pixel shaders. But regardless the cases where you actually need depth output should be pretty rare.[Edited by - MJP on November 19, 2010 12:52:42 PM];Quote:Original post by MJPOkay so at the lowest level (no effects), shaders don't have any concept of sampler states. You set those states on the device using SetSamplerState, for a specified sampler index. Then in the pixel shader profile you're compiling to, there are sampler registers that map directly to the sampler/texture index you use for SetSamplerState/SetTexture. Looking at your assembly, you're doing a texture load on s0 which means index 0. So if wanted to bind a texture to sampler you would call SetTexture and pass 0, and for any sampler states you would call SetSamplerState and also pass 0.Ah, the reference to the sampler in tex2D was throwing me off and making me wonder if the SetSamplerState stuff was fixed-function only...Quote:Original post by MJPWhen you declare some HLSL type that's mapped to a register (samplers, constants, etc.), the HLSL compiler will automatically assign that variable to a register for you. Usually it's just done in ascending order. Your C++ code can obtain reflection data for a shader via http://msdn.microsoft.com/en-us/library/bb205762%28VS.85%29.aspx that includes all constants and samplers used in a shader, as well as which register they were mapped to. You could then use that data to set appropriate states on the device. As an alternative to that, you can also explicitly map a constant or a sampler to a register. The syntax is like this:sampler2D someSampler : register(s0);float4 someConstant : register(c0);If you're not using effects, you can remove all of that sampler_state stuff. That information is parsed by the effect framework, so that at runtime it can call SetSamplerState with the appropriate values when you use the effect. Without effects it's useless.I see. So if I know what texture stages my textures are in already, I should just explicitly map a sampler to a register?Basically, I was hoping just to be able to specify the texture stage as a parameter to tex2D() (Which explicitly assigning registers like in your example seems to do).Quote:Original post by MJPYou output depth with the "DEPTH" semantic. Basically whatever value you output gets used directly in the depth test and written to the depth buffer, which means you want post-projection z/w in the range [0.0, 1.0]. If you don't output a depth value, the interpolated z/w from the position output by your vertex shader is used.Be careful though with depth output...it will totally break early z-cull optimizations used on GPU's to prevent occluded pixels from being shaded, which can seriously degrade performance if you're running heavy pixel shaders. But regardless the cases where you actually need depth output should be pretty rare.I see - that would explain why the examples I saw tended not to output depth in the pixel shader then.Thanks! ;Quote:Original post by Evil SteveIf you're not using effects, you can remove all of that sampler_state stuff. That information is parsed by the effect framework, so that at runtime it can call SetSamplerState with the appropriate values when you use the effect. Without effects it's useless.I see. So if I know what texture stages my textures are in already, I should just explicitly map a sampler to a register?Basically, I was hoping just to be able to specify the texture stage as a parameter to tex2D() (Which explicitly assigning registers like in your example seems to do).Yeah, you can just map the sampler to the index you want and then just use that sampler with tex2D. |
Creating 2D Game in DirectX9 | For Beginners | I'm sure that some of these questions have been answered, but my search results keep coming up with answers that are older than I'd hoped.So, I'm working on creating a little 2D game using C++ and DirectX9 in Visual Studio 2010. I have successfully drawn a few sprites and made them recognize collisions and I can even control my character with my keyboard (although my animations are awful).I'm wondering where to go next. I would like to implement a title screen and perhaps a pause menu, and I'd also really like to learn how to implement basic physics that make my character appear to be standing on the ground, held there by some invisible force such as gravity or maybe I'd settle for a ghost.I'm unsure where to put logic that would give my player life (health points, I'm not Frankenstein), or how to put a working life bar on the screen. I want to make badguys that will die, and cutscenes where badguys talk before they die. Maybe a townsperson that repeats a phrase over and over. I'd like to add a second or third level to my game.My problem seems to be that I'm unfamiliar with the logic structure of DirectX. It seems like most of what I would call gameplay happens between BeginScene and EndScene, but games don't generally load their entire content at all times, right? I mean, how do I tell the game what level to draw? Let's say that he reaches the edge of the screen, do I End Scene and call another function that contains a scene? I'm not afraid of doing a ridiculous amount of work, but I'm afraid that my performance is going to suffer if I continue loading everything into a single scene. Where do I go from here? | If you're just starting in, you've mentioned about six months development working fulltime. My advice would be to pick one thing from your list and work on that.Quote:my search results keep coming up with answers that are older than I'd hoped.Search again. There are hundreds of posts on collision detection, for example, all posted within the last year or two. Physics and collision calculations don't change with age.Quote:It seems like most of what I would call gameplay happens between BeginScene and EndSceneActually, BeginScene/EndScene is just the rendering portion of your game. All the physics, getting and processing user-input, sound-playing, collision calculations, health point counting, etc., normally happens elsewhere.As mentioned above, your best approach for the time being should be to pick one thing, try to get it to work and ask questions when you run into problems.Go, Bucks! ; I guess I should've rephrased my question. I knew I put too much information in that first post. I already have code for all of that stuff, I just don't know where it goes.I feel like an idiot not being able to explain my dilemma. I have a function called game_run() that replaces the majority of the Win32 message loop and basically (at least, as I understand it) just runs over and over again to create my game.The Game_Run() function looks like this:(caveman and caveman2 are just sprites)void Game_Run(HWND hwnd){ //make sure the Direct3D device is valid if (d3ddev == NULL) return;Poll_Mouse();Poll_Keyboard(); //after short delay, ready for next frame? //this keeps the game running at a steady frame rate if (GetTickCount() - start >= 30) { //reset timing start = GetTickCount(); //move the sprite caveman.x += caveman.movex; caveman.y += caveman.movey;if (Key_Down(DIK_LEFT)){caveman2.x -= 5; if (++caveman2.animcount > caveman2.animdelay){//reset countercaveman2.animcount = 0;//animate the spriteif (++caveman2.curframe > caveman2.lastframe)caveman2.curframe = 0;}}if (Key_Down(DIK_RIGHT)){caveman2.x += 5;if (++caveman2.animcount > caveman2.animdelay){//reset countercaveman2.animcount = 0;//animate the spriteif (++caveman2.curframe > caveman2.lastframe)caveman2.curframe = 0;}}if (Key_Down(DIK_UP)){caveman2.y -= 5;if (++caveman2.animcount > caveman2.animdelay){//reset countercaveman2.animcount = 0;//animate the spriteif (++caveman2.curframe > caveman2.lastframe)caveman2.curframe = 0;}}if (Key_Down(DIK_DOWN)){caveman2.y += 5;if (++caveman2.animcount > caveman2.animdelay){//reset countercaveman2.animcount = 0;//animate the spriteif (++caveman2.curframe > caveman2.lastframe)caveman2.curframe = 0;}} //"warp" the sprite at screen edges if (caveman.x > SCREEN_WIDTH - caveman.width) caveman.x = 0; if (caveman.x < 0) caveman.x = SCREEN_WIDTH - caveman.width;if (caveman2.x > SCREEN_WIDTH - caveman2.width)caveman2.x = SCREEN_WIDTH - caveman2.width;if (caveman2.x < 0)caveman2.x = 0;if (caveman2.y > SCREEN_HEIGHT - caveman2.height)caveman2.y = SCREEN_HEIGHT - caveman2.height;if (caveman2.y < 0)caveman2.y = 0; //has animation delay reached threshold? if (++caveman.animcount > caveman.animdelay) { //reset counter caveman.animcount = 0; //animate the sprite if (++caveman.curframe > caveman.lastframe)caveman.curframe = 0; } } //start rendering if (d3ddev->BeginScene()) { //erase the entire background d3ddev->StretchRect(back, NULL, backbuffer, NULL, D3DTEXF_NONE);//start sprite handlersprite_handler->Begin(D3DXSPRITE_ALPHABLEND);//create vector to update sprite positionD3DXVECTOR3 position((float)caveman.x, (float)caveman.y, 0);D3DXVECTOR3 position2((float)caveman2.x, (float)caveman2.y, 0);//configure the rect for the source fileRECT srcRect;int columns = 8;srcRect.left = (caveman.curframe % columns) * caveman.width;srcRect.top = (caveman.curframe / columns) * caveman.height;srcRect.right = srcRect.left + caveman.width;srcRect.bottom = srcRect.top + caveman.height;RECT srcRect2;int columns2 = 8;srcRect2.left = (caveman2.curframe % columns) * caveman2.width;srcRect2.top = (caveman2.curframe / columns) * caveman2.height;srcRect2.right = srcRect2.left + caveman2.width;srcRect2.bottom = srcRect2.top + caveman2.height;//draw the spritesprite_handler->Draw(caveman_image,&srcRect,NULL,&position,D3DCOLOR_XRGB(255, 255, 255));sprite_handler->Draw(caveman_image2,&srcRect2,NULL,&position2,D3DCOLOR_XRGB(255, 255, 255));if(Collision(caveman, caveman2)){caveman.x = caveman.x - 10;}//stop drawingsprite_handler->End();//stop rendering d3ddev->EndScene(); } //display the back buffer on the screen d3ddev->Present(NULL, NULL, NULL, NULL); //check for escape key (to exit program) if (Key_Down(DIK_ESCAPE)) PostMessage(hwnd, WM_DESTROY, 0, 0);}Now, can I split this function up somehow to encompass these other features? I have been reading game programming books left and right but nothing's quite clear on how to break this up. I don't mean to sound ungrateful for a response, and I'd certainly only focus on one thing at a time, but I don't know how to even begin working on the next part. ;Quote:I knew I put too much information in that first post.Yeah. Ask a general question, get a general answer.I understand that you're looking for information on organizing your code. However, ensuring your program is properly coded should be your first priority. I.e., organizing poor code isn't what it's about at the moment. Some basics that you should address first may change the way you approach your run-loop.Checking for errors: You should get in the habit right now of properly checking for errors. Every DirectX function gives some indication of success or failure. The tutorial examples in the SDK are a good place to start to see how to do that, primarily the use of the SUCCEEDED and FAILED macros. Those examples will also provide with a better (more efficient and useful) way to clear the backbuffer.With regard to error checking:if (d3ddev->BeginScene()) ...BeginScene and most DirectX functions return a value indicating success or failure, not true/false values. If there's a problem with the device, you don't handle it.Due to the fact that your program is sharing the computer with other applications, frequently testing the status of the device should be a requirement in your code to avoid nasty situations. It's common to check the status once each frame and handle each error (if any) explicitly. dev->TestCooperativeLevel() is a good function for that testing.With regard to general game- and run-loop organization, this article has some good general organization information. The idea is to encapsulate unrelated activities into separate routines. Those routines (functions) are then called (in order) within the loop.Quote:I have a function called game_run() that replaces the majority of the Win32 message loopYou may want to consider using a message loop for getting user input, and eliminate the complications of DirectInput. For a lot of applications, getting user input through the window procedure is much simpler, more than adequate and avoids the complications of creating, managing and shutting down DirectInput (or XInput).Using the example from the article cited above, I'd modify it for DirectX something like the following:while( user doesn't exit ) check for user input // a PeekMessage loop, for instance CheckDeviceStatus if( device is ok ) run AI move enemies resolve collisions draw graphics play sounds else handle other conditions such as device lost, device unavailable, etc.end while[Edited by - Buckeye on November 19, 2010 12:10:21 PM]; For some reason I can't click on the link that you posted (it turns blue, but it doesn't actually do anything).Is checking device status on every loop iteration going to be resource intensive?The return types from those functions actually will set off that if statement if anything other than success is returned on that function. I will add additional handling for specific issues, but that one checks for failure of that function. If the device fails, that function will fail, and my loop will close. I know this because it's happened.This particular project is rather shoddy because I'm just poking things in to see if they'll work. I'm not all that interested in creating a performance-intensive project right now, because I can honestly say that I'm still missing a few of the basics. ; RE: the link. It's fixed now. I didn't check my own syntax. [embarrass]Quote:Is checking device status on every loop iteration going to be resource intensive?Nope.Quote:This particular project is rather shoddy because I'm just poking things in to see if they'll work. I'm not all that interested in creating a performance-intensive project right now, because I can honestly say that I'm still missing a few of the basics.I understand the interest in getting something working, and the comments I've made have nothing to do with making things performance-intensive. |
Model Formats | Graphics and GPU Programming;Programming | I was wondering if those of you that have implemented many model format's could advise me on a model format, or multiple formats, that I should consider using.My requirements are as follows:Scale well from small models to very large models (10k-50k polys most likely)Support dynamic animation types - Not to sure about this, all I know is that I will need to have multiple animations functioning at once - e.g A door opening and a window closing on a house, the animations for which being inside the model file itself.Load-speed will most likely not be an issue, but nothing monolithic obviously :PNot terribly difficult to parse. :DThis will be the first model importer that I write for my engine, so please don't suggest to me anything too difficult or cumbersome for my need's. Anything in the way of a tutorial for whichever model format you suggest will be greatly appreciated also. Thanks.[Edited by - Magmatwister on November 19, 2010 12:35:50 PM] | I'd suggest using a library that can do the hard work for you.You can use that to convert a 3d modelling format into something more game friendly. ;Quote:Original post by Adam_42I'd suggest using a library that can do the hard work for you.You can use that to convert a 3d modelling format into something more game friendly.Cheers, I'll look into it. |
Facebook Development Questions | For Beginners | Hi there, not sure if this is the right forum or if I should post this in the "Multi-player and Networking" bit.This question is not entirely related to Game Development Some friends and I are looking into making a Facebook application (a game) and I'm a little confused on exactly how it works. The game we am planning is 2D multi-player (NOT AN MMO) shooter style game where you can log on and challenge your friends to a game etc.Just a few questions:1/ Is it possible to use XNA? I assume it as as I only need some DLLs and Facebook supports .NET2/ I am a little confused by the server architecture do I need a hosted server? or can i somehow use a client as a server host? and just have a database on my server?Anyone got any experiance with this kinda thing can point me in the right direct?Cheers in advance ~Andy xD | I'm going to answer assuming you mean a game running inside a facebook page, rather than a stand-alone game which uses facebook for login.1)Probably notA quick bit of googling found this: http://silversprite.codeplex.com/I know nothing about it other than I found it when checking my answer to you.You might also like to check out using Unity instead - they support running in a web page and there are a few Unity games on facebook already.2)Yes you do. You need to be able to serve web pages.I suggest you create a facebook developer account and create a simple App. When you know a bit more about how facebook development works, you'll have a bit more perspective on your other questions.EDIT:It might have been better to post in Web Development forum about the facebook stuff, and in the DirectX forum about the XNA stuff. ; Facebook doesn't host any of the games or apps. They just provide a framework for your game to run from your server. Facebook people don't go for "installed" games, it has to be 100% through the broswer. I'm not sure if you can actually stream a XNA game like that. For C#, Silverlight is probably the way you need to go. ; Thanks man for the quick reply. :) much appreciatedSilverSprite looks EXACTLY what i need :D so defo gunna look into it.Now my question on servers is what i thought, however will a simple server do it? Heart internet I was looking at a Web Hosting package from this website. However, I am slightly numbish when it comes to Web server :) Question is, will that allow me todo what I want? Say use 1 player as a Host (server then on fb) store data on a database on here, and then be able to play? |
Handling sprite collision shapes to manage movement, overlap, and hit detection | General and Gameplay Programming;Programming | I am making a top-down view Zelda-like. I am using circles for the collision shapes of my actors, mainly because it allows easy sliding around corners. I want the sprites of my actors to overlap a bit to simulate perspective, but only by a set amount so that it is still clear what actors is what.Therefore, the collision circle of an actor placed at the bottom edge of. The problem is in hit detection for attacks and sizing the circle. Make the circle it too big and I have too much empty space for attack hit detection.Big collision circleMake the circle too small and I allow too much overlap between sprites.Small collision circleThis is making me think about having two collision shapes, one for movement and one for damage. But I still have to make sure that the movement collision shape isn't so big that it prevents one actor from reaching another actor's damage shape to attack it. | |
Linking a Library within a Library that has externs | General and Gameplay Programming;Programming | Hello,Im creating a library to interface into drawing a specific file type. This library needs to pull in a 3rd party library to do some processing on this specific file type. This 3rd party lib requires the users of it to create some extern functions that it uses to make data types on target hardware.So, it looks like this:------------| | | 3rd Party | | Lib| | | ------------ | |\/------------| | | My Lib | |-----------| | externs | ------------ | |\/------------| | | My App | | | | | ------------My App calls My Lib and says "draw me file X", My Lib does a bunch of junk eventually calling 3rd Party Lib and says "process file X". 3rd Party Lib requires several externs to be declared that it uses.I made all these externs inside My Lib. My problem is, when I link My App, its telling me undefined references to all the extern functions. I can't figure out why. Heres one of the externs inside My Lib to be called by 3rd Party Lib:// inside typeConversions.cextern int CreateShort(short* shortList, int numShorts){int i;for(i = 0; i < numShorts; i++){BYTE_SWAP_SHORT(shortList);}return ERROR_OK;}When I link My App I get (among several other similar errors):open.cpp: undefined reference to `CreateShort'Where open.cpp is inside the 3rd Party Lib.I have both My Lib and 3rd Party Lib included in My App. Ideally, I want to not expose users of My Lib to 3rd Party Lib, so for example My App would not have to include 3rd Party Lib at all, they dont know it even exists. All that should be exposed is My Lib. Is this possible? Anyone know how to fix my problem? | Your idea is sound. I just tried it out on Visual Studio 2005 by the following steps:1.) Created a new solution2.) Added two static lib projects and a Win32 executable project3.) Added a single cpp file to each lib3.) Placed a call to a function "MyFunction()" in the first lib4.) Added the line:extern "C" void MyFunction();To tell the compiler that "MyFunction" will be found at link time (i.e. it is "non-static"), with the "C" modifier to tell the compiler to leave off C++ symbol decoration.5.) Created the function:extern "C" void MyFunction() {}In the cpp file of the second lib.The linker joined the two libs just fine.Can you provide some information on your setup: the development environment you're using, and how you are building and linking the files.Also: don't forget about your option of using a DLL for your intermediate library, if that may fit your deployment better. ; Sorry, forgot to mention I'm using Eclipse 3.3.0 and My Lib is written in C. If I put " extern "C" " I get parse errors when compiling My Lib.I dont have any special flags set in the make properties, is there anything I should do in there? I've tried setting the -static flag, but that doesn't seem to do anything. |
Poll Results [11.11.10 - 11.15.10] - Text RPG Experiment | GDNet Lounge;Community | Last Action"you're out in the hinterlands east of the Feora River, we run a small farm here," says the woman. You see she is short and lean of frame, wiry muscles beneath her shirt and slacks show she is no simple kitchen maiden. "We discovered you unconscious in your camp - we saw your cooking fire smoke run up for two days straight and feared the bush afire." She steps into the room and a man follows, medium height with a dark beard and piercing eyes. "My husband carried you back here." The man gives you a nod but otherwise remains silent, his stare seems off-putting.[font="Courier New"]"Uhm, thanks - but I think I should leave now"-------------33----||||||-----------------------------9.64%"I come from over the mountains, I don't know this land"---71----|||||||||||||||--------------------20.7%[to the man] "Who are you looking at?"---------------------29----|||||------------------------------8.47%"Who are you two?"-----------------------------------------61----||||||||||||-----------------------17.8%"How long have I been asleep?"—————————–148—||||||||||||||||||||||||||||||||—43.2%<br /><br />Total Votes: 342<br /><br /><span style="font-weight:bold;">Backstory</span><br /><br />You are a traveler. Orphaned at a young age, you have survived on your own throughout your early years hopping from village to village and learning to live off the land. You began hearing stories from other travelers of a great civilization far off beyond the tall mountains. No one from there was willing or able to give you details - all they could remember was that it was grand and amazing. Curious, and with nothing to tie you to this land, you have set out to find this place. After crossing the mountains and a substantial desert on the other side, you have once again reached fertile land. You made camp beneath the trees for the first time in many weeks, but when you awoke again, you find yourself in a house with no memory of having traveled there.<br /><br /><span style="font-weight:bold;">Inventory</span><br /><br />[1] Strange-smelling fungus<br /><br /><span style="font-weight:bold;">Codex</span><br /><br /><ul><li>someone named "Ashwyn" appears to be a powerful… person?<li>you are in some region of the land know as the "hinterlands", east of a river known as the "Feora"</ol><br /><span style="font-weight:bold;">Story Log</span><br /><br />You wake up. The room is dark. Where are you? How did you get here? You see light beneath a door and hear voices in the next room speaking softly.<br /><span style="font-weight:bold;">> <a href='"http://www.gamedev.net/community/forums/topic.asp?topic_id=586553"'>Sneak up to the door and listen</a></span><br /><br />You get up and sneak over to the door. It is thick and wooden. Little sound gets through, but you hear a man and woman talking about someone named "Ashwyn". They sound fearful.<br /><span style="font-weight:bold;">> <a href='"http://www.gamedev.net/community/forums/topic.asp?topic_id=586825"'>Search the room</a></span><br /><br />With your eyes now adjusted to the dark, you carefully work your way around the room. The bed is a simple feather mattress on wood slats. Some empty shelves are on one wall, covered in dust. A low table resides in the corner. There are no windows. Your nose picks up a peculiar smell that leads you towards a blank wall, but as you get closer you see fungus growing on it. You scrape it off and put it in your pocket.<br /><span style="font-weight:bold;">> <a href='"http://www.gamedev.net/community/forums/topic.asp?topic_id=587221"'>Look for a way out</a></span><br /><br />You peer closely at the wall, wondering if perhaps the fungus meant there was a seam or doorway built there. Before you can complete your examination however you realize the conversation in the next room has stopped and footsteps approach the door. Before you can even decide what to do it swings open, flooding the room with light. As your eyes readjust, the voice of a woman speaks: "Oh good, you're awake!"<br /><span style="font-weight:bold;">> <a href='"http://www.gamedev.net/community/forums/topic.asp?topic_id=587485"'>"Where am I? How did I get here?"</a></span> | I have no idea why everyone voted to ask how long they'd been asleep for :(Really guys? ;Quote:Original post by WavarianI have no idea why everyone voted to ask how long they'd been asleep for :(Really guys?The girl was polite, so that answer seemed the most polite of all three choices.She hasn't introduced herself, but she gave us a pretty much hint of who they are, so asking who are they is a bit unnecessary, something more likely to be asked a bit later. The third option is rude and definitely we don't want to anger that guy. First option is unpolite, and if these guys are actually evil, they won't allow us to leave either way (rather than telling them I want to leave, a valid choice would've been to run away).Second option seems fair, proven we suspect the guys are up to something or we don't really belong there. The last option seems to be the most likely to give us more information about the whole situation from the girl. Or at least from what she wants us to believe.That's my reasoning ;Quote:Original post by WavarianI have no idea why everyone voted to ask how long they'd been asleep for :(Really guys?Hahahaha.To be honest I was quite surprised as well. Interesting analysis there Matias. I was actually expecting the second option to be picked - and it did come in second place - but holy wow I did not expect the last option to jump out with such a large margin!On the other hand I find it exciting that people aren't doing what I expect them to. Keeps me on my toes [smile] ; If you all want more background on what I'm doing here with this poll experiment, check out my blog:My first foray into Interactive FictionAgain, I'm really interested in feedback from participants!! ; Well, I picked no 2, oh Master of Puppets! ; As Matias said, the last option seemed most promising - I'm far more interested in why we were asleep for >2 days than in randomly telling people that I come from over the mountains. Given the woman said they run a farm who they were also seems less useful.I'm curious as to WTF we were cooking that meant the fire lasted for two days though?Also, if the woman isn't a kitchen maiden, is the guy a kitchen maiden? or me? now you've mentioned it I feel someone has to be a kitchen maiden! ;Quote:Original post by sprite_houndAlso, if the woman isn't a kitchen maiden, is the guy a kitchen maiden? or me? Stop spoiling stuff!! Jeeez [wink] ; What, was there no "Eat rope" option?! |
Request for clarification on inheritance in vb.net | General and Gameplay Programming;Programming | Okay, so I'm self taught and I've picked up enough knowledge to write high performance multithreaded threadsafe game servers for several hundred clients, but I'm apparently missing out on a lot of basic knowledge, heh.I have a class, 'skinny' version below, that is a base class. There are about 20 other classes that need to inherit this class. Not a problem yet. BUT. The base class has several New() subs that need to be common to all the derived classes. That's the point of a base class, correct? The base class's New subs are not exposed through the derived classes, and I was hoping to get around copy/pasting the polymorphed (baaa sheep) subs into every single derived class. Can someone enlighten me on what I'm missing and direct me somewhere where I can lose some of my ignorance? :)Sub Form_Load() ' Somewhat pseudocode Dim i As New Item ' I need all three of these to work as shown ' Hopefully not needing to paste all the New() code ' From the base class into 20 other classes Dim dc1 As New DerivedClass() Dim dc2 As New DerivedClass(i) Dim dc3 As New DerivedClass(1, 2, 3)End SubPublic MustInherit Class BaseHelper Public Sub New() ' Blah End Sub Public Sub New(i As Item) ' Blah End Sub Public Sub New(s1 As UInt32, s2 As UInt32) ' Blah End SubEnd ClassPublic Class DerivedClass1 : Inherits BaseHelper ' Random stuff specific to this classEnd Class | I dont think it is possible, did you check the error help?To correct this errorDeclare and implement at least one Sub New constructor somewhere in the derived class.Add a call to a base class constructor, MyBase.New(), as the first line of every Sub New.and if you google it you get pretty much the same answer. So i guess you have to declare a sub new in all derived classes.; Thanks for the confirmation. :) |
loading a texture in DirectX | For Beginners | I found a decent tutorial on loading a texture in DirectX using D3DXCreateTextureFromFile over here:http://www.drunkenhyena.com/cgi-bin/view_cpp_article.pl?chapter=2;article=30However, I can't figure out how to access the individual pixels of the texture. For instance, if I want to know if the pixel at x=100,y=100 in the texture is red, does anyone know how to do this? | Call lockrect on the texture and it will give you back a pointer to the data in the texture. And specify the rectangle you want to lock. http://msdn.microsoft.com/en-us/library/bb205913(VS.85).aspx for more info |
Apollo 69 Need Feedback | Your Announcements;Community | Hello everyone! Need your feedback on my first game (Facebook):Game LinkThank you all!:) | ">Game Teaser">Game Tutorial; ups:) |
blender. aplying a bump map. | 2D and 3D Art;Visual Arts | Hi.I have a mesh with texture coords, a colour map texture and a bump map texture. I can link the colour map to the mesh and blender will display it correctly. But how do i link the bump map to the same mesh?Thnx in Advance! | Before or after version 2.5? ; Im currently using version 2.49 but i supose il update to the latest instead of using outdated methods... Hope my export scripts dont need much modifying :D ; Considering that 2.5 is basically a from-the-ground-up rebuild, it is very likely that your scripts will need much updating. For instance, last I checked they haven't completed a full Ogre meshes exporter for 2.5.To get bump maps working in 2.49, add another texture to your material and load up the bump map. On the Shading(F5) panel, under the Map To buttons, deselect the button labeled Col (you don't want bump info contributing to color) and select the button labeled Nor (so that bump map affects surface normal). Beneath those buttons you will find a slider labeled Nor. Adjusting this slider up will increase the strength of your bumps. Tweak it until you get something you like. |
PBO issue using SDL | Graphics and GPU Programming;Programming | Currently I am using SDL for my openGL application which using Pixel Buffer Object (PBO) to capture screen pixels, an advanced buffer technique. The issue that I am facing currently is that after binding to the pbo, the pixels read time is much more than expected approx. 11ms. But if run the same application using GLUT library instead of PBO or using some plain windows programming in which the screen built using WinMain then it gives much faster read time of approx. 0.01 ms. The only difference between all these three applications is that the windows are built using different techniques. But all other code is exactly similar. I am also pasting my code here for review for all of the three different techniques.1. First code is using SDL (Read time is 11ms) ===========================================/* * SimpleSDL.cpp * SimpleSDL * * Created by david on 19/06/2010. */// in order to get function prototypes from glext.h, define GL_GLEXT_PROTOTYPES before including glext.h#define GL_GLEXT_PROTOTYPES#define SCREEN_WIDTH256//800#define SCREEN_HEIGHT256//600#define SCREEN_BPP32#include <iostream>#include <vector>#ifdef __APPLE__//Apple Headers//#include <OpenGL/OpenGL.h>#include <GLUT/glut.h>#include "SDL.h"#include "SDL_opengl.h"#else//Windows and linux headers#include "oglext\glext.h"#include "SDL.h"#include "SDL_opengl.h"#include <gl\gl.h>#include <gl\glu.h>#include "glut.h"#include <iostream>#include <sstream>#include <iomanip>#include "Timer.h"#include "glInfo.h" // glInfo struct#endifusing std::stringstream;using std::cout;using std::endl;using std::ends;// VBO Extension Definitions, From glext.h#define GL_ARRAY_BUFFER_ARB 0x8892#define GL_STATIC_DRAW_ARB 0x88E4typedef void (APIENTRY * PFNGLBINDBUFFERARBPROC) (GLenum target, GLuint buffer);typedef void (APIENTRY * PFNGLDELETEBUFFERSARBPROC) (GLsizei n, const GLuint *buffers);typedef void (APIENTRY * PFNGLGENBUFFERSARBPROC) (GLsizei n, GLuint *buffers);typedef void (APIENTRY * PFNGLBUFFERDATAARBPROC) (GLenum target, int size, const GLvoid *data, GLenum usage);typedef void (APIENTRY * PFNGLBUFFERSUBDATAARBPROC) (GLenum, GLintptrARB, GLsizeiptrARB, GLvoid const *);typedef void (APIENTRY * PFNGLGETBUFFERPARAMETERIVARBPROC) (GLenum, GLenum, GLint *);typedef GLvoid* (APIENTRY * PFNGLMAPBUFFERARBPROC) (GLenum, GLenum);typedef GLboolean* (APIENTRY * PFNGLUNMAPBUFFERARBPROC) (GLenum);//Surface for OpenGL to be drawn toSDL_Surface *screen = NULL;//False unti program quit by ESC or clicking top corner 'X'bool quit;//Keyboard and other Input Device eventsSDL_Event event;GLfloatrtri;// Angle For The Triangle ( NEW )GLfloatrquad;// Angle For The Quad ( NEW )// function pointers for PBO Extension// Windows needs to get function pointers from ICD OpenGL drivers,// because opengl32.dll does not support extensions higher than v1.1.#ifdef _WIN32PFNGLGENBUFFERSARBPROC pglGenBuffersARB = 0; // VBO Name Generation ProcedurePFNGLBINDBUFFERARBPROC pglBindBufferARB = 0; // VBO Bind ProcedurePFNGLBUFFERDATAARBPROC pglBufferDataARB = 0; // VBO Data Loading ProcedurePFNGLBUFFERSUBDATAARBPROC pglBufferSubDataARB = 0;// VBO Sub Data Loading ProcedurePFNGLDELETEBUFFERSARBPROC pglDeleteBuffersARB = 0;// VBO Deletion ProcedurePFNGLGETBUFFERPARAMETERIVARBPROC pglGetBufferParameterivARB = 0; // return various parameters of VBOPFNGLMAPBUFFERARBPROC pglMapBufferARB = 0; // map VBO procedurePFNGLUNMAPBUFFERARBPROC pglUnmapBufferARB = 0; // unmap VBO procedure#define glGenBuffersARB pglGenBuffersARB#define glBindBufferARB pglBindBufferARB#define glBufferDataARB pglBufferDataARB#define glBufferSubDataARB pglBufferSubDataARB#define glDeleteBuffersARB pglDeleteBuffersARB#define glGetBufferParameterivARB pglGetBufferParameterivARB#define glMapBufferARB pglMapBufferARB#define glUnmapBufferARBpglUnmapBufferARB#endif// constants//const int SCREEN_WIDTH = 256;//const int SCREEN_HEIGHT = 256;const int CHANNEL_COUNT = 4;const int DATA_SIZE = SCREEN_WIDTH * SCREEN_HEIGHT * CHANNEL_COUNT;const GLenum PIXEL_FORMAT = GL_BGRA;const int PBO_COUNT = 2;// global variablesvoid *font = GLUT_BITMAP_8_BY_13;bool pboSupported;GLubyte* colorBuffer = 0;bool pboUsed;GLuint pboIds[PBO_COUNT]; // IDs of PBOsfloat cameraAngleX;float cameraAngleY;float cameraDistance;Timer timer, t1;float readTime, processTime;//Methods In Programbool init();void init_GL();bool init_SDL();void clean_up();void display();void draw();void handle_input();///////////////////////////////////////////////////////////////////////////////// change the brightness///////////////////////////////////////////////////////////////////////////////void add(unsigned char* src, int width, int height, int shift, unsigned char* dst){ if(!src || !dst) return; int value; for(int i = 0; i < height; ++i) { for(int j = 0; j < width; ++j) { value = *src + shift; if(value > 255) *dst = (unsigned char)255; else *dst = (unsigned char)value; ++src; ++dst; value = *src + shift; if(value > 255) *dst = (unsigned char)255; else *dst = (unsigned char)value; ++src; ++dst; value = *src + shift; if(value > 255) *dst = (unsigned char)255; else *dst = (unsigned char)value; ++src; ++dst; ++src; // skip alpha ++dst; } }}void toOrtho(){ // set viewport to be the entire window glViewport((GLsizei)SCREEN_WIDTH, 0, (GLsizei)SCREEN_WIDTH, (GLsizei)SCREEN_HEIGHT); // set orthographic viewing frustum glMatrixMode(GL_PROJECTION); glLoadIdentity(); glOrtho(0, SCREEN_WIDTH, 0, SCREEN_HEIGHT, -1, 1); // switch to modelview matrix in order to set scene glMatrixMode(GL_MODELVIEW); glLoadIdentity(); gluLookAt(0, 0, 0, 0, 0, -1, 0, 1, 0); // eye(x,y,z), focal(x,y,z), up(x,y,z)}void toPerspective(){ // set viewport to be the entire window glViewport(0, 0, (GLsizei)SCREEN_WIDTH, (GLsizei)SCREEN_HEIGHT); // set perspective viewing frustum glMatrixMode(GL_PROJECTION); glLoadIdentity(); gluPerspective(60.0f, (float)(SCREEN_WIDTH)/SCREEN_HEIGHT, 1.0f, 1000.0f); // FOV, AspectRatio, NearClip, FarClip // switch to modelview matrix in order to set scene glMatrixMode(GL_MODELVIEW); glLoadIdentity(); gluLookAt(0, 0, 8, 0, 0, 0, 0, 1, 0); // eye(x,y,z), focal(x,y,z), up(x,y,z)}///////////////////////////////////////////////////////////////////////////////// write 2d text using GLUT// The projection matrix must be set to orthogonal before call this function.///////////////////////////////////////////////////////////////////////////////void drawString(const char *str, int x, int y, float color[4], void *font){ glPushAttrib(GL_LIGHTING_BIT | GL_CURRENT_BIT); // lighting and color mask glDisable(GL_LIGHTING);// need to disable lighting for proper text color glDisable(GL_TEXTURE_2D); glColor4fv(color);// set text color glRasterPos2i(x, y); // place text position // loop all characters in the string while(*str) { glutBitmapCharacter(font, *str); ++str; } glEnable(GL_TEXTURE_2D); glEnable(GL_LIGHTING); glPopAttrib();}///////////////////////////////////////////////////////////////////////////////// display info messages///////////////////////////////////////////////////////////////////////////////void showInfo(){ // backup current model-view matrix glPushMatrix(); // save current modelview matrix glLoadIdentity(); // reset modelview matrix // set to 2D orthogonal projection glMatrixMode(GL_PROJECTION);// switch to projection matrix glPushMatrix(); // save current projection matrix glLoadIdentity(); // reset projection matrix gluOrtho2D(0, SCREEN_WIDTH, 0, SCREEN_HEIGHT); // set to orthogonal projection const int FONT_HEIGHT = 14; float color[4] = {1, 1, 1, 1}; stringstream ss; ss << "PBO: "; if(pboUsed) ss << "on" << ends; else ss << "off" << ends; drawString(ss.str().c_str(), 1, SCREEN_HEIGHT-FONT_HEIGHT, color, font); ss.str(""); // clear buffer ss << "Read Time: " << readTime << " ms" << ends; drawString(ss.str().c_str(), 1, SCREEN_HEIGHT-(2*FONT_HEIGHT), color, font); ss.str(""); ss << std::fixed << std::setprecision(3); ss << "Process Time: " << processTime << " ms" << ends; drawString(ss.str().c_str(), 1, SCREEN_HEIGHT-(3*FONT_HEIGHT), color, font); ss.str(""); ss << "Press SPACE to toggle PBO." << ends; drawString(ss.str().c_str(), 1, 1, color, font); // unset floating format ss << std::resetiosflags(std::ios_base::fixed | std::ios_base::floatfield); // restore projection matrix glPopMatrix(); // restore to previous projection matrix // restore modelview matrix glMatrixMode(GL_MODELVIEW); // switch to modelview matrix glPopMatrix(); // restore to previous modelview matrix}///////////////////////////////////////////////////////////////////////////////// display transfer rates///////////////////////////////////////////////////////////////////////////////void showTransferRate(){ static Timer timer; static int count = 0; static stringstream ss; double elapsedTime; // backup current model-view matrix glPushMatrix(); // save current modelview matrix glLoadIdentity(); // reset modelview matrix // set to 2D orthogonal projection glMatrixMode(GL_PROJECTION); // switch to projection matrix glPushMatrix(); // save current projection matrix glLoadIdentity(); // reset projection matrix gluOrtho2D(0, SCREEN_WIDTH, 0, SCREEN_HEIGHT); // set to orthogonal projection float color[4] = {1, 1, 0, 1}; // update fps every second elapsedTime = timer.getElapsedTime(); if(elapsedTime < 1.0) { ++count; } else { ss.str(""); ss << std::fixed << std::setprecision(1); ss << "Transfer Rate: " << (count / elapsedTime) * (SCREEN_WIDTH * SCREEN_HEIGHT) / (1024 * 1024) << " Mp" << ends; // update fps string ss << std::resetiosflags(std::ios_base::fixed | std::ios_base::floatfield); count = 0; // reset counter timer.start(); // restart timer } drawString(ss.str().c_str(), 200, 286, color, font); // restore projection matrix glPopMatrix(); // restore to previous projection matrix // restore modelview matrix glMatrixMode(GL_MODELVIEW); // switch to modelview matrix glPopMatrix(); // restore to previous modelview matrix}///////////////////////////////////////////////////////////////////////////////// print transfer rates///////////////////////////////////////////////////////////////////////////////void printTransferRate(){ const double INV_MEGA = 1.0 / (1024 * 1024); static Timer timer; static int count = 0; static stringstream ss; double elapsedTime; // loop until 1 sec passed elapsedTime = timer.getElapsedTime(); if(elapsedTime < 1.0) { ++count; } else { cout << std::fixed << std::setprecision(1); cout << "Transfer Rate: " << (count / elapsedTime) * (SCREEN_WIDTH * SCREEN_HEIGHT) * INV_MEGA << " Mpixels/s. (" << count / elapsedTime << " FPS)\n"; cout << std::resetiosflags(std::ios_base::fixed | std::ios_base::floatfield); count = 0; // reset counter timer.start(); // restart timer }}int DrawLesson5Scene(GLvoid)// Here's Where We Do All The Drawing{//glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);// Clear Screen And Depth Buffer//glLoadIdentity();// Reset The Current Modelview MatrixglTranslatef(-1.5f,0.0f,-6.0f);// Move Left 1.5 Units And Into The Screen 6.0glRotatef(rtri,0.0f,1.0f,0.0f);// Rotate The Triangle On The Y axis ( NEW )glBegin(GL_TRIANGLES);// Start Drawing A TriangleglColor3f(1.0f,0.0f,0.0f);// RedglVertex3f( 0.0f, 1.0f, 0.0f);// Top Of Triangle (Front)glColor3f(0.0f,1.0f,0.0f);// GreenglVertex3f(-1.0f,-1.0f, 1.0f);// Left Of Triangle (Front)glColor3f(0.0f,0.0f,1.0f);// BlueglVertex3f( 1.0f,-1.0f, 1.0f);// Right Of Triangle (Front)glColor3f(1.0f,0.0f,0.0f);// RedglVertex3f( 0.0f, 1.0f, 0.0f);// Top Of Triangle (Right)glColor3f(0.0f,0.0f,1.0f);// BlueglVertex3f( 1.0f,-1.0f, 1.0f);// Left Of Triangle (Right)glColor3f(0.0f,1.0f,0.0f);// GreenglVertex3f( 1.0f,-1.0f, -1.0f);// Right Of Triangle (Right)glColor3f(1.0f,0.0f,0.0f);// RedglVertex3f( 0.0f, 1.0f, 0.0f);// Top Of Triangle (Back)glColor3f(0.0f,1.0f,0.0f);// GreenglVertex3f( 1.0f,-1.0f, -1.0f);// Left Of Triangle (Back)glColor3f(0.0f,0.0f,1.0f);// BlueglVertex3f(-1.0f,-1.0f, -1.0f);// Right Of Triangle (Back)glColor3f(1.0f,0.0f,0.0f);// RedglVertex3f( 0.0f, 1.0f, 0.0f);// Top Of Triangle (Left)glColor3f(0.0f,0.0f,1.0f);// BlueglVertex3f(-1.0f,-1.0f,-1.0f);// Left Of Triangle (Left)glColor3f(0.0f,1.0f,0.0f);// GreenglVertex3f(-1.0f,-1.0f, 1.0f);// Right Of Triangle (Left)glEnd();// Done Drawing The PyramidglLoadIdentity();// Reset The Current Modelview MatrixglTranslatef(1.5f,0.0f,-7.0f);// Move Right 1.5 Units And Into The Screen 7.0glRotatef(rquad,1.0f,1.0f,1.0f);// Rotate The Quad On The X axis ( NEW )glBegin(GL_QUADS);// Draw A QuadglColor3f(0.0f,1.0f,0.0f);// Set The Color To BlueglVertex3f( 1.0f, 1.0f,-1.0f);// Top Right Of The Quad (Top)glVertex3f(-1.0f, 1.0f,-1.0f);// Top Left Of The Quad (Top)glVertex3f(-1.0f, 1.0f, 1.0f);// Bottom Left Of The Quad (Top)glVertex3f( 1.0f, 1.0f, 1.0f);// Bottom Right Of The Quad (Top)glColor3f(1.0f,0.5f,0.0f);// Set The Color To OrangeglVertex3f( 1.0f,-1.0f, 1.0f);// Top Right Of The Quad (Bottom)glVertex3f(-1.0f,-1.0f, 1.0f);// Top Left Of The Quad (Bottom)glVertex3f(-1.0f,-1.0f,-1.0f);// Bottom Left Of The Quad (Bottom)glVertex3f( 1.0f,-1.0f,-1.0f);// Bottom Right Of The Quad (Bottom)glColor3f(1.0f,0.0f,0.0f);// Set The Color To RedglVertex3f( 1.0f, 1.0f, 1.0f);// Top Right Of The Quad (Front)glVertex3f(-1.0f, 1.0f, 1.0f);// Top Left Of The Quad (Front)glVertex3f(-1.0f,-1.0f, 1.0f);// Bottom Left Of The Quad (Front)glVertex3f( 1.0f,-1.0f, 1.0f);// Bottom Right Of The Quad (Front)glColor3f(1.0f,1.0f,0.0f);// Set The Color To YellowglVertex3f( 1.0f,-1.0f,-1.0f);// Top Right Of The Quad (Back)glVertex3f(-1.0f,-1.0f,-1.0f);// Top Left Of The Quad (Back)glVertex3f(-1.0f, 1.0f,-1.0f);// Bottom Left Of The Quad (Back)glVertex3f( 1.0f, 1.0f,-1.0f);// Bottom Right Of The Quad (Back)glColor3f(0.0f,0.0f,1.0f);// Set The Color To BlueglVertex3f(-1.0f, 1.0f, 1.0f);// Top Right Of The Quad (Left)glVertex3f(-1.0f, 1.0f,-1.0f);// Top Left Of The Quad (Left)glVertex3f(-1.0f,-1.0f,-1.0f);// Bottom Left Of The Quad (Left)glVertex3f(-1.0f,-1.0f, 1.0f);// Bottom Right Of The Quad (Left)glColor3f(1.0f,0.0f,1.0f);// Set The Color To VioletglVertex3f( 1.0f, 1.0f,-1.0f);// Top Right Of The Quad (Right)glVertex3f( 1.0f, 1.0f, 1.0f);// Top Left Of The Quad (Right)glVertex3f( 1.0f,-1.0f, 1.0f);// Bottom Left Of The Quad (Right)glVertex3f( 1.0f,-1.0f,-1.0f);// Bottom Right Of The Quad (Right)glEnd();// Done Drawing The Quadrtri+=0.2f;// Increase The Rotation Variable For The Triangle ( NEW )rquad-=0.15f;// Decrease The Rotation Variable For The Quad ( NEW )return TRUE;// Keep Going}int DrawGLScene(GLvoid)// Here's Where We Do All The Drawing{static int shift = 0; static int index = 0; int nextIndex = 0; // pbo index used for next frame // brightness shift amount shift = ++shift % 200; // increment current index first then get the next index // "index" is used to read pixels from a framebuffer to a PBO // "nextIndex" is used to process pixels in the other PBO index = (index + 1) % 2; nextIndex = (index + 1) % 2;// set the framebuffer to read glReadBuffer(GL_FRONT);GLuint* srcTex; if(pboUsed) // with PBO { // read framebuffer /////////////////////////////// timer.start(); // copy pixels from framebuffer to PBO // Use offset instead of ponter. // OpenGL should perform asynch DMA transfer, so glReadPixels() will return immediately. glBindBufferARB(GL_PIXEL_PACK_BUFFER_ARB, pboIds[index]);glReadPixels(0, 0, SCREEN_WIDTH, SCREEN_HEIGHT, PIXEL_FORMAT, GL_UNSIGNED_BYTE, 0);// measure the time reading framebuffer timer.stop(); readTime = timer.getElapsedTimeInMilliSec(); /////////////////////////////////////////////////// // process pixel data ///////////////////////////// // map the PBO that contain framebuffer pixels before processing it glBindBufferARB(GL_PIXEL_PACK_BUFFER_ARB, pboIds[nextIndex]); GLubyte* src = (GLubyte*) glMapBufferARB(GL_PIXEL_PACK_BUFFER_ARB, GL_READ_ONLY_ARB); if(src) { // change brightness add(src, SCREEN_WIDTH, SCREEN_HEIGHT, shift, colorBuffer); glUnmapBufferARB(GL_PIXEL_PACK_BUFFER_ARB);// release pointer to the mapped buffer } glBindBufferARB(GL_PIXEL_PACK_BUFFER_ARB, 0); } else // without PBO { // read framebuffer /////////////////////////////// timer.start(); // read framebuffer /////////////////////////////// glReadPixels(0, 0, SCREEN_WIDTH, SCREEN_HEIGHT, PIXEL_FORMAT, GL_UNSIGNED_BYTE, colorBuffer); // measure the time reading framebuffer timer.stop(); readTime = timer.getElapsedTimeInMilliSec(); /////////////////////////////////////////////////// // change brightness add(colorBuffer, SCREEN_WIDTH, SCREEN_HEIGHT, shift, colorBuffer); } // render to the framebuffer //////////////////////////glDrawBuffer(GL_BACK); toPerspective(); // set to perspective on the left side of the window // clear buffer glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT | GL_STENCIL_BUFFER_BIT); ////// tramsform camera //glTranslatef(0, 0, cameraDistance); //glRotatef(cameraAngleX, 1, 0, 0); // pitch //glRotatef(cameraAngleY, 0, 1, 0); // heading //// draw a cube //draw();DrawLesson5Scene(); // draw the read color buffer to the right side of the window toOrtho(); // set to orthographic on the right side of the window glRasterPos2i(0, 0);glDrawPixels(SCREEN_WIDTH, SCREEN_HEIGHT, PIXEL_FORMAT, GL_UNSIGNED_BYTE, colorBuffer);showInfo();printTransferRate();//glutSwapBuffers();return TRUE;// Keep Going}/*-------------------------------------------------- * Setup SDL *--------------------------------------------------*/bool init_SDL(){//Init all SDL Partsif(SDL_Init(SDL_INIT_EVERYTHING) == -1){return false;} //screen = SDL_SetVideoMode( SCREEN_WIDTH, SCREEN_HEIGHT, SCREEN_BPP, SDL_OPENGL | SDL_DOUBLEBUF | SDL_FULLSCREEN );//FULLSCREENscreen = SDL_SetVideoMode( SCREEN_WIDTH*2, SCREEN_HEIGHT, SCREEN_BPP, SDL_OPENGL | SDL_DOUBLEBUF);SDL_WM_SetCaption("Simple SDL Demo", NULL); return true;}/*-------------------------------------------------- * Init OpenGL *--------------------------------------------------*/void init_GL(){// get OpenGL info glInfo glInfo; glInfo.getInfo(); glInfo.printSelf();#ifdef _WIN32 // check PBO is supported by your video card if(glInfo.isExtensionSupported("GL_ARB_pixel_buffer_object")) { // get pointers to GL functions glGenBuffersARB = (PFNGLGENBUFFERSARBPROC)wglGetProcAddress("glGenBuffersARB"); glBindBufferARB = (PFNGLBINDBUFFERARBPROC)wglGetProcAddress("glBindBufferARB"); glBufferDataARB = (PFNGLBUFFERDATAARBPROC)wglGetProcAddress("glBufferDataARB"); glBufferSubDataARB = (PFNGLBUFFERSUBDATAARBPROC)wglGetProcAddress("glBufferSubDataARB"); glDeleteBuffersARB = (PFNGLDELETEBUFFERSARBPROC)wglGetProcAddress("glDeleteBuffersARB"); glGetBufferParameterivARB = (PFNGLGETBUFFERPARAMETERIVARBPROC)wglGetProcAddress("glGetBufferParameterivARB"); glMapBufferARB = (PFNGLMAPBUFFERARBPROC)wglGetProcAddress("glMapBufferARB"); glUnmapBufferARB = (PFNGLUNMAPBUFFERARBPROC)wglGetProcAddress("glUnmapBufferARB"); // check once again PBO extension if(glGenBuffersARB && glBindBufferARB && glBufferDataARB && glBufferSubDataARB && glMapBufferARB && glUnmapBufferARB && glDeleteBuffersARB && glGetBufferParameterivARB) { pboSupported = pboUsed = true; //cout << "Video card supports GL_ARB_pixel_buffer_object." << endl; } else { pboSupported = pboUsed = false; // cout << "Video card does NOT support GL_ARB_pixel_buffer_object." << endl; } }#else // for linux, do not need to get function pointers, it is up-to-date if(glInfo.isExtensionSupported("GL_ARB_pixel_buffer_object")) { pboSupported = pboUsed = true; cout << "Video card supports GL_ARB_pixel_buffer_object." << endl; } else { pboSupported = pboUsed = false; cout << "Video card does NOT support GL_ARB_pixel_buffer_object." << endl; }#endifif(pboSupported) { // create 2 pixel buffer objects, you need to delete them when program exits. // glBufferDataARB with NULL pointer reserves only memory space. glGenBuffersARB(PBO_COUNT, pboIds); glBindBufferARB(GL_PIXEL_PACK_BUFFER_ARB, pboIds[0]); glBufferDataARB(GL_PIXEL_PACK_BUFFER_ARB, DATA_SIZE, 0, GL_STREAM_READ_ARB); glBindBufferARB(GL_PIXEL_PACK_BUFFER_ARB, pboIds[1]); glBufferDataARB(GL_PIXEL_PACK_BUFFER_ARB, DATA_SIZE, 0, GL_STREAM_READ_ARB); glBindBufferARB(GL_PIXEL_PACK_BUFFER_ARB, 0); }glShadeModel(GL_SMOOTH);// Enable Smooth ShadingglClearColor(0.0f, 0.0f, 0.0f, 0.5f);// Black BackgroundglClearDepth(1.0f);// Depth Buffer SetupglEnable(GL_DEPTH_TEST);// Enables Depth TestingglDepthFunc(GL_LEQUAL);// The Type Of Depth Testing To DoglHint(GL_PERSPECTIVE_CORRECTION_HINT, GL_NICEST);// Really Nice Perspective Calculations//glClearColor(0.8, 0.7, 0.9, 1.0);glViewport(0, 0, SCREEN_WIDTH, SCREEN_HEIGHT);}/*-------------------------------------------------- * Init Everything *--------------------------------------------------*/bool init(){// allocate buffers to store frames colorBuffer = new GLubyte[DATA_SIZE]; memset(colorBuffer, 255, DATA_SIZE);if(init_SDL() == false){std::cout << "Setting Up SDL Failed - Now Exiting or Crashing" << std::endl;return false;}elsestd::cout<< "SDL Initialized " << std::endl; init_GL();std::cout << "OpenGL Initialized" << std::endl; quit = false; return true;}/*----------------------------------------------------------------- *Clean Up RAM Before Quitting *----------------------------------------------------------------- */void clean_up(){// deallocate frame buffer delete [] colorBuffer; colorBuffer = 0;// clean up PBOs if(pboSupported) { glDeleteBuffersARB(PBO_COUNT, pboIds); }//Close All SDL SubsystemsSDL_Quit();}/*-------------------------------------------------- *Draw Scene Code *--------------------------------------------------*/void draw(){glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT); glMatrixMode(GL_PROJECTION);glLoadIdentity();gluPerspective(43.0, SCREEN_WIDTH/SCREEN_HEIGHT, 1, 50);glMatrixMode(GL_MODELVIEW);glLoadIdentity();//DRAW CODE HERESDL_GL_SwapBuffers();}/*-------------------------------------------------- * Handle input Code *--------------------------------------------------*/void handle_input(){if(SDL_PollEvent(&event)){switch(event.type){case SDL_KEYDOWN:switch(event.key.keysym.sym){//ESCAPEcase SDLK_ESCAPE:quit = true;break;//SPACEdefault:break;}break;//EXIT SYSTEMcase SDL_QUIT:quit = true;break;}}}/*----------------------------------------------------------------- *Main Method *----------------------------------------------------------------- */int main(int argc, char *args[]){if(init() == false){std::cout << "Problem Initialising" << std::endl;return 1;} do{//GAME MAIN LOOP GOES HERE handle_input();//draw();DrawGLScene();SDL_GL_SwapBuffers(); }while(!quit); clean_up();return 0; }================================================================================================================================================================2. Second technique is using GLUT Library (Read time: 0.01ms approx.) ===================================================================///////////////////////////////////////////////////////////////////////////////// main.cpp// ========// testing Pixel Buffer Object for packing (read-back) pixel data from// framebuffer to a PBO using GL_ARB_pixel_buffer_object extension//// AUTHOR: Song Ho Ahn ([email protected])// CREATED: 2007-11-30// UPDATED: 2008-06-12///////////////////////////////////////////////////////////////////////////////// in order to get function prototypes from glext.h, define GL_GLEXT_PROTOTYPES before including glext.h#define GL_GLEXT_PROTOTYPES#include <cstdlib>#ifdef __APPLE__#include <GLUT/glut.h>#else#include "glut.h"#endif#include "glext.h"#include <iostream>#include <sstream>#include <iomanip>#include "glInfo.h" // glInfo struct#include "Timer.h"using std::stringstream;using std::cout;using std::endl;using std::ends;// GLUT CALLBACK functionsvoid displayCB();void reshapeCB(int w, int h);void timerCB(int millisec);void idleCB();void keyboardCB(unsigned char key, int x, int y);void mouseCB(int button, int stat, int x, int y);void mouseMotionCB(int x, int y);void initGL();int initGLUT(int argc, char **argv);bool initSharedMem();void clearSharedMem();void initLights();void setCamera(float posX, float posY, float posZ, float targetX, float targetY, float targetZ);void drawString(const char *str, int x, int y, float color[4], void *font);void drawString3D(const char *str, float pos[3], float color[4], void *font);void showInfo();void showTransferRate();void printTransferRate();void draw();void add(unsigned char* src, int width, int height, int shift, unsigned char* dst);void toOrtho();void toPerspective();// constantsconst int SCREEN_WIDTH = 256;const int SCREEN_HEIGHT = 256;const int CHANNEL_COUNT = 4;const int DATA_SIZE = SCREEN_WIDTH * SCREEN_HEIGHT * CHANNEL_COUNT;const GLenum PIXEL_FORMAT = GL_BGRA;const int PBO_COUNT = 2;// global variablesvoid *font = GLUT_BITMAP_8_BY_13;GLuint pboIds[PBO_COUNT]; // IDs of PBOsbool mouseLeftDown;bool mouseRightDown;float mouseX, mouseY;float cameraAngleX;float cameraAngleY;float cameraDistance;bool pboSupported;bool pboUsed;int drawMode = 0;Timer timer, t1;float readTime, processTime;GLubyte* colorBuffer = 0;// function pointers for PBO Extension// Windows needs to get function pointers from ICD OpenGL drivers,// because opengl32.dll does not support extensions higher than v1.1.#ifdef _WIN32PFNGLGENBUFFERSARBPROC pglGenBuffersARB = 0; // VBO Name Generation ProcedurePFNGLBINDBUFFERARBPROC pglBindBufferARB = 0; // VBO Bind ProcedurePFNGLBUFFERDATAARBPROC pglBufferDataARB = 0; // VBO Data Loading ProcedurePFNGLBUFFERSUBDATAARBPROC pglBufferSubDataARB = 0;// VBO Sub Data Loading ProcedurePFNGLDELETEBUFFERSARBPROC pglDeleteBuffersARB = 0;// VBO Deletion ProcedurePFNGLGETBUFFERPARAMETERIVARBPROC pglGetBufferParameterivARB = 0; // return various parameters of VBOPFNGLMAPBUFFERARBPROC pglMapBufferARB = 0; // map VBO procedurePFNGLUNMAPBUFFERARBPROC pglUnmapBufferARB = 0; // unmap VBO procedure#define glGenBuffersARB pglGenBuffersARB#define glBindBufferARB pglBindBufferARB#define glBufferDataARB pglBufferDataARB#define glBufferSubDataARB pglBufferSubDataARB#define glDeleteBuffersARB pglDeleteBuffersARB#define glGetBufferParameterivARB pglGetBufferParameterivARB#define glMapBufferARB pglMapBufferARB#define glUnmapBufferARBpglUnmapBufferARB#endif///////////////////////////////////////////////////////////////////////////////// draw a cube with immediate mode// 54 calls = 24 glVertex*() calls + 24 glColor*() calls + 6 glNormal*() calls///////////////////////////////////////////////////////////////////////////////void draw(){ glBegin(GL_QUADS); // face v0-v1-v2-v3 glNormal3f(0,0,1); glColor3f(1,1,1); glVertex3f(1,1,1); glColor3f(1,1,0); glVertex3f(-1,1,1); glColor3f(1,0,0); glVertex3f(-1,-1,1); glColor3f(1,0,1); glVertex3f(1,-1,1); // face v0-v3-v4-v6 glNormal3f(1,0,0); glColor3f(1,1,1); glVertex3f(1,1,1); glColor3f(1,0,1); glVertex3f(1,-1,1); glColor3f(0,0,1); glVertex3f(1,-1,-1); glColor3f(0,1,1); glVertex3f(1,1,-1); // face v0-v5-v6-v1 glNormal3f(0,1,0); glColor3f(1,1,1); glVertex3f(1,1,1); glColor3f(0,1,1); glVertex3f(1,1,-1); glColor3f(0,1,0); glVertex3f(-1,1,-1); glColor3f(1,1,0); glVertex3f(-1,1,1); // face v1-v6-v7-v2 glNormal3f(-1,0,0); glColor3f(1,1,0); glVertex3f(-1,1,1); glColor3f(0,1,0); glVertex3f(-1,1,-1); glColor3f(0,0,0); glVertex3f(-1,-1,-1); glColor3f(1,0,0); glVertex3f(-1,-1,1); // face v7-v4-v3-v2 glNormal3f(0,-1,0); glColor3f(0,0,0); glVertex3f(-1,-1,-1); glColor3f(0,0,1); glVertex3f(1,-1,-1); glColor3f(1,0,1); glVertex3f(1,-1,1); glColor3f(1,0,0); glVertex3f(-1,-1,1); // face v4-v7-v6-v5 glNormal3f(0,0,-1); glColor3f(0,0,1); glVertex3f(1,-1,-1); glColor3f(0,0,0); glVertex3f(-1,-1,-1); glColor3f(0,1,0); glVertex3f(-1,1,-1); glColor3f(0,1,1); glVertex3f(1,1,-1); glEnd();}///////////////////////////////////////////////////////////////////////////////int main(int argc, char **argv){ initSharedMem(); // init GLUT and GL initGLUT(argc, argv); initGL(); // get OpenGL info glInfo glInfo; glInfo.getInfo(); glInfo.printSelf();#ifdef _WIN32 // check PBO is supported by your video card if(glInfo.isExtensionSupported("GL_ARB_pixel_buffer_object")) { // get pointers to GL functions glGenBuffersARB = (PFNGLGENBUFFERSARBPROC)wglGetProcAddress("glGenBuffersARB"); glBindBufferARB = (PFNGLBINDBUFFERARBPROC)wglGetProcAddress("glBindBufferARB"); glBufferDataARB = (PFNGLBUFFERDATAARBPROC)wglGetProcAddress("glBufferDataARB"); glBufferSubDataARB = (PFNGLBUFFERSUBDATAARBPROC)wglGetProcAddress("glBufferSubDataARB"); glDeleteBuffersARB = (PFNGLDELETEBUFFERSARBPROC)wglGetProcAddress("glDeleteBuffersARB"); glGetBufferParameterivARB = (PFNGLGETBUFFERPARAMETERIVARBPROC)wglGetProcAddress("glGetBufferParameterivARB"); glMapBufferARB = (PFNGLMAPBUFFERARBPROC)wglGetProcAddress("glMapBufferARB"); glUnmapBufferARB = (PFNGLUNMAPBUFFERARBPROC)wglGetProcAddress("glUnmapBufferARB"); // check once again PBO extension if(glGenBuffersARB && glBindBufferARB && glBufferDataARB && glBufferSubDataARB && glMapBufferARB && glUnmapBufferARB && glDeleteBuffersARB && glGetBufferParameterivARB) { pboSupported = pboUsed = true; cout << "Video card supports GL_ARB_pixel_buffer_object." << endl; } else { pboSupported = pboUsed = false; cout << "Video card does NOT support GL_ARB_pixel_buffer_object." << endl; } }#else // for linux, do not need to get function pointers, it is up-to-date if(glInfo.isExtensionSupported("GL_ARB_pixel_buffer_object")) { pboSupported = pboUsed = true; cout << "Video card supports GL_ARB_pixel_buffer_object." << endl; } else { pboSupported = pboUsed = false; cout << "Video card does NOT support GL_ARB_pixel_buffer_object." << endl; }#endif if(pboSupported) { // create 2 pixel buffer objects, you need to delete them when program exits. // glBufferDataARB with NULL pointer reserves only memory space. glGenBuffersARB(PBO_COUNT, pboIds); glBindBufferARB(GL_PIXEL_PACK_BUFFER_ARB, pboIds[0]); glBufferDataARB(GL_PIXEL_PACK_BUFFER_ARB, DATA_SIZE, 0, GL_STREAM_READ_ARB); glBindBufferARB(GL_PIXEL_PACK_BUFFER_ARB, pboIds[1]); glBufferDataARB(GL_PIXEL_PACK_BUFFER_ARB, DATA_SIZE, 0, GL_STREAM_READ_ARB); glBindBufferARB(GL_PIXEL_PACK_BUFFER_ARB, 0); } // start timer, the elapsed time will be used for updateVertices() timer.start(); // the last GLUT call (LOOP) // window will be shown and display callback is triggered by events // NOTE: this call never return main(). glutMainLoop(); /* Start GLUT event-processing loop */ return 0;}///////////////////////////////////////////////////////////////////////////////// initialize GLUT for windowing///////////////////////////////////////////////////////////////////////////////int initGLUT(int argc, char **argv){ // GLUT stuff for windowing // initialization openGL window. // it is called before any other GLUT routine glutInit(&argc, argv); glutInitDisplayMode(GLUT_RGB | GLUT_DOUBLE | GLUT_ALPHA); // display mode glutInitWindowSize(SCREEN_WIDTH*2, SCREEN_HEIGHT); // window size glutInitWindowPosition(100, 100); // window location // finally, create a window with openGL context // Window will not displayed until glutMainLoop() is called // it returns a unique ID int handle = glutCreateWindow(argv[0]);// param is the title of window // register GLUT callback functions glutDisplayFunc(displayCB); //glutTimerFunc(33, timerCB, 33); // redraw only every given millisec glutIdleFunc(idleCB); // redraw only every given millisec glutReshapeFunc(reshapeCB); glutKeyboardFunc(keyboardCB); glutMouseFunc(mouseCB); glutMotionFunc(mouseMotionCB); return handle;}///////////////////////////////////////////////////////////////////////////////// initialize OpenGL// disable unused features///////////////////////////////////////////////////////////////////////////////void initGL(){ glShadeModel(GL_SMOOTH);// shading mathod: GL_SMOOTH or GL_FLAT glPixelStorei(GL_UNPACK_ALIGNMENT, 4); // 4-byte pixel alignment // enable /disable features glHint(GL_PERSPECTIVE_CORRECTION_HINT, GL_NICEST); //glHint(GL_LINE_SMOOTH_HINT, GL_NICEST); //glHint(GL_POLYGON_SMOOTH_HINT, GL_NICEST); glEnable(GL_DEPTH_TEST); glEnable(GL_LIGHTING); glEnable(GL_TEXTURE_2D); glEnable(GL_CULL_FACE);// track material ambient and diffuse from surface color, call it before glEnable(GL_COLOR_MATERIAL) glColorMaterial(GL_FRONT_AND_BACK, GL_AMBIENT_AND_DIFFUSE); glEnable(GL_COLOR_MATERIAL); glClearColor(0, 0, 0, 0); // background color glClearStencil(0); // clear stencil buffer glClearDepth(1.0f);// 0 is near, 1 is far glDepthFunc(GL_LEQUAL); initLights(); //setCamera(0, 0, 8, 0, 0, 0);}///////////////////////////////////////////////////////////////////////////////// write 2d text using GLUT// The projection matrix must be set to orthogonal before call this function.///////////////////////////////////////////////////////////////////////////////void drawString(const char *str, int x, int y, float color[4], void *font){ glPushAttrib(GL_LIGHTING_BIT | GL_CURRENT_BIT); // lighting and color mask glDisable(GL_LIGHTING);// need to disable lighting for proper text color glDisable(GL_TEXTURE_2D); glColor4fv(color);// set text color glRasterPos2i(x, y); // place text position // loop all characters in the string while(*str) { glutBitmapCharacter(font, *str); ++str; } glEnable(GL_TEXTURE_2D); glEnable(GL_LIGHTING); glPopAttrib();}///////////////////////////////////////////////////////////////////////////////// draw a string in 3D space///////////////////////////////////////////////////////////////////////////////void drawString3D(const char *str, float pos[3], float color[4], void *font){ glPushAttrib(GL_LIGHTING_BIT | GL_CURRENT_BIT); // lighting and color mask glDisable(GL_LIGHTING);// need to disable lighting for proper text color glColor4fv(color);// set text color glRasterPos3fv(pos); // place text position // loop all characters in the string while(*str) { glutBitmapCharacter(font, *str); ++str; } glEnable(GL_LIGHTING); glPopAttrib();}///////////////////////////////////////////////////////////////////////////////// initialize global variables///////////////////////////////////////////////////////////////////////////////bool initSharedMem(){ mouseLeftDown = mouseRightDown = false; // allocate buffers to store frames colorBuffer = new GLubyte[DATA_SIZE]; memset(colorBuffer, 255, DATA_SIZE); return true;}///////////////////////////////////////////////////////////////////////////////// clean up shared memory///////////////////////////////////////////////////////////////////////////////void clearSharedMem(){ // deallocate frame buffer delete [] colorBuffer; colorBuffer = 0; // clean up PBOs if(pboSupported) { glDeleteBuffersARB(PBO_COUNT, pboIds); }}///////////////////////////////////////////////////////////////////////////////// initialize lights///////////////////////////////////////////////////////////////////////////////void initLights(){ // set up light colors (ambient, diffuse, specular) GLfloat lightKa[] = {.2f, .2f, .2f, 1.0f}; // ambient light GLfloat lightKd[] = {.7f, .7f, .7f, 1.0f}; // diffuse light GLfloat lightKs[] = {1, 1, 1, 1}; // specular light glLightfv(GL_LIGHT0, GL_AMBIENT, lightKa); glLightfv(GL_LIGHT0, GL_DIFFUSE, lightKd); glLightfv(GL_LIGHT0, GL_SPECULAR, lightKs); // position the light float lightPos[4] = {0, 0, 20, 1}; // positional light glLightfv(GL_LIGHT0, GL_POSITION, lightPos); glEnable(GL_LIGHT0); // MUST enable each light source after configuration}///////////////////////////////////////////////////////////////////////////////// set camera position and lookat direction///////////////////////////////////////////////////////////////////////////////void setCamera(float posX, float posY, float posZ, float targetX, float targetY, float targetZ){ glMatrixMode(GL_MODELVIEW); glLoadIdentity(); gluLookAt(posX, posY, posZ, targetX, targetY, targetZ, 0, 1, 0); // eye(x,y,z), focal(x,y,z), up(x,y,z)}///////////////////////////////////////////////////////////////////////////////// display info messages///////////////////////////////////////////////////////////////////////////////void showInfo(){ // backup current model-view matrix glPushMatrix(); // save current modelview matrix glLoadIdentity(); // reset modelview matrix // set to 2D orthogonal projection glMatrixMode(GL_PROJECTION);// switch to projection matrix glPushMatrix(); // save current projection matrix glLoadIdentity(); // reset projection matrix gluOrtho2D(0, SCREEN_WIDTH, 0, SCREEN_HEIGHT); // set to orthogonal projection const int FONT_HEIGHT = 14; float color[4] = {1, 1, 1, 1}; stringstream ss; ss << "PBO: "; if(pboUsed) ss << "on" << ends; else ss << "off" << ends; drawString(ss.str().c_str(), 1, SCREEN_HEIGHT-FONT_HEIGHT, color, font); ss.str(""); // clear buffer ss << "Read Time: " << readTime << " ms" << ends; drawString(ss.str().c_str(), 1, SCREEN_HEIGHT-(2*FONT_HEIGHT), color, font); ss.str(""); ss << std::fixed << std::setprecision(3); ss << "Process Time: " << processTime << " ms" << ends; drawString(ss.str().c_str(), 1, SCREEN_HEIGHT-(3*FONT_HEIGHT), color, font); ss.str(""); ss << "Press SPACE to toggle PBO." << ends; drawString(ss.str().c_str(), 1, 1, color, font); // unset floating format ss << std::resetiosflags(std::ios_base::fixed | std::ios_base::floatfield); // restore projection matrix glPopMatrix(); // restore to previous projection matrix // restore modelview matrix glMatrixMode(GL_MODELVIEW); // switch to modelview matrix glPopMatrix(); // restore to previous modelview matrix}///////////////////////////////////////////////////////////////////////////////// display transfer rates///////////////////////////////////////////////////////////////////////////////void showTransferRate(){ static Timer timer; static int count = 0; static stringstream ss; double elapsedTime; // backup current model-view matrix glPushMatrix(); // save current modelview matrix glLoadIdentity(); // reset modelview matrix // set to 2D orthogonal projection glMatrixMode(GL_PROJECTION); // switch to projection matrix glPushMatrix(); // save current projection matrix glLoadIdentity(); // reset projection matrix gluOrtho2D(0, SCREEN_WIDTH, 0, SCREEN_HEIGHT); // set to orthogonal projection float color[4] = {1, 1, 0, 1}; // update fps every second elapsedTime = timer.getElapsedTime(); if(elapsedTime < 1.0) { ++count; } else { ss.str(""); ss << std::fixed << std::setprecision(1); ss << "Transfer Rate: " << (count / elapsedTime) * (SCREEN_WIDTH * SCREEN_HEIGHT) / (1024 * 1024) << " Mp" << ends; // update fps string ss << std::resetiosflags(std::ios_base::fixed | std::ios_base::floatfield); count = 0; // reset counter timer.start(); // restart timer } drawString(ss.str().c_str(), 200, 286, color, font); // restore projection matrix glPopMatrix(); // restore to previous projection matrix // restore modelview matrix glMatrixMode(GL_MODELVIEW); // switch to modelview matrix glPopMatrix(); // restore to previous modelview matrix}///////////////////////////////////////////////////////////////////////////////// print transfer rates///////////////////////////////////////////////////////////////////////////////void printTransferRate(){ const double INV_MEGA = 1.0 / (1024 * 1024); static Timer timer; static int count = 0; static stringstream ss; double elapsedTime; // loop until 1 sec passed elapsedTime = timer.getElapsedTime(); if(elapsedTime < 1.0) { ++count; } else { cout << std::fixed << std::setprecision(1); cout << "Transfer Rate: " << (count / elapsedTime) * (SCREEN_WIDTH * SCREEN_HEIGHT) * INV_MEGA << " Mpixels/s. (" << count / elapsedTime << " FPS)\n"; cout << std::resetiosflags(std::ios_base::fixed | std::ios_base::floatfield); count = 0; // reset counter timer.start(); // restart timer }}///////////////////////////////////////////////////////////////////////////////// change the brightness///////////////////////////////////////////////////////////////////////////////void add(unsigned char* src, int width, int height, int shift, unsigned char* dst){ if(!src || !dst) return; int value; for(int i = 0; i < height; ++i) { for(int j = 0; j < width; ++j) { value = *src + shift; if(value > 255) *dst = (unsigned char)255; else *dst = (unsigned char)value; ++src; ++dst; value = *src + shift; if(value > 255) *dst = (unsigned char)255; else *dst = (unsigned char)value; ++src; ++dst; value = *src + shift; if(value > 255) *dst = (unsigned char)255; else *dst = (unsigned char)value; ++src; ++dst; ++src; // skip alpha ++dst; } }}void toOrtho(){ // set viewport to be the entire window glViewport((GLsizei)SCREEN_WIDTH, 0, (GLsizei)SCREEN_WIDTH, (GLsizei)SCREEN_HEIGHT); // set orthographic viewing frustum glMatrixMode(GL_PROJECTION); glLoadIdentity(); glOrtho(0, SCREEN_WIDTH, 0, SCREEN_HEIGHT, -1, 1); // switch to modelview matrix in order to set scene glMatrixMode(GL_MODELVIEW); glLoadIdentity(); gluLookAt(0, 0, 0, 0, 0, -1, 0, 1, 0); // eye(x,y,z), focal(x,y,z), up(x,y,z)}void toPerspective(){ // set viewport to be the entire window glViewport(0, 0, (GLsizei)SCREEN_WIDTH, (GLsizei)SCREEN_HEIGHT); // set perspective viewing frustum glMatrixMode(GL_PROJECTION); glLoadIdentity(); gluPerspective(60.0f, (float)(SCREEN_WIDTH)/SCREEN_HEIGHT, 1.0f, 1000.0f); // FOV, AspectRatio, NearClip, FarClip // switch to modelview matrix in order to set scene glMatrixMode(GL_MODELVIEW); glLoadIdentity(); gluLookAt(0, 0, 8, 0, 0, 0, 0, 1, 0); // eye(x,y,z), focal(x,y,z), up(x,y,z)}//=============================================================================// CALLBACKS//=============================================================================void displayCB(){ static int shift = 0; static int index = 0; int nextIndex = 0; // pbo index used for next frame // brightness shift amount shift = ++shift % 200; // increment current index first then get the next index // "index" is used to read pixels from a framebuffer to a PBO // "nextIndex" is used to process pixels in the other PBO index = (index + 1) % 2; nextIndex = (index + 1) % 2; // set the framebuffer to read glReadBuffer(GL_FRONT); if(pboUsed) // with PBO { // read framebuffer /////////////////////////////// t1.start(); // copy pixels from framebuffer to PBO // Use offset instead of ponter. // OpenGL should perform asynch DMA transfer, so glReadPixels() will return immediately. glBindBufferARB(GL_PIXEL_PACK_BUFFER_ARB, pboIds[index]); glReadPixels(0, 0, SCREEN_WIDTH, SCREEN_HEIGHT, PIXEL_FORMAT, GL_UNSIGNED_BYTE, 0); // measure the time reading framebuffer t1.stop(); readTime = t1.getElapsedTimeInMilliSec(); /////////////////////////////////////////////////// // process pixel data ///////////////////////////// t1.start(); // map the PBO that contain framebuffer pixels before processing it glBindBufferARB(GL_PIXEL_PACK_BUFFER_ARB, pboIds[nextIndex]); GLubyte* src = (GLubyte*)glMapBufferARB(GL_PIXEL_PACK_BUFFER_ARB, GL_READ_ONLY_ARB); if(src) { // change brightness add(src, SCREEN_WIDTH, SCREEN_HEIGHT, shift, colorBuffer); glUnmapBufferARB(GL_PIXEL_PACK_BUFFER_ARB);// release pointer to the mapped buffer } // measure the time reading framebuffer t1.stop(); processTime = t1.getElapsedTimeInMilliSec(); /////////////////////////////////////////////////// glBindBufferARB(GL_PIXEL_PACK_BUFFER_ARB, 0); } else // without PBO { // read framebuffer /////////////////////////////// t1.start(); glReadPixels(0, 0, SCREEN_WIDTH, SCREEN_HEIGHT, PIXEL_FORMAT, GL_UNSIGNED_BYTE, colorBuffer); // measure the time reading framebuffer t1.stop(); readTime = t1.getElapsedTimeInMilliSec(); /////////////////////////////////////////////////// // covert to greyscale //////////////////////////// t1.start(); // change brightness add(colorBuffer, SCREEN_WIDTH, SCREEN_HEIGHT, shift, colorBuffer); // measure the time reading framebuffer t1.stop(); processTime = t1.getElapsedTimeInMilliSec(); /////////////////////////////////////////////////// } // render to the framebuffer ////////////////////////// glDrawBuffer(GL_BACK); toPerspective(); // set to perspective on the left side of the window // clear buffer glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT | GL_STENCIL_BUFFER_BIT); // tramsform camera glTranslatef(0, 0, cameraDistance); glRotatef(cameraAngleX, 1, 0, 0); // pitch glRotatef(cameraAngleY, 0, 1, 0); // heading // draw a cube draw(); // draw the read color buffer to the right side of the window toOrtho(); // set to orthographic on the right side of the window glRasterPos2i(0, 0); glDrawPixels(SCREEN_WIDTH, SCREEN_HEIGHT, PIXEL_FORMAT, GL_UNSIGNED_BYTE, colorBuffer); // draw info messages showInfo(); printTransferRate(); glutSwapBuffers();}void reshapeCB(int w, int h){ toPerspective();}void timerCB(int millisec){ glutTimerFunc(millisec, timerCB, millisec); glutPostRedisplay();}void idleCB(){ glutPostRedisplay();}void keyboardCB(unsigned char key, int x, int y){ switch(key) { case 27: // ESCAPE clearSharedMem(); //exit(0); break; case ' ': if(pboSupported) pboUsed = !pboUsed; cout << "PBO mode: " << (pboUsed ? "on" : "off") << endl; break; case 'd': // switch rendering modes (fill -> wire -> point) case 'D': drawMode = ++drawMode % 3; if(drawMode == 0) // fill mode { glPolygonMode(GL_FRONT_AND_BACK, GL_FILL); glEnable(GL_DEPTH_TEST); glEnable(GL_CULL_FACE); } else if(drawMode == 1) // wireframe mode { glPolygonMode(GL_FRONT_AND_BACK, GL_LINE); glDisable(GL_DEPTH_TEST); glDisable(GL_CULL_FACE); } else// point mode { glPolygonMode(GL_FRONT_AND_BACK, GL_POINT); glDisable(GL_DEPTH_TEST); glDisable(GL_CULL_FACE); } break; default: ; } glutPostRedisplay();}void mouseCB(int button, int state, int x, int y){ mouseX = x; mouseY = y; if(button == GLUT_LEFT_BUTTON) { if(state == GLUT_DOWN) { mouseLeftDown = true; } else if(state == GLUT_UP) mouseLeftDown = false; } else if(button == GLUT_RIGHT_BUTTON) { if(state == GLUT_DOWN) { mouseRightDown = true; } else if(state == GLUT_UP) mouseRightDown = false; }}void mouseMotionCB(int x, int y){ if(mouseLeftDown) { cameraAngleY += (x - mouseX); cameraAngleX += (y - mouseY); mouseX = x; mouseY = y; } if(mouseRightDown) { cameraDistance += (y - mouseY) * 0.2f; mouseY = y; }}================================================================================================================================================================3. Third technique is using plain Windows Code (WinMain) - Read Time: 0.01ms ==========================================================================/* *This Code Was Created By Jeff Molofee 2000 *A HUGE Thanks To Fredric Echols For Cleaning Up *And Optimizing The Base Code, Making It More Flexible! *If You've Found This Code Useful, Please Let Me Know. *Visit My Site At nehe.gamedev.net */// in order to get function prototypes from glext.h, define GL_GLEXT_PROTOTYPES before including glext.h#define GL_GLEXT_PROTOTYPES#include <windows.h>// Header File For Windows#include <gl\gl.h>// Header File For The OpenGL32 Library#include <gl\glu.h>// Header File For The GLu32 Library#include "glut.h"//#include <gl\glaux.h>// Header File For The Glaux Library#include "oglext\glext.h"#include <iostream>#include <sstream>#include <iomanip>#include "glInfo.h" // glInfo struct#include "Timer.h"using std::stringstream;using std::cout;using std::endl;using std::ends;// VBO Extension Definitions, From glext.h#define GL_ARRAY_BUFFER_ARB 0x8892#define GL_STATIC_DRAW_ARB 0x88E4typedef void (APIENTRY * PFNGLBINDBUFFERARBPROC) (GLenum target, GLuint buffer);typedef void (APIENTRY * PFNGLDELETEBUFFERSARBPROC) (GLsizei n, const GLuint *buffers);typedef void (APIENTRY * PFNGLGENBUFFERSARBPROC) (GLsizei n, GLuint *buffers);typedef void (APIENTRY * PFNGLBUFFERDATAARBPROC) (GLenum target, int size, const GLvoid *data, GLenum usage);typedef void (APIENTRY * PFNGLBUFFERSUBDATAARBPROC) (GLenum, GLintptrARB, GLsizeiptrARB, GLvoid const *);typedef void (APIENTRY * PFNGLGETBUFFERPARAMETERIVARBPROC) (GLenum, GLenum, GLint *);typedef GLvoid* (APIENTRY * PFNGLMAPBUFFERARBPROC) (GLenum, GLenum);typedef GLboolean* (APIENTRY * PFNGLUNMAPBUFFERARBPROC) (GLenum);HDChDC=NULL;// Private GDI Device ContextHGLRChRC=NULL;// Permanent Rendering ContextHWNDhWnd=NULL;// Holds Our Window HandleHINSTANCEhInstance;// Holds The Instance Of The Applicationboolkeys[256];// Array Used For The Keyboard Routineboolactive=TRUE;// Window Active Flag Set To TRUE By Defaultboolfullscreen=TRUE;// Fullscreen Flag Set To Fullscreen Mode By DefaultGLfloatrtri;// Angle For The Triangle ( NEW )GLfloatrquad;// Angle For The Quad ( NEW )// function pointers for PBO Extension// Windows needs to get function pointers from ICD OpenGL drivers,// because opengl32.dll does not support extensions higher than v1.1.#ifdef _WIN32PFNGLGENBUFFERSARBPROC pglGenBuffersARB = 0; // VBO Name Generation ProcedurePFNGLBINDBUFFERARBPROC pglBindBufferARB = 0; // VBO Bind ProcedurePFNGLBUFFERDATAARBPROC pglBufferDataARB = 0; // VBO Data Loading ProcedurePFNGLBUFFERSUBDATAARBPROC pglBufferSubDataARB = 0;// VBO Sub Data Loading ProcedurePFNGLDELETEBUFFERSARBPROC pglDeleteBuffersARB = 0;// VBO Deletion ProcedurePFNGLGETBUFFERPARAMETERIVARBPROC pglGetBufferParameterivARB = 0; // return various parameters of VBOPFNGLMAPBUFFERARBPROC pglMapBufferARB = 0; // map VBO procedurePFNGLUNMAPBUFFERARBPROC pglUnmapBufferARB = 0; // unmap VBO procedure#define glGenBuffersARB pglGenBuffersARB#define glBindBufferARB pglBindBufferARB#define glBufferDataARB pglBufferDataARB#define glBufferSubDataARB pglBufferSubDataARB#define glDeleteBuffersARB pglDeleteBuffersARB#define glGetBufferParameterivARB pglGetBufferParameterivARB#define glMapBufferARB pglMapBufferARB#define glUnmapBufferARBpglUnmapBufferARB#endif// constantsconst int SCREEN_WIDTH = 256;const int SCREEN_HEIGHT = 256;const int CHANNEL_COUNT = 4;const int DATA_SIZE = SCREEN_WIDTH * SCREEN_HEIGHT * CHANNEL_COUNT;const GLenum PIXEL_FORMAT = GL_BGRA;const int PBO_COUNT = 2;// global variablesvoid *font = GLUT_BITMAP_8_BY_13;bool pboSupported;GLubyte* colorBuffer = 0;bool pboUsed;GLuint pboIds[PBO_COUNT]; // IDs of PBOsfloat cameraAngleX;float cameraAngleY;float cameraDistance;Timer timer, t1;float readTime, processTime;// GLUT CALLBACK functionsvoid displayCB();void reshapeCB(int w, int h);void timerCB(int millisec);void idleCB();void keyboardCB(unsigned char key, int x, int y);void mouseCB(int button, int stat, int x, int y);void mouseMotionCB(int x, int y);bool mouseLeftDown;bool mouseRightDown;float mouseX, mouseY;int drawMode = 0;LRESULTCALLBACK WndProc(HWND, UINT, WPARAM, LPARAM);// Declaration For WndProc///////////////////////////////////////////////////////////////////////////////// initialize global variables//////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// clean up shared memory///////////////////////////////////////////////////////////////////////////////void clearSharedMem(){ // deallocate frame buffer delete [] colorBuffer; colorBuffer = 0; // clean up PBOs if(pboSupported) { glDeleteBuffersARB(PBO_COUNT, pboIds); }}bool initSharedMem(){ mouseLeftDown = mouseRightDown = false; // allocate buffers to store frames colorBuffer = new GLubyte[DATA_SIZE]; memset(colorBuffer, 255, DATA_SIZE); return true;}///////////////////////////////////////////////////////////////////////////////// write 2d text using GLUT// The projection matrix must be set to orthogonal before call this function.///////////////////////////////////////////////////////////////////////////////void drawString(const char *str, int x, int y, float color[4], void *font){ glPushAttrib(GL_LIGHTING_BIT | GL_CURRENT_BIT); // lighting and color mask glDisable(GL_LIGHTING);// need to disable lighting for proper text color glDisable(GL_TEXTURE_2D); glColor4fv(color);// set text color glRasterPos2i(x, y); // place text position // loop all characters in the string while(*str) { glutBitmapCharacter(font, *str); ++str; } glEnable(GL_TEXTURE_2D); glEnable(GL_LIGHTING); glPopAttrib();}///////////////////////////////////////////////////////////////////////////////// display info messages///////////////////////////////////////////////////////////////////////////////void showInfo(){ // backup current model-view matrix glPushMatrix(); // save current modelview matrix glLoadIdentity(); // reset modelview matrix // set to 2D orthogonal projection glMatrixMode(GL_PROJECTION);// switch to projection matrix glPushMatrix(); // save current projection matrix glLoadIdentity(); // reset projection matrix gluOrtho2D(0, SCREEN_WIDTH, 0, SCREEN_HEIGHT); // set to orthogonal projection const int FONT_HEIGHT = 14; float color[4] = {1, 1, 1, 1}; stringstream ss; ss << "PBO: "; if(pboUsed) ss << "on" << ends; else ss << "off" << ends; drawString(ss.str().c_str(), 1, SCREEN_HEIGHT-FONT_HEIGHT, color, font); ss.str(""); // clear buffer ss << "Read Time: " << readTime << " ms" << ends; drawString(ss.str().c_str(), 1, SCREEN_HEIGHT-(2*FONT_HEIGHT), color, font); ss.str(""); ss << std::fixed << std::setprecision(3); ss << "Process Time: " << processTime << " ms" << ends; drawString(ss.str().c_str(), 1, SCREEN_HEIGHT-(3*FONT_HEIGHT), color, font); ss.str(""); ss << "Press SPACE to toggle PBO." << ends; drawString(ss.str().c_str(), 1, 1, color, font); // unset floating format ss << std::resetiosflags(std::ios_base::fixed | std::ios_base::floatfield); // restore projection matrix glPopMatrix(); // restore to previous projection matrix // restore modelview matrix glMatrixMode(GL_MODELVIEW); // switch to modelview matrix glPopMatrix(); // restore to previous modelview matrix}///////////////////////////////////////////////////////////////////////////////// display transfer rates///////////////////////////////////////////////////////////////////////////////void showTransferRate(){ static Timer timer; static int count = 0; static stringstream ss; double elapsedTime; // backup current model-view matrix glPushMatrix(); // save current modelview matrix glLoadIdentity(); // reset modelview matrix // set to 2D orthogonal projection glMatrixMode(GL_PROJECTION); // switch to projection matrix glPushMatrix(); // save current projection matrix glLoadIdentity(); // reset projection matrix gluOrtho2D(0, SCREEN_WIDTH, 0, SCREEN_HEIGHT); // set to orthogonal projection float color[4] = {1, 1, 0, 1}; // update fps every second elapsedTime = timer.getElapsedTime(); if(elapsedTime < 1.0) { ++count; } else { ss.str(""); ss << std::fixed << std::setprecision(1); ss << "Transfer Rate: " << (count / elapsedTime) * (SCREEN_WIDTH * SCREEN_HEIGHT) / (1024 * 1024) << " Mp" << ends; // update fps string ss << std::resetiosflags(std::ios_base::fixed | std::ios_base::floatfield); count = 0; // reset counter timer.start(); // restart timer } drawString(ss.str().c_str(), 200, 286, color, font); // restore projection matrix glPopMatrix(); // restore to previous projection matrix // restore modelview matrix glMatrixMode(GL_MODELVIEW); // switch to modelview matrix glPopMatrix(); // restore to previous modelview matrix}///////////////////////////////////////////////////////////////////////////////// print transfer rates///////////////////////////////////////////////////////////////////////////////void printTransferRate(){ const double INV_MEGA = 1.0 / (1024 * 1024); static Timer timer; static int count = 0; static stringstream ss; double elapsedTime; // loop until 1 sec passed elapsedTime = timer.getElapsedTime(); if(elapsedTime < 1.0) { ++count; } else { cout << std::fixed << std::setprecision(1); cout << "Transfer Rate: " << (count / elapsedTime) * (SCREEN_WIDTH * SCREEN_HEIGHT) * INV_MEGA << " Mpixels/s. (" << count / elapsedTime << " FPS)\n"; cout << std::resetiosflags(std::ios_base::fixed | std::ios_base::floatfield); count = 0; // reset counter timer.start(); // restart timer }}GLvoid ReSizeGLScene(GLsizei width, GLsizei height)// Resize And Initialize The GL Window{if (height==0)// Prevent A Divide By Zero By{height=1;// Making Height Equal One}glViewport(0,0,width,height);// Reset The Current ViewportglMatrixMode(GL_PROJECTION);// Select The Projection MatrixglLoadIdentity();// Reset The Projection Matrix// Calculate The Aspect Ratio Of The WindowgluPerspective(45.0f,(GLfloat)width/(GLfloat)height,0.1f,100.0f);glMatrixMode(GL_MODELVIEW);// Select The Modelview MatrixglLoadIdentity();// Reset The Modelview Matrix}int InitGL(GLvoid)// All Setup For OpenGL Goes Here{initSharedMem();// get OpenGL info glInfo glInfo; glInfo.getInfo(); glInfo.printSelf();#ifdef _WIN32 // check PBO is supported by your video card if(glInfo.isExtensionSupported("GL_ARB_pixel_buffer_object")) { // get pointers to GL functions glGenBuffersARB = (PFNGLGENBUFFERSARBPROC)wglGetProcAddress("glGenBuffersARB"); glBindBufferARB = (PFNGLBINDBUFFERARBPROC)wglGetProcAddress("glBindBufferARB"); glBufferDataARB = (PFNGLBUFFERDATAARBPROC)wglGetProcAddress("glBufferDataARB"); glBufferSubDataARB = (PFNGLBUFFERSUBDATAARBPROC)wglGetProcAddress("glBufferSubDataARB"); glDeleteBuffersARB = (PFNGLDELETEBUFFERSARBPROC)wglGetProcAddress("glDeleteBuffersARB"); glGetBufferParameterivARB = (PFNGLGETBUFFERPARAMETERIVARBPROC)wglGetProcAddress("glGetBufferParameterivARB"); glMapBufferARB = (PFNGLMAPBUFFERARBPROC)wglGetProcAddress("glMapBufferARB"); glUnmapBufferARB = (PFNGLUNMAPBUFFERARBPROC)wglGetProcAddress("glUnmapBufferARB"); // check once again PBO extension if(glGenBuffersARB && glBindBufferARB && glBufferDataARB && glBufferSubDataARB && glMapBufferARB && glUnmapBufferARB && glDeleteBuffersARB && glGetBufferParameterivARB) { pboSupported = pboUsed = true; //cout << "Video card supports GL_ARB_pixel_buffer_object." << endl; } else { pboSupported = pboUsed = false; // cout << "Video card does NOT support GL_ARB_pixel_buffer_object." << endl; } }#else // for linux, do not need to get function pointers, it is up-to-date if(glInfo.isExtensionSupported("GL_ARB_pixel_buffer_object")) { pboSupported = pboUsed = true; cout << "Video card supports GL_ARB_pixel_buffer_object." << endl; } else { pboSupported = pboUsed = false; cout << "Video card does NOT support GL_ARB_pixel_buffer_object." << endl; }#endifif(pboSupported) { // create 2 pixel buffer objects, you need to delete them when program exits. // glBufferDataARB with NULL pointer reserves only memory space. glGenBuffersARB(PBO_COUNT, pboIds); glBindBufferARB(GL_PIXEL_PACK_BUFFER_ARB, pboIds[0]); glBufferDataARB(GL_PIXEL_PACK_BUFFER_ARB, DATA_SIZE, 0, GL_STREAM_READ_ARB); glBindBufferARB(GL_PIXEL_PACK_BUFFER_ARB, pboIds[1]); glBufferDataARB(GL_PIXEL_PACK_BUFFER_ARB, DATA_SIZE, 0, GL_STREAM_READ_ARB); glBindBufferARB(GL_PIXEL_PACK_BUFFER_ARB, 0); }glShadeModel(GL_SMOOTH);// Enable Smooth ShadingglClearColor(0.0f, 0.0f, 0.0f, 0.5f);// Black BackgroundglClearDepth(1.0f);// Depth Buffer SetupglEnable(GL_DEPTH_TEST);// Enables Depth TestingglDepthFunc(GL_LEQUAL);// The Type Of Depth Testing To DoglHint(GL_PERSPECTIVE_CORRECTION_HINT, GL_NICEST);// Really Nice Perspective Calculationsreturn TRUE;// Initialization Went OK}///////////////////////////////////////////////////////////////////////////////// change the brightness///////////////////////////////////////////////////////////////////////////////void add(unsigned char* src, int width, int height, int shift, unsigned char* dst){ if(!src || !dst) return; int value; for(int i = 0; i < height; ++i) { for(int j = 0; j < width; ++j) { value = *src + shift; if(value > 255) *dst = (unsigned char)255; else *dst = (unsigned char)value; ++src; ++dst; value = *src + shift; if(value > 255) *dst = (unsigned char)255; else *dst = (unsigned char)value; ++src; ++dst; value = *src + shift; if(value > 255) *dst = (unsigned char)255; else *dst = (unsigned char)value; ++src; ++dst; ++src; // skip alpha ++dst; } }}///////////////////////////////////////////////////////////////////////////////// draw a cube with immediate mode// 54 calls = 24 glVertex*() calls + 24 glColor*() calls + 6 glNormal*() calls///////////////////////////////////////////////////////////////////////////////void draw(){ glBegin(GL_QUADS); // face v0-v1-v2-v3 glNormal3f(0,0,1); glColor3f(1,1,1); glVertex3f(1,1,1); glColor3f(1,1,0); glVertex3f(-1,1,1); glColor3f(1,0,0); glVertex3f(-1,-1,1); glColor3f(1,0,1); glVertex3f(1,-1,1); // face v0-v3-v4-v6 glNormal3f(1,0,0); glColor3f(1,1,1); glVertex3f(1,1,1); glColor3f(1,0,1); glVertex3f(1,-1,1); glColor3f(0,0,1); glVertex3f(1,-1,-1); glColor3f(0,1,1); glVertex3f(1,1,-1); // face v0-v5-v6-v1 glNormal3f(0,1,0); glColor3f(1,1,1); glVertex3f(1,1,1); glColor3f(0,1,1); glVertex3f(1,1,-1); glColor3f(0,1,0); glVertex3f(-1,1,-1); glColor3f(1,1,0); glVertex3f(-1,1,1); // face v1-v6-v7-v2 glNormal3f(-1,0,0); glColor3f(1,1,0); glVertex3f(-1,1,1); glColor3f(0,1,0); glVertex3f(-1,1,-1); glColor3f(0,0,0); glVertex3f(-1,-1,-1); glColor3f(1,0,0); glVertex3f(-1,-1,1); // face v7-v4-v3-v2 glNormal3f(0,-1,0); glColor3f(0,0,0); glVertex3f(-1,-1,-1); glColor3f(0,0,1); glVertex3f(1,-1,-1); glColor3f(1,0,1); glVertex3f(1,-1,1); glColor3f(1,0,0); glVertex3f(-1,-1,1); // face v4-v7-v6-v5 glNormal3f(0,0,-1); glColor3f(0,0,1); glVertex3f(1,-1,-1); glColor3f(0,0,0); glVertex3f(-1,-1,-1); glColor3f(0,1,0); glVertex3f(-1,1,-1); glColor3f(0,1,1); glVertex3f(1,1,-1); glEnd();}void toOrtho(){ // set viewport to be the entire window glViewport((GLsizei)SCREEN_WIDTH, 0, (GLsizei)SCREEN_WIDTH, (GLsizei)SCREEN_HEIGHT); // set orthographic viewing frustum glMatrixMode(GL_PROJECTION); glLoadIdentity(); glOrtho(0, SCREEN_WIDTH, 0, SCREEN_HEIGHT, -1, 1); // switch to modelview matrix in order to set scene glMatrixMode(GL_MODELVIEW); glLoadIdentity(); gluLookAt(0, 0, 0, 0, 0, -1, 0, 1, 0); // eye(x,y,z), focal(x,y,z), up(x,y,z)}void toPerspective(){ // set viewport to be the entire window glViewport(0, 0, (GLsizei)SCREEN_WIDTH, (GLsizei)SCREEN_HEIGHT); // set perspective viewing frustum glMatrixMode(GL_PROJECTION); glLoadIdentity(); gluPerspective(60.0f, (float)(SCREEN_WIDTH)/SCREEN_HEIGHT, 1.0f, 1000.0f); // FOV, AspectRatio, NearClip, FarClip // switch to modelview matrix in order to set scene glMatrixMode(GL_MODELVIEW); glLoadIdentity(); gluLookAt(0, 0, 8, 0, 0, 0, 0, 1, 0); // eye(x,y,z), focal(x,y,z), up(x,y,z)}int DrawLesson5Scene(GLvoid)// Here's Where We Do All The Drawing{//glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);// Clear Screen And Depth Buffer//glLoadIdentity();// Reset The Current Modelview MatrixglTranslatef(-1.5f,0.0f,-6.0f);// Move Left 1.5 Units And Into The Screen 6.0glRotatef(rtri,0.0f,1.0f,0.0f);// Rotate The Triangle On The Y axis ( NEW )glBegin(GL_TRIANGLES);// Start Drawing A TriangleglColor3f(1.0f,0.0f,0.0f);// RedglVertex3f( 0.0f, 1.0f, 0.0f);// Top Of Triangle (Front)glColor3f(0.0f,1.0f,0.0f);// GreenglVertex3f(-1.0f,-1.0f, 1.0f);// Left Of Triangle (Front)glColor3f(0.0f,0.0f,1.0f);// BlueglVertex3f( 1.0f,-1.0f, 1.0f);// Right Of Triangle (Front)glColor3f(1.0f,0.0f,0.0f);// RedglVertex3f( 0.0f, 1.0f, 0.0f);// Top Of Triangle (Right)glColor3f(0.0f,0.0f,1.0f);// BlueglVertex3f( 1.0f,-1.0f, 1.0f);// Left Of Triangle (Right)glColor3f(0.0f,1.0f,0.0f);// GreenglVertex3f( 1.0f,-1.0f, -1.0f);// Right Of Triangle (Right)glColor3f(1.0f,0.0f,0.0f);// RedglVertex3f( 0.0f, 1.0f, 0.0f);// Top Of Triangle (Back)glColor3f(0.0f,1.0f,0.0f);// GreenglVertex3f( 1.0f,-1.0f, -1.0f);// Left Of Triangle (Back)glColor3f(0.0f,0.0f,1.0f);// BlueglVertex3f(-1.0f,-1.0f, -1.0f);// Right Of Triangle (Back)glColor3f(1.0f,0.0f,0.0f);// RedglVertex3f( 0.0f, 1.0f, 0.0f);// Top Of Triangle (Left)glColor3f(0.0f,0.0f,1.0f);// BlueglVertex3f(-1.0f,-1.0f,-1.0f);// Left Of Triangle (Left)glColor3f(0.0f,1.0f,0.0f);// GreenglVertex3f(-1.0f,-1.0f, 1.0f);// Right Of Triangle (Left)glEnd();// Done Drawing The PyramidglLoadIdentity();// Reset The Current Modelview MatrixglTranslatef(1.5f,0.0f,-7.0f);// Move Right 1.5 Units And Into The Screen 7.0glRotatef(rquad,1.0f,1.0f,1.0f);// Rotate The Quad On The X axis ( NEW )glBegin(GL_QUADS);// Draw A QuadglColor3f(0.0f,1.0f,0.0f);// Set The Color To BlueglVertex3f( 1.0f, 1.0f,-1.0f);// Top Right Of The Quad (Top)glVertex3f(-1.0f, 1.0f,-1.0f);// Top Left Of The Quad (Top)glVertex3f(-1.0f, 1.0f, 1.0f);// Bottom Left Of The Quad (Top)glVertex3f( 1.0f, 1.0f, 1.0f);// Bottom Right Of The Quad (Top)glColor3f(1.0f,0.5f,0.0f);// Set The Color To OrangeglVertex3f( 1.0f,-1.0f, 1.0f);// Top Right Of The Quad (Bottom)glVertex3f(-1.0f,-1.0f, 1.0f);// Top Left Of The Quad (Bottom)glVertex3f(-1.0f,-1.0f,-1.0f);// Bottom Left Of The Quad (Bottom)glVertex3f( 1.0f,-1.0f,-1.0f);// Bottom Right Of The Quad (Bottom)glColor3f(1.0f,0.0f,0.0f);// Set The Color To RedglVertex3f( 1.0f, 1.0f, 1.0f);// Top Right Of The Quad (Front)glVertex3f(-1.0f, 1.0f, 1.0f);// Top Left Of The Quad (Front)glVertex3f(-1.0f,-1.0f, 1.0f);// Bottom Left Of The Quad (Front)glVertex3f( 1.0f,-1.0f, 1.0f);// Bottom Right Of The Quad (Front)glColor3f(1.0f,1.0f,0.0f);// Set The Color To YellowglVertex3f( 1.0f,-1.0f,-1.0f);// Top Right Of The Quad (Back)glVertex3f(-1.0f,-1.0f,-1.0f);// Top Left Of The Quad (Back)glVertex3f(-1.0f, 1.0f,-1.0f);// Bottom Left Of The Quad (Back)glVertex3f( 1.0f, 1.0f,-1.0f);// Bottom Right Of The Quad (Back)glColor3f(0.0f,0.0f,1.0f);// Set The Color To BlueglVertex3f(-1.0f, 1.0f, 1.0f);// Top Right Of The Quad (Left)glVertex3f(-1.0f, 1.0f,-1.0f);// Top Left Of The Quad (Left)glVertex3f(-1.0f,-1.0f,-1.0f);// Bottom Left Of The Quad (Left)glVertex3f(-1.0f,-1.0f, 1.0f);// Bottom Right Of The Quad (Left)glColor3f(1.0f,0.0f,1.0f);// Set The Color To VioletglVertex3f( 1.0f, 1.0f,-1.0f);// Top Right Of The Quad (Right)glVertex3f( 1.0f, 1.0f, 1.0f);// Top Left Of The Quad (Right)glVertex3f( 1.0f,-1.0f, 1.0f);// Bottom Left Of The Quad (Right)glVertex3f( 1.0f,-1.0f,-1.0f);// Bottom Right Of The Quad (Right)glEnd();// Done Drawing The Quadrtri+=0.2f;// Increase The Rotation Variable For The Triangle ( NEW )rquad-=0.15f;// Decrease The Rotation Variable For The Quad ( NEW )return TRUE;// Keep Going}int DrawGLScene(GLvoid)// Here's Where We Do All The Drawing{static int shift = 0; static int index = 0; int nextIndex = 0; // pbo index used for next frame // brightness shift amount shift = ++shift % 200; // increment current index first then get the next index // "index" is used to read pixels from a framebuffer to a PBO // "nextIndex" is used to process pixels in the other PBO index = (index + 1) % 2; nextIndex = (index + 1) % 2;// set the framebuffer to read glReadBuffer(GL_FRONT); if(pboUsed) // with PBO { // read framebuffer /////////////////////////////// timer.start(); // copy pixels from framebuffer to PBO // Use offset instead of ponter. // OpenGL should perform asynch DMA transfer, so glReadPixels() will return immediately. glBindBufferARB(GL_PIXEL_PACK_BUFFER_ARB, pboIds[index]); glReadPixels(0, 0, SCREEN_WIDTH, SCREEN_HEIGHT, PIXEL_FORMAT, GL_UNSIGNED_BYTE, 0);// measure the time reading framebuffer timer.stop(); readTime = timer.getElapsedTimeInMilliSec(); /////////////////////////////////////////////////// // process pixel data ///////////////////////////// // map the PBO that contain framebuffer pixels before processing it glBindBufferARB(GL_PIXEL_PACK_BUFFER_ARB, pboIds[nextIndex]); GLubyte* src = (GLubyte*)glMapBufferARB(GL_PIXEL_PACK_BUFFER_ARB, GL_READ_ONLY_ARB); if(src) { // change brightness add(src, SCREEN_WIDTH, SCREEN_HEIGHT, shift, colorBuffer); glUnmapBufferARB(GL_PIXEL_PACK_BUFFER_ARB);// release pointer to the mapped buffer } glBindBufferARB(GL_PIXEL_PACK_BUFFER_ARB, 0); } else // without PBO { // read framebuffer /////////////////////////////// timer.start(); // read framebuffer /////////////////////////////// glReadPixels(0, 0, SCREEN_WIDTH, SCREEN_HEIGHT, PIXEL_FORMAT, GL_UNSIGNED_BYTE, colorBuffer); // measure the time reading framebuffer timer.stop(); readTime = timer.getElapsedTimeInMilliSec(); /////////////////////////////////////////////////// // change brightness add(colorBuffer, SCREEN_WIDTH, SCREEN_HEIGHT, shift, colorBuffer); } // render to the framebuffer ////////////////////////// glDrawBuffer(GL_BACK); toPerspective(); // set to perspective on the left side of the window // clear buffer glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT | GL_STENCIL_BUFFER_BIT); ////// tramsform camera //glTranslatef(0, 0, cameraDistance); //glRotatef(cameraAngleX, 1, 0, 0); // pitch //glRotatef(cameraAngleY, 0, 1, 0); // heading //// draw a cube //draw();DrawLesson5Scene(); // draw the read color buffer to the right side of the window toOrtho(); // set to orthographic on the right side of the window glRasterPos2i(0, 0); glDrawPixels(SCREEN_WIDTH, SCREEN_HEIGHT, PIXEL_FORMAT, GL_UNSIGNED_BYTE, colorBuffer);// draw info messages showInfo(); printTransferRate();//glutSwapBuffers();return TRUE;// Keep Going}GLvoid KillGLWindow(GLvoid)// Properly Kill The Window{if (fullscreen)// Are We In Fullscreen Mode?{ChangeDisplaySettings(NULL,0);// If So Switch Back To The DesktopShowCursor(TRUE);// Show Mouse Pointer}if (hRC)// Do We Have A Rendering Context?{if (!wglMakeCurrent(NULL,NULL))// Are We Able To Release The DC And RC Contexts?{MessageBox(NULL,"Release Of DC And RC Failed.","SHUTDOWN ERROR",MB_OK | MB_ICONINFORMATION);}if (!wglDeleteContext(hRC))// Are We Able To Delete The RC?{MessageBox(NULL,"Release Rendering Context Failed.","SHUTDOWN ERROR",MB_OK | MB_ICONINFORMATION);}hRC=NULL;// Set RC To NULL}if (hDC && !ReleaseDC(hWnd,hDC))// Are We Able To Release The DC{MessageBox(NULL,"Release Device Context Failed.","SHUTDOWN ERROR",MB_OK | MB_ICONINFORMATION);hDC=NULL;// Set DC To NULL}if (hWnd && !DestroyWindow(hWnd))// Are We Able To Destroy The Window?{MessageBox(NULL,"Could Not Release hWnd.","SHUTDOWN ERROR",MB_OK | MB_ICONINFORMATION);hWnd=NULL;// Set hWnd To NULL}if (!UnregisterClass("OpenGL",hInstance))// Are We Able To Unregister Class{MessageBox(NULL,"Could Not Unregister Class.","SHUTDOWN ERROR",MB_OK | MB_ICONINFORMATION);hInstance=NULL;// Set hInstance To NULL}}/*This Code Creates Our OpenGL Window. Parameters Are:* *title- Title To Appear At The Top Of The Window* *width- Width Of The GL Window Or Fullscreen Mode* *height- Height Of The GL Window Or Fullscreen Mode* *bits- Number Of Bits To Use For Color (8/16/24/32)* *fullscreenflag- Use Fullscreen Mode (TRUE) Or Windowed Mode (FALSE)*/ BOOL CreateGLWindow(char* title, int width, int height, int bits, bool fullscreenflag){GLuintPixelFormat;// Holds The Results After Searching For A MatchWNDCLASSwc;// Windows Class StructureDWORDdwExstyle;// Window Extended styleDWORDdwstyle;// Window styleRECTWindowRect;// Grabs Rectangle Upper Left / Lower Right ValuesWindowRect.left=(long)0;// Set Left Value To 0WindowRect.right=(long)width;// Set Right Value To Requested WidthWindowRect.top=(long)0;// Set Top Value To 0WindowRect.bottom=(long)height;// Set Bottom Value To Requested Heightfullscreen=fullscreenflag;// Set The Global Fullscreen FlaghInstance= GetModuleHandle(NULL);// Grab An Instance For Our Windowwc.style= CS_HREDRAW | CS_VREDRAW | CS_OWNDC;// Redraw On Size, And Own DC For Window.wc.lpfnWndProc= (WNDPROC) WndProc;// WndProc Handles Messageswc.cbClsExtra= 0;// No Extra Window Datawc.cbWndExtra= 0;// No Extra Window Datawc.hInstance= hInstance;// Set The Instancewc.hIcon= LoadIcon(NULL, IDI_WINLOGO);// Load The Default Iconwc.hCursor= LoadCursor(NULL, IDC_ARROW);// Load The Arrow Pointerwc.hbrBackground= NULL;// No Background Required For GLwc.lpszMenuName= NULL;// We Don't Want A Menuwc.lpszClassName= "OpenGL";// Set The Class Nameif (!RegisterClass(&wc))// Attempt To Register The Window Class{MessageBox(NULL,"Failed To Register The Window Class.","ERROR",MB_OK|MB_ICONEXCLAMATION);return FALSE;// Return FALSE} if (fullscreen)// Attempt Fullscreen Mode?{DEVMODE dmScreenSettings;// Device Modememset(&dmScreenSettings,0,sizeof(dmScreenSettings));// Makes Sure Memory's CleareddmScreenSettings.dmSize=sizeof(dmScreenSettings);// Size Of The Devmode StructuredmScreenSettings.dmPelsWidth= width;// Selected Screen WidthdmScreenSettings.dmPelsHeight= height;// Selected Screen HeightdmScreenSettings.dmBitsPerPel= bits;// Selected Bits Per PixeldmScreenSettings.dmFields=DM_BITSPERPEL|DM_PELSWIDTH|DM_PELSHEIGHT;// Try To Set Selected Mode And Get Results. NOTE: CDS_FULLSCREEN Gets Rid Of Start Bar.if (ChangeDisplaySettings(&dmScreenSettings,CDS_FULLSCREEN)!=DISP_CHANGE_SUCCESSFUL){// If The Mode Fails, Offer Two Options. Quit Or Use Windowed Mode.if (MessageBox(NULL,"The Requested Fullscreen Mode Is Not Supported By\nYour Video Card. Use Windowed Mode Instead?","NeHe GL",MB_YESNO|MB_ICONEXCLAMATION)==IDYES){fullscreen=FALSE;// Windowed Mode Selected. Fullscreen = FALSE}else{// Pop Up A Message Box Letting User Know The Program Is Closing.MessageBox(NULL,"Program Will Now Close.","ERROR",MB_OK|MB_ICONSTOP);return FALSE;// Return FALSE}}}if (fullscreen)// Are We Still In Fullscreen Mode?{dwExstyle=WS_EX_APPWINDOW;// Window Extended styledwstyle=WS_POPUP;// Windows styleShowCursor(FALSE);// Hide Mouse Pointer}else{dwExstyle=WS_EX_APPWINDOW | WS_EX_WINDOWEDGE;// Window Extended styledwstyle=WS_OVERLAPPEDWINDOW;// Windows style}AdjustWindowRectEx(&WindowRect, dwstyle, FALSE, dwExstyle);// Adjust Window To True Requested Size// Create The Windowif (!(hWnd=CreateWindowEx(dwExstyle,// Extended style For The Window"OpenGL",// Class Nametitle,// Window Titledwstyle |// Defined Window styleWS_CLIPSIBLINGS |// Required Window styleWS_CLIPCHILDREN,// Required Window style0, 0,// Window PositionWindowRect.right-WindowRect.left,// Calculate Window WidthWindowRect.bottom-WindowRect.top,// Calculate Window HeightNULL,// No Parent WindowNULL,// No MenuhInstance,// InstanceNULL)))// Dont Pass Anything To WM_CREATE{KillGLWindow();// Reset The DisplayMessageBox(NULL,"Window Creation Error.","ERROR",MB_OK|MB_ICONEXCLAMATION);return FALSE;// Return FALSE}staticPIXELFORMATDESCRIPTOR pfd=// pfd Tells Windows How We Want Things To Be{sizeof(PIXELFORMATDESCRIPTOR),// Size Of This Pixel Format Descriptor1,// Version NumberPFD_DRAW_TO_WINDOW |// Format Must Support WindowPFD_SUPPORT_OPENGL |// Format Must Support OpenGLPFD_DOUBLEBUFFER,// Must Support Double BufferingPFD_TYPE_RGBA,// Request An RGBA Formatbits,// Select Our Color Depth8, 0, 8, 0, 8, 0,// Color Bits Ignored8,// No Alpha Buffer0,// Shift Bit Ignored0,// No Accumulation Buffer0, 0, 0, 0,// Accumulation Bits Ignored16,// 16Bit Z-Buffer (Depth Buffer) 0,// No Stencil Buffer0,// No Auxiliary BufferPFD_MAIN_PLANE,// Main Drawing Layer0,// Reserved0, 0, 0// Layer Masks Ignored//sizeof(PIXELFORMATDESCRIPTOR),// Size Of This Pixel Format Descriptor//1,// Version Number//PFD_DRAW_TO_WINDOW |// Format Must Support Window//PFD_SUPPORT_OPENGL |// Format Must Support OpenGL//PFD_DOUBLEBUFFER,// Must Support Double Buffering//PFD_TYPE_RGBA,// Request An RGBA Format//bits,// Select Our Color Depth//0, 0, 0, 0, 0, 0,// Color Bits Ignored//0,// No Alpha Buffer//0,// Shift Bit Ignored//0,// No Accumulation Buffer//0, 0, 0, 0,// Accumulation Bits Ignored//16,// 16Bit Z-Buffer (Depth Buffer) //0,// No Stencil Buffer//0,// No Auxiliary Buffer//PFD_MAIN_PLANE,// Main Drawing Layer//0,// Reserved//0, 0, 0}; if (!(hDC=GetDC(hWnd)))// Did We Get A Device Context?{KillGLWindow();// Reset The DisplayMessageBox(NULL,"Can't Create A GL Device Context.","ERROR",MB_OK|MB_ICONEXCLAMATION);return FALSE;// Return FALSE}if (!(PixelFormat=ChoosePixelFormat(hDC,&pfd)))// Did Windows Find A Matching Pixel Format?{KillGLWindow();// Reset The DisplayMessageBox(NULL,"Can't Find A Suitable PixelFormat.","ERROR",MB_OK|MB_ICONEXCLAMATION);return FALSE;// Return FALSE}if(!SetPixelFormat(hDC,PixelFormat,&pfd))// Are We Able To Set The Pixel Format?{KillGLWindow();// Reset The DisplayMessageBox(NULL,"Can't Set The PixelFormat.","ERROR",MB_OK|MB_ICONEXCLAMATION);return FALSE;// Return FALSE}if (!(hRC=wglCreateContext(hDC)))// Are We Able To Get A Rendering Context?{KillGLWindow();// Reset The DisplayMessageBox(NULL,"Can't Create A GL Rendering Context.","ERROR",MB_OK|MB_ICONEXCLAMATION);return FALSE;// Return FALSE}if(!wglMakeCurrent(hDC,hRC))// Try To Activate The Rendering Context{KillGLWindow();// Reset The DisplayMessageBox(NULL,"Can't Activate The GL Rendering Context.","ERROR",MB_OK|MB_ICONEXCLAMATION);return FALSE;// Return FALSE}ShowWindow(hWnd,SW_SHOW);// Show The WindowSetForegroundWindow(hWnd);// Slightly Higher PrioritySetFocus(hWnd);// Sets Keyboard Focus To The WindowReSizeGLScene(width, height);// Set Up Our Perspective GL Screenif (!InitGL())// Initialize Our Newly Created GL Window{KillGLWindow();// Reset The DisplayMessageBox(NULL,"Initialization Failed.","ERROR",MB_OK|MB_ICONEXCLAMATION);return FALSE;// Return FALSE}return TRUE;// Success}LRESULT CALLBACK WndProc(HWNDhWnd,// Handle For This WindowUINTuMsg,// Message For This WindowWPARAMwParam,// Additional Message InformationLPARAMlParam)// Additional Message Information{switch (uMsg)// Check For Windows Messages{case WM_ACTIVATE:// Watch For Window Activate Message{if (!HIWORD(wParam))// Check Minimization State{active=TRUE;// Program Is Active}else{active=FALSE;// Program Is No Longer Active}return 0;// Return To The Message Loop}case WM_SYSCOMMAND:// Intercept System Commands{switch (wParam)// Check System Calls{case SC_SCREENSAVE:// Screensaver Trying To Start?case SC_MONITORPOWER:// Monitor Trying To Enter Powersave?return 0;// Prevent From Happening}break;// Exit}case WM_CLOSE:// Did We Receive A Close Message?{PostQuitMessage(0);// Send A Quit Messagereturn 0;// Jump Back}case WM_KEYDOWN:// Is A Key Being Held Down?{keys[wParam] = TRUE;// If So, Mark It As TRUEreturn 0;// Jump Back}case WM_KEYUP:// Has A Key Been Released?{keys[wParam] = FALSE;// If So, Mark It As FALSEreturn 0;// Jump Back}case WM_SIZE:// Resize The OpenGL Window{ReSizeGLScene(LOWORD(lParam),HIWORD(lParam)); // LoWord=Width, HiWord=Heightreturn 0;// Jump Back}}// Pass All Unhandled Messages To DefWindowProcreturn DefWindowProc(hWnd,uMsg,wParam,lParam);}///////////////////////////////////////////////////////////////////////////////// initialize GLUT for windowing///////////////////////////////////////////////////////////////////////////////int initGLUT(int argc, char **argv){ // GLUT stuff for windowing // initialization openGL window. // it is called before any other GLUT routine glutInit(&argc, argv); glutInitDisplayMode(GLUT_RGB | GLUT_DOUBLE | GLUT_ALPHA); // display mode glutInitWindowSize(SCREEN_WIDTH*2, SCREEN_HEIGHT); // window size glutInitWindowPosition(100, 100); // window location // finally, create a window with openGL context // Window will not displayed until glutMainLoop() is called // it returns a unique ID int handle = glutCreateWindow(argv[0]);// param is the title of window // register GLUT callback functions //glutDisplayFunc(DrawGLScene); //glutTimerFunc(33, timerCB, 33); // redraw only every given millisec glutIdleFunc(idleCB); // redraw only every given millisec //glutReshapeFunc(reshapeCB); //glutKeyboardFunc(keyboardCB); //glutMouseFunc(mouseCB); //glutMotionFunc(mouseMotionCB); return handle;}int WINAPI WinMain(HINSTANCEhInstance,// InstanceHINSTANCEhPrevInstance,// Previous InstanceLPSTRlpCmdLine,// Command Line ParametersintnCmdShow)// Window Show State/////////////////////////////////////////////////////////////////////////////////int main(int argc, char **argv){// init GLUT and GL //initGLUT(argc, argv); //initGL();InitGL(); //// the last GLUT call (LOOP) // // window will be shown and display callback is triggered by events // // NOTE: this call never return main(). // glutMainLoop(); /* Start GLUT event-processing loop */ MSGmsg;// Windows Message StructureBOOLdone=FALSE;// Bool Variable To Exit Loop// Ask The User Which Screen Mode They Preferif (MessageBox(NULL,"Would You Like To Run In Fullscreen Mode?", "Start FullScreen?",MB_YESNO|MB_ICONQUESTION)==IDNO){fullscreen=FALSE;// Windowed Mode} // Create Our OpenGL Windowif (!CreateGLWindow("NeHe's Solid Object Tutorial",512,256,32,fullscreen)){return 0;// Quit If Window Was Not Created}while(!done)// Loop That Runs While done=FALSE{if (PeekMessage(&msg,NULL,0,0,PM_REMOVE))// Is There A Message Waiting?{if (msg.message==WM_QUIT)// Have We Received A Quit Message?{done=TRUE;// If So done=TRUE}else// If Not, Deal With Window Messages{TranslateMessage(&msg;// Translate The MessageDispatchMessage(&msg;// Dispatch The Message}}else// If There Are No Messages{// Draw The Scene. Watch For ESC Key And Quit Messages From DrawGLScene()if ((active && !DrawGLScene()) || keys[VK_ESCAPE])// Active? Was There A Quit Received?{done=TRUE;// ESC or DrawGLScene Signalled A Quit}else// Not Time To Quit, Update Screen{SwapBuffers(hDC);// Swap Buffers (Double Buffering)}if (keys[VK_F1])// Is F1 Being Pressed?{keys[VK_F1]=FALSE;// If So Make Key FALSEKillGLWindow();// Kill Our Current Windowfullscreen=!fullscreen;// Toggle Fullscreen / Windowed Mode// Recreate Our OpenGL Windowif (!CreateGLWindow("NeHe's Solid Object Tutorial",512,256,32,fullscreen)){return 0;// Quit If Window Was Not Created}}}}// ShutdownKillGLWindow();// Kill The Windowreturn (msg.wParam);// Exit The Program//return 0;}void reshapeCB(int w, int h){ toPerspective();}void timerCB(int millisec){ glutTimerFunc(millisec, timerCB, millisec); glutPostRedisplay();}void idleCB(){ glutPostRedisplay();}void keyboardCB(unsigned char key, int x, int y){ switch(key) { case 27: // ESCAPE clearSharedMem(); //exit(0); break; case ' ': if(pboSupported) pboUsed = !pboUsed; cout << "PBO mode: " << (pboUsed ? "on" : "off") << endl; break; case 'd': // switch rendering modes (fill -> wire -> point) case 'D': drawMode = ++drawMode % 3; if(drawMode == 0) // fill mode { glPolygonMode(GL_FRONT_AND_BACK, GL_FILL); glEnable(GL_DEPTH_TEST); glEnable(GL_CULL_FACE); } else if(drawMode == 1) // wireframe mode { glPolygonMode(GL_FRONT_AND_BACK, GL_LINE); glDisable(GL_DEPTH_TEST); glDisable(GL_CULL_FACE); } else// point mode { glPolygonMode(GL_FRONT_AND_BACK, GL_POINT); glDisable(GL_DEPTH_TEST); glDisable(GL_CULL_FACE); } break; default: ; } glutPostRedisplay();}void mouseCB(int button, int state, int x, int y){ mouseX = x; mouseY = y; if(button == GLUT_LEFT_BUTTON) { if(state == GLUT_DOWN) { mouseLeftDown = true; } else if(state == GLUT_UP) mouseLeftDown = false; } else if(button == GLUT_RIGHT_BUTTON) { if(state == GLUT_DOWN) { mouseRightDown = true; } else if(state == GLUT_UP) mouseRightDown = false; }}void mouseMotionCB(int x, int y){ if(mouseLeftDown) { cameraAngleY += (x - mouseX); cameraAngleX += (y - mouseY); mouseX = x; mouseY = y; } if(mouseRightDown) { cameraDistance += (y - mouseY) * 0.2f; mouseY = y; }}===============================================================================The primary difference between all these three technique is the way the windows of the application are created.I want to achieve the same speed performance on SDL application. Any help in this regard will be highly appreciated. Eagerly waiting for your early response. | That's A LOT of code for even the most insane person to go through...What was wrong with the code again? ; First of all thanks for your reply. I just want to know that what values do I need to initialize in SDL before creating a SDL window in order to get PBO to work. Currently I am using the following lines of code to bring SDL window. But when I use PBO it does not have any performance benefits as was with when I create window using GLUT or plain Windows programming using WinMain./*--------------------------------------------------* Setup SDL*--------------------------------------------------*/bool init_SDL(){//Init all SDL Partsif(SDL_Init(SDL_INIT_EVERYTHING) == -1){return false;}//screen = SDL_SetVideoMode( SCREEN_WIDTH, SCREEN_HEIGHT, SCREEN_BPP, SDL_OPENGL | SDL_DOUBLEBUF | SDL_FULLSCREEN ); //FULLSCREENscreen = SDL_SetVideoMode( SCREEN_WIDTH*2, SCREEN_HEIGHT, SCREEN_BPP, SDL_OPENGL | SDL_DOUBLEBUF);SDL_WM_SetCaption("Simple SDL Demo", NULL);return true;}Is there any way to change the pixelformatdescriptor of SDL? or some other better way to get results. Eagerly waiting for your reply. Thanks. ; I am unsure about the specifics of PBO, but it *might* help if you add SDL_HWSURFACE | SDL_OPENGL. As far as I know the SDL_HWSURFACE would direct SDL to use hardware acceleration on the screen.Why aren't you happy with GLUT alone then? IMO if it works for your purpose then stick with it. I personally cannot see any advantages of using SDL over GLUT except for maybe cross-platforming (Which GLUT already does).Hope that helps. =) ; Flags like SDL_DOUBLEBUF and SDL_HWSURFACE have no effect on an OpenGL rendering context. Also, you don't define the bit depth in SDL_SetVideoMode for OpenGL, just pass 0. The only flag you need is SDL_OPENGL and optionally SDL_FULLSCREEN if you want fullscreen. You configure other things like bit depth, double buffering, etc with SDL_GL_SetAttribute (which you must call before SDL_SetVideoMode). To create an OpenGL rendering context with SDL, the correct order of calls is:SDL_Init(SDL_INIT_VIDEO);//setup OpenGL parametersSDL_GL_SetAttribute(SDL_GL_DOUBLEBUFFER, 1);SDL_GL_SetAttribute( SDL_GL_RED_SIZE, 8 );SDL_GL_SetAttribute( SDL_GL_GREEN_SIZE, 8 );SDL_GL_SetAttribute( SDL_GL_BLUE_SIZE, 8 );SDL_GL_SetAttribute( SDL_GL_ALPHA_SIZE, 8 );SDL_GL_SetAttribute( SDL_GL_DEPTH_SIZE, 0 );//and so on, set other attributes hereSDL_SetVideoMode(SCREEN_WIDTH, SCREEN_HEIGHT, 0, SDL_OPENGL);You can read more here.Once you have a valid OpenGL rendering context, then you can use OpenGL features such as PBO. Since you never actually define your rendering context correctly, my guess is the speed difference is due to OpenGL having to convert from whatever the default format is to match the format of the PBO. Thus the performance hit. Use SDL_GL_SetAttribute properly to make your framebuffer format match your PBO format and I bet you will see a big improvement in performance. ; First of all thanks for your kind reply. I have tried what you said and it resolves my issue, the glReadPixels now takes only 0-1 ms. But unfortunately by setting the rendering context, the frame rate of the rest of the scene suddenly drops by a factor of 5 like previously it was 42 and now it is showing maximum frame rate of 34. So what should I do next to resolve it. Are there any other setting besides the parameters that you have shown. Eagerly waiting for your early response. Thanks. ; I'm glad that you resolved your initial issue. As for the drop in frame rate, I will admit that I have not reviewed your code in depth, so I can not make a direct recommendation. On one hand, I probably would not worry about a drop of 5 frames per second. On the other hand, your code does not appear to be doing anything terribly complex, so it is strange to see a drop. Did you benchmark your updated code with the GLUT version? What type of GPU are you running this on? ; Thanks for your reply. In fact the code that I have posted earlier is only a sample code that I have used for illustration of my previous issue. I am in fact running a game that includes sea environment, terrain and some harbors area. And by defining the openGL rendering context parameters for SDL it drops to 34 FPS maximum and this causes the scene to jerk at some time due to sea rendering. But if I run the code without defining the openGL context parameters for SDL it gives FPS of 40 maximum. The GPU that I have is nVidia 8500 GT. But I think that it does not have any effect on it because I have also run this code in my office where it is showing the similar behavior where I have nVidia 8800 GTS. Waiting for your reply. Thanks. |
Steering behaviour libraries? | Artificial Intelligence;Programming | Hello all. I've been reading a lot about steering behaviours recently (y'know Craig Reynolds, Boids flocking, all that), which sound very useful. I was overjoyed when I saw OpenSteer - a steering behaviour library written by Reynolds himself. However, the last stable release was in 2004 and there are a lot of common steering behaviours missing.I tried to search the web for alternatives or extensions to OpenSteer, but couldn't find anything. So, my question is, can anyone recommend a good steering behaviour library? | As far as I know, everybody implements this themselves... ; I used to be of the mind to implement everything myself. But these days I find it is worth tracking down suitable libraries to save the hassle of putting together a good implementation. Even once one understands everything, it's still a long way from well-written stable code. Not to mention the time pressures of work deadlines - writing everything yourself runs the risk of encountering "that bug", which grinds progress to a halt for days or weeks at a time.I still can't find any suitable libraries for steering behaviours, however, so it looks like I am indeed stuck with coding everything myself. Luckily I got a couple of good books, so maybe progress will be swift. ; Oh, I agree on principal. I just don't know of any steering libraries beyond Reynold's original work. :) ; I've heard there's some Steering behavior implementation in recast & detourCheersDark Sylinc ; Suppose I have a map format .Obj, how OpenSteer like finding ways to make the map? |
Bad Performance on Great GPU | Graphics and GPU Programming;Programming | Hi!My DirectX application draws lots of particles. It needs a lot of fillrate and it's GPU bound on most systems. Antialiasing is disabled.On a HD3650 mobile graphics card, it runs very well.But some users have much better GPUs (GTX 260 or GTX 470) and report bad performance.Do you have any idea what could cause this? How can I investigate the problem when I don't have a test machine with a GTX260 available?Thanks!Lukas | - Try running the shader through nvidia's shader profiling tool.- It might be worth getting those people to try it with older / newer driver versions.- Can you get at any nvidia card to test it with?- Have you tried running it with the debug runtimes enabled on an nvidia card? They will pick up different issues on different hardware as the caps vary.- Check the actual frame rate on these 'slow' cards with say FRAPS. |
How do Shaders work? | Graphics and GPU Programming;Programming | Hi all, I'm pretty new to graphics programming and currently trying to build an engine of a sorts in DirectX 10.I pretty much had to work off of Frank Luna's tutorials that he has in his book, Introduction to 3D Game Programming with DirectX 10, to get to where I am now. Currently, I have a working Model class that, using ASSIMP, loads any model I want and applies diffuse and spec textures on it as well.I currently have 3 FX files, model.fx (which is a modified .fx file that Luna made), light.fx, and lighthelper.fx (both of which are the exact same as Luna's). My model loader uses model.fx to render the model and apply textures onto it.I also made a Lighting class, which uses light.fx and lighthelper.fx... but lo and behold, upon runtime, the lights aren't doing anything, even though I've done everything correctly in the class itself.The way Luna did his tutorials was that he had his Main class apply all the shaders while his other classes just set up the variables. I did not like this and attempted to move the shaders into their respective classes. This has worked for my model class but it doesn't seem to work for my lighting class. My friend, who admits he doesn't know shaders all too well, says its because even though my lighting class is probably doing everything correctly, it doesn't see my model shader and can't apply anything to it.So, I ask again, how do shaders work? Do I really need to have the shader work done in one main class? Or can I have my shaders work in their classes where they're needed? I honestly don't know shaders very well at all (other than how to implement them within the code) and would appreciate if I also got an article or tutorial on how to write shaders properly and the possibilities I have with them.But right now I want a direct answer on whether or not I can do what I want and have each class handle the shaders on their own. | You have to activate the shader, then when you render your triangles, the shader is working on those triangles. Then, you switch to a different shader and keep repeating the process. ; Like I tell everyone one new to graphics programming, before you start delving into a particular API, take the time out to understand the fundamentals behind graphics programming. It will save you a lot of time and effort in the long run. "How does shader work?" If you understood how the graphics pipeline work (a fundamental concept in graphics program) then it would be easier to visualize how shader work. Simply copying, pasting and modify shaders won't really help if you don't understand 1. How shader works 2. The effect that the shader is trying to acheive. As someone who is just getting started in graphics programming I would avoid going directly to API specific books. Instead pick up a book like Computer Graphics : Practice & Principles, or something thats platform agnostic. DirectX is complex on its own and not understanding how stuff work on a fundamental basis will only serve to complicate the matter. |
Chain Reaction: Escape [UDK] - needed 3d/2d artists, flash programmers | Old Archive;Archive | Quote:You know how it feels when out of the blue you find yourself in the middle of a blizzard, the wind with persistence worthy of a better cause, tries to throw you out of the rickety ****, that only with a high degree of optimism could be called a scooter, and you, with all of your strength try to keep the saddle and tear vis a vis the storm, despite the fact that you do not expect to find anything specific at the end of your detour? No? Thought so. My name is Jack. In our Vault we no longer use any family names, since the pool of genes run out. You know, ninety years underground, sealed society, and someone eventually nails his own cousin. We spent more than two hundred. Together with incest there came general reluctance to use the surnames - a psychological trick for us to hate ourselves less. Well, the man will do anything not to feel a monster.Each of us, nevertheless, had a nickname. Most connected with the jobs we performed, but sometimes because of some other qualities. We had Arek the Carpenter, Susan the Midwife, Frank the Bignose. However, as we also had Paul the Thief, Adam the Murderer ... and Jack the Psycho as well. Pleasure to meet you. According to the Vault's Chief, pathogenic behaviors were caused by containment of our group, and genetic defects. With enthusiasm he preached that we needed new blood, that we needed a breath of fresh air. I hope that someday he'll see the surface and breathe the freezing cold air, trying to make one big hell of an icicle out of your lungs. For me, I had more new fresh air than I ever wanted. And so much of the cold freshnes that it will suffice till the end of my life. In a nutshell, living space was shrinking, someone had to check whether it's possible to live outside or not. To reduce depletion of the pool of healthy genes, and root out the evil at the same time, filling our prisonlike shelter, a small group of nutso's and criminals were sent to the surface - me included. After three months of vitamin treatment accompanied by irradiation under UV lamps, armed to teeth, equipped with hightech gadgets, we were escorted to, and kicked through the farthest Vault's hatch, which closed behind our backs. Our task was simple - find a new place to live or die trying. I, personally did not go too far. Despite all the preparations, I still could not get used to this horrible, gross and furiously burning sun, and therefore I gave it a finger and turned my back on it. I travelled in the opposite direction. I haven't even reached the twenty kilometers count on the meter, when I found myself amidst the white hell's performance, and after five more the wind finally made it's point - it threw me out of the scooter and blown me into a snowdrift like a child's toy. If this wasn't enough, my ****ing luck caused me to find the only snowdrift within a radius of thirty kilometers, under which the metal door to a Vault lay hidden. Suit lessened the blow a bit which, however, was strong enough to sound the brass bells and all the angelic choires in my head. Bemused and disoriented, but still sober enough to think, I started looking for shelter from the fury of a blizzard. Luckily, the door to the Vault were not locked from the inside - short wrestling match with that hatch, and I was inside. The interior was not very friendly, actually - I don't remember much of that day - the only certain thing I remember is the neon reading: 'Medical Bay'. Shaking I hobbled there and dozed off on a ruggy bed. According to the gold watch of my grandfather, I was unconscious for more than twenty hours. Sirens started screaming everywhere, which woke me up, and the annoying flashing red light pierced continously through my eyes. The megaphones from the ceiling communicated with a cool as earths surface womans voice: Welcome to the Kraków's atomic Vault number thirteen. You have been qualified as an intruder. The full lock-up procedure has been commenced. Air reserves will suffice for up to twenty hours. Reserves of clean water have been exhausted. If you are a lawful resident of the Vault, enter the access code in the central computer. Have a nice day. If I wasn't a bit saddened by the fact of my imminent suffocation, I would lose my cell of the battery because of the bloody communicate repeated every ten minutes. My holophone was dead - with shatterd screen it wasn't as lucky as me when we gatecrashed our way to the party here - I was alone. ****, ****ing ****headed ****. Twenty hours till I breath carbon dioxide. I had to get out of here...Chain Reaction: Escape is a project of an old-school adventurer game (or should I stay, puzzle game, as there will be no mobs to shoot ;P), set in a post-apocalyptic world. If I recall correctly, it will be the first game of that kind since Beneath a Steel Sky (which wasn't 100% post-apo, and was released a long, long time ago). It will take place in one of atomic shelters, left in Eastern Europe.Basically, what we are looking for as a team, are artists. Right now our team consists of two part-time 3d modelers, and me - a designer, programmer and leader. We have open spots for:3d Modelers (static items, no organics)2d artists (textures,concept arts)Flash Programmers/DesignersLevel Artists (design, LIGHTING)Here are few shots to keep you interested, and a fly-thru video at the end of the post. It's not much - but we basically have no concept arts, as we have no concept artists :P Here you go:Stationary computerMedical BayLibraryGenerator roomFly-through first level">YouTube - Chain Reaction: Escape fly-throughChain Reaction: Escape PC game - Indie DBMContact me via mail: [email protected] , PM, or IndieDB. | Bump. ; Is this a paid opportunity?I am a 3D modeler loking for paid work.My portfolio - www.karanshah.110mb.com/3d.htm; I am just curious about what kind of role the flash programmer will have in the project.I'm a professional flashdeveloper and would like some more info about this.best regardsAndreas ; Unfortunately it's not a paid project, we're independent developer team with no funding atm, and we're not sure whether we will get any in nearest future.As to what would be the main job for a Flash Developer - we need someone to develop for us GUI and game-logic elements (interactive computer screens, terminals, so on), using Scaleform. ; Bump ; Bumpity bumpity bump. |
Does my loop need to be synchronized and also a question about double buffering | For Beginners | Hello. I made a snake game the other day in Java, and although i've made anagram games and memory games, i would describe this as my first proper game. The first with a game loop anyway.I use a javax.swing.Timer to call the loop method over and over at intervals the user chooses (as they decide the speed of the snake). I have only just learned about threads and i was wondering should I make my loop() method sychronized? If I don't is there a danger that the Timer could fire another ActionEvent before the last loop has finished running? (which would cause problems) At the moment it's synchronized but i'm not sure if that is just pointless. The other question is about should I use a double buffer. I have only just started learning about double buffering and am yet to do it in a program. And i understand it draws onto an object and not until it has finished does it draw the whole thing at once to the screen to prevent flickering.But with my code as it only calls repaint once per loop (when the snake has moved) wouldn't it be impossible for it to dislay half drawn anyway?The game works great with no flicker but obviously it's simple and my computer is fast so i'm not sure if that is just covering for what could be bad programming.Anyway any help would be greatly appreciated. How do people around here feel about people posting the code for a whole program? As I've never had any real feedback about my code it would be hugely benificial to get criticism, but i also undersand it would be time consuming for the people and i wouldn't want to come arross as selfish by asking too much. | Quote:I have only just learned about threads and i was wondering should I make my loop() method sychronized? If I don't is there a danger that the Timer could fire another ActionEvent before the last loop has finished runningjavax.swing.Timer invokes all of its timer events on one thread. This means that it's not possible to have a second gameplay tick start before the first one is finished; until the first one is finished, the thread is still busy. So there's no need for synchronization to protect specifically from other timer events.Quote:How do people around here feel about people posting the code for a whole program? As I've never had any real feedback about my code it would be hugely benificial to get criticism, but i also undersand it would be time consuming for the people and i wouldn't want to come arross as selfish by asking too much.There's sort of a paradox involved in choosing how much code to show. You're supposed to only post as much code as necessary to find the bug, but since you don't know where the bug is, you may mistakenly post too little code and not show the actually problematic part. The other concern is that faced with pages and pages of code, people will just ignore it.If you can, it's always worth the time to produce a minimal demonstrating example -- as short a piece of REAL (that is, you actually compiled and ran it and it demonstrated the problem) code as possible. This can actually help you find the bug yourself, too. ; Thanks Sneftel. I suspected that might be the case with the Timer but wasn't sure so thanks for clearing that up for me.Also to anyone thinking of replying regarding my buffer question, i think was just getting confused by how repaint() worked. I think i understand now and am looking into the bufferStrategy class, so there is no need to reply now. |
[Question] Resource Production in RTS games | Artificial Intelligence;Programming | When Developing Resource Production in RTS games after some search i found two papers talking mainly in this topic(Online Planning for Resource Production in Real-Time Strategy Games, Extending Online Planning for Resource Production in Real-Time Strategy Games with Search). The System i'm working on is using Online CBR and CBP techniques but i'm trying to enhance the performance of the Resource Production planner the question isShould the Resource Planner be: 1- "Independant Planner trying to maximize consumable resources according to some constraints and mathematical model"( somehow a combinatorial approach ).2- "Plan generator (as introduced in the two papers i.e. given certain state and try to plan the best set of Actions to get to the Goal)". | For Kohan 2, we didn't do any specific planning, but rather assumed that things were worth roughly what they cost. With that said, we did have a couple tricks for ensuring that the money went the right places...We did have some build templates, which would guide our production (for instance, so that we would try to develop one settlement that could build the most powerful units, while setting the others up for economic development). When considering building something, we would calculate it's economic value, but that looked at its change in our income (that is, how much upkeep does it cost per second, or how much income does it generate per second), while ignoring the initial build cost. The economic value would then be factored into the priority for building it, along with its military value and a host of other factors. Finally, the one thing we did that sort of resembled planning (but not really) was what we called goal commitment. That is, if we had a high priority goal that needed some resources (say, 300 gold), and we didn't currently have enough gold to complete that goal, but at our current income rate we would have enough soon (i.e. within a minute or two) then we would not execute any lower priority goals until the high priority goal was completed. So for example, if we wanted to upgrade our settlement (which was a huge deal and critical to success), that typically was more expensive than the amount of cash we'd have on hand. However once our income reached the point that we could reasonably save for it we would, since that was also a very high priority goal to achieve.More details can be found in my AI Game Programming Wisdom 3 article, if you're interested... ; @Kevin DillYour way of attacking the resource production problem is very interesting and I see that waiting for 2 or 3 minutes to get the 300 gold an issue that would be further enhanced.As humans play a game, they try to maximize the production rather than instant production for a specific goal. ; Well, they don't automatically wait whenever they have an expensive goal. They only wait if (a) they can save the money in a reasonably short amount of time (the amount of time is obviously game dependent - I honestly don't remember what value we used), and (b) that goal is the highest priority goal. It's a quick and dirty way to keep the AI from frittering its money away on small things, rather than waiting and building something big.If you think about it, even building units requires something like this. The smallest and weakest unit is typically the cheapest, so if you always spent money on any goal that was available, you would only ever build that unit, because you'd never have enough money to build anything bigger. As soon as you got the money to build the wimpy little unit you'd spend it.Planning is certainly an option, and has been used in RTS's - it just isn't what we did. I seem to recall that there was an article in AI Game Programming Wisdom 4 that described a planning approach to RTS AI. With that said, I'm not convinced that planning would necessarily get better results, and it's a good bit more complicated to code, balance, test, and debug. It seems to me that what you really want is designer templates (which we had), which guides the AI toward a known good build order. You can even customize the build order for different characters, in order to get different personalities. For instance, a wood elf character might go quickly toward a sawmill and archer units, while dwarf character would build a smithy and axemen. That's not something that you will easily get out of a planner - it will always do what is "optimal," which may or may not be something that looks cool. |
deplacement in 2D space | Math and Physics;Programming | Hi guys,I'm writing a bawling game for the iPhone and I'm preparing my own "physics" engine because I don't need much.Is really simple what I have to do, I need to launch a ball from the bottom of the screen to the upper part. I prepare a system that give a point in the screen(UITouch) it calculate the angle between the y-axis and the vector is created. (I use atan to calculate this angle and I think I'm ok with this. I have negative angle when I touch on the right side of my ball and positive on the left.) The angle are right I checked and they seems the right ones.My problem is when I have to launch the ball and calculate the new x and y coordinates.When I draw the new position of the ball it's like my launch is rotated 45 degree counterclockwise. (If I touch upper right it goes up. If I touch right it goes upper right..so on)I'm really upset with this I can't figure out what's the problem. I tried playing with the angle(adding PI/2) to rotate all the stuff but I'm doing something wrong.Thank you in advance for your help.- (void) applyForceToObject:(int)force withDirectionVectorX:(int)vectorX vectorY:(int)vectorY { double x1 = (vectorX - self.x);double y1 = (vectorY - self.y); trajectory = atan(x1 / y1);NSLog(@"Trajectory:%f rad, %f degree.", trajectory, trajectory*180/PI); speed = force;}- (void) updateWithTimeInterval:(NSTimeInterval)timeInterval { timeSinceLastUpdate = timeInterval;timeSinceFirstUpdate += timeSinceLastUpdate; self.x += timeInterval/100*speed*cos((trajectory + (PI / 2)));self.y -= timeInterval/100*speed*sin((trajectory + (PI / 2))); // I sottract this because the y axis is inverted. (0 up, 320 down)} | |
Survival Games? | Game Design and Theory;Game Design | Hi,I am thinking about doing a survival game.Something like Robinson Crusoe where theplayer has to find food, water and shelter...Anybody have played similar games, wouldlove to have a look how at they are designed.thanx :D | Robinson Requiem, the best one.There was a german game, "shipwreck", "shipshaft" or something, can't recall the title.One or two roguelikes about this (one was survival in a forest as a celtic warrior, don't recall the title).A futuristic game about a pilot crashing on a planet "Noctris", "Nocturis", something starting at 'N'. But that one was more like action shooter, still the feeling was of a robinson.Oh yes, one of my minigames should count as well :)http://worldoflords.com/misc/games/radioactiveshelter/ ; I would definitely consider such a game. Mind you, I'm more of a simulation fanatic; so realism would be the most important element to me. A survival game which really immerses the player in the dilemma of survival can be a very difficult thing to accomplish. So much of survival in the real world is making tools, which relies upon a person's patience, knowledge and dexterity. Not only do we not have controllers sophisticated enough to model such a thing, but it is actually a pretty dull and lackluster part of survival....hunting monkeys is so much more fun! :) So my feeling is that yes, you can pull it off and make an excellent game...but you'll have to decide how you can emulate the experience in a game in a manner by which it is still FUN. ; @AcharisHave you played Robinson Requiem alot? I remember the time when Robinson Requiem came out.It got a review with a score about 70% in PC player i think,decent enough. Though some horrible reviews too becauseof its difficulty.If you recommend it, I will try to find it and have a closerlook. Oh, I checked your mini game, enjoyed it while stayingalive for 45 days! :D@keinmannI agree completely. I think the atmosphere and the feeling ofsurvival in player's mind would be the most important. ; It was awesome and horrible at the same time. The good point of RR was realism, you really felt like you really crashed on that planet and everything was real. The bad point was realism, to use first aid kit you had to be a medicine student in real life at least. You weren't "playing" that game, you were more like doing "things" and watching dying for various reasons (typically for unknown reasons if you attempted to patch yourself via medikit :D)RR is abandonware, so you can grab it easily and without moral dilemmas :) ; The Sims Castaway anyone?The PS2 version was somewhat decent, although extremely easy like any Sims game.Still you had to harvest many kinds of resources, make tools with those resources and build a shelter (build, not buy) ; i dont think there is any fps survival game where you have to eat and stuff , it would make a interesting mmo for sure. ; Have you tried Minecraft? It's pretty popular these days. ; I was just about to suggest the same, "Minecraft Alpha". It's basically about surviving the nights in a random generated world. Well ok, and mining of course :-), but you can definitely get some great ideas out of it for building a survival game.; Minecraft isn't so much a 'survival' game, as it is a 'don't get raped by the undead at night' game.In a survival game I would expect to be forced to survive against the elements and nature. Find food and water, don't let your body temperature get out side of normal ranges, don't get attacked by wild animals, etc. I would love to see an advanced simulation for survival that allowed you to deal with shaping stones and branches to actually make the tools, shelter, fences, and other things. |
How would I go about creating a virus? If you read the post it isn't as bad as it see | For Beginners | Ok when i say virus you probably think computer crippling disease. but the one i want to make is going to be used as a laugh and no harm is going to be done.Ok the idea i was thinking of was called The Rick Roll ( yeah i know but my mates hate him)and i thought it would be cool to annoy them with it.i want it to. Play 'Never Gonna Give You Up' on a loop.. Set the volume to a constant 50 and you can't turn it down.. When headphones are plugged in it still plays from their speakers.. You can't turn it of, except for task manager ( i am not that mean)Would it play though Windows Media player, also it would be some sort of annoying background activity (meaning they can still use their computer like normal). I am using C++ at the moment, but most viruses are made in notepad ain't they. | depending on what you want to do there are limitations on what you are asking especially now with windows 7 that has self contained audio levels per application ; You are obviously on the wrong website. This website is all about game development. Besides, you didn't ask anything in your post. I'll just give you a simple piece of advice: don't create a virus - dispite your seemingly harmless intention. ; A) No.B) No.C) NO!Even relatively "harmless" viruses that spread widely can end up costing a lot of money (distributed over many people in terms of time and effort removing it and regaining control of their system, bringing it in to tech shops for repair etc.)Beyond potential legal ramifications this is in NO way a good use of your time and is not going to earn you any friends. ; This wouldn't be a "virus" anyway. A virus is code that replicates itself in order to spread. You are just talking about building a malicious program. It requires no specific knowledge to do so. For an experienced programmer this is a ~2 hour project.Also: Never do this. No, C++ is a programming language, notepad is a program. Writing code in notepad means nothing until it is compiled/distributed/injected.And no, notepad does not have a built in compiler. ; There seems to be a distinct lack of understanding what a computer virus is these days. Viruses are self replicating programs, designed to spread from one machine to another. What you are after is a variation of a rootkit program. They are difficult to write, as you need intimate knowledge of the operating system. In all seriousness, I would not bother, unless you want to learn or enjoy hacking.I'd rather get one of these and chuck it into the machine's USB ports. http://www.instructables.com/id/The-Trickster-USB-Computer-Prank/Make it more compact though. ; I encourage you to use notepad to write all of your viruses. Notepad accepts your ideas. Notepad embraces you. Notepad can give you the love that you're missing. C++ really can't. C++ takes your ideas and does things with them. Notepad quietly listens. C++ tries to interpret your statements and executes them. Notepad saves your statements and shows them to you later.C++ has control structures and functions, and OOP and COM. Notepad has fonts, and word wrap. C++ has syntax, Notepad is freeform. Notepad is freedom. Notepad is expression.It sounds like Notepad is what you need. ; Nope. |
Software Engineering books | For Beginners | Hello all,After some time, I'm finally managing to get a grip on the C++ language and its libraries, deal with compilers, linkers, etc. I even got my first prototype up and running with a reasonable frame rate, etc.My questions and my problems are: how to get on to the next level? I've been having lots of headaches and troubles trying to get my OOP designs solid and prone to growth, but it is just too hard! Harder even than the programming itself. Off course there isn't no silver bullet, but I really want to improve my design skills.What are your favorite software engineering books? Focused on games or not.Cheers!Fabio | Code Complete ; 1) Game Coding Complete2) Design Patterns: Elements of Reusable Object-Oriented Software ; I've enjoyed The Pragmatic Programmer ; 1) Object-Oriented Analysis and Design with Applications2) AntiPatterns: Refactoring Software, Architectures, and Projects in Crisis The second is about what not to do and how to recover from mistakes :)Hope this helps!Enjoy ; hi guys,thanks for the tips! I already have code complete & the GoF Patterns book but haven't read both of 'em. I tried the GoF, but found it incredible difficult (but I was much greener in OOP then..)What you guys think about Martin Fowler's books?; Take a look at Head First Design Patterns. It's written in the context of Java, but the code is similar enough and the information is directly relevant to C++. I found it incredibly effective at clearing up some of the fog that design patterns can create. It left me looking for opportunities to use what I had learned.; I second the Head First Design Patterns book. Very good for learning patterns, after which you might want to transfer to a drier, more direct book for reference. ; Code craft: the practice of writing excellent code |
How to detect multiple key presses in OpenGL? | Graphics and GPU Programming;Programming | Hello everybody,I am pretty new to OpenGL so please try to understand me :). I have that beautiful function void key(unsigned char k, int x, int y)which is posted to OpenGL in : glutKeyboardFunc(key);but with this function I can only detect one key being pressed at a time. How can I do it to detect multiple key presses ? | Quote:Original post by lordmonkeyI am pretty new to OpenGL so please try to understand me :). I have that beautiful function void key(unsigned char k, int x, int y)which is posted to OpenGL in : glutKeyboardFunc(key);Note that this is actually a question about Glut, which is only tangentially related to OpenGL. Regardless:Quote:but with this function I can only detect one key being pressed at a time. How can I do it to detect multiple key presses ?It will be called once each time a key is pressed. If you want to track multiple key presses, then each time the function is called, record which key was just pressed in an array (do the same with a keyup function to clear them). Then you can check the array to see all the keys which are pressed at the current time... ; And just to add on be sure you read them in individual ifs and not a set of else if's otherwise it will find one key and return. ; Ok, I have it working but i have 2 problems with this, but first i will explain what I implemented:I have something like this to atore info about pressed keys :enum key_state {NOTPUSHED, PUSHED} keyarr[127];for my array of pushed or notpushed values for every key, then i will initialized them all with notpushed valuethen:this is my : glutKeyboardFunc(key);void key(unsigned char k, int x, int y){if(k == 'd')keyarr[int('d')] = PUSHED;if(k == 'w')keyarr[int('w')] = PUSHED;if(k == 'r')keyarr[int('r')] = PUSHED; glutPostRedisplay();}this is my : glutKeyboardUpFunc(keyup);void keyup(unsigned char k, int x, int y){if(k == 'd')keyarr['d'] = NOTPUSHED;if(k == 'w')keyarr['w'] = NOTPUSHED;if(k == 'r')keyarr['r'] = NOTPUSHED; glutPostRedisplay();}and in the main draw() function (for now i don't have any other place to put it in) I put : if( keyarr['d'] ) tankTurretAngle--; if( keyarr['w'] ) wheelAngle += 5; if( keyarr['r'] ) yRot++;and it works :) but...1)when I press any key of defined ones there is this small 'lag' like in windows when you push and hold key while typing how can I omit that ?2) when I release one of e.g. 3 held keys whole animation which is running thanks to that stops. how can I handle this so that the animation won't stop but only the part responsible for the released key ? ; They keyboard functions are only called when you actually press or release a key, and consequently, glutPostRedisplay is only called when you actually press or release a key. You can actually get multiple key presses by holding the key down, but that is only because GLUT issues multiple callbacks if you hold it down, just like you can do in, say, notepad by holding down a key to "type" repeated keystrokes.What you need instead is to only record the keys in the callback functions, and then use the idle callback to redisplay your scene. Thus, remove glutPostRedisplay from your keyboard callbacks, and set the idle callback like this:void idle(){ glutPostRedisplay();}int main(){ ... glutIdleFunc(idle); ...}The idle function is called as soon as there's nothing else to do (like handling keyboard messages), which you use to update your game logics and redisplaying the scene. ; Hell yeah :) :] that works perfectly , thanks a lot. |
Reflection of big surfaces like water (GLSL) | Graphics and GPU Programming;Programming | I made a program that renders a cube map from the center of a sphere to make reflection and it works fine, but this won't work with bigger, flat objects like water as the cube map is rendered from the center only. Should I render many cube maps or is there another way? | You can use planar reflection. Instead of rendering a cube, you render the scene as normal, but with the camera flipped upside down beneath the water.To get this 'upside-down camera', you can construct a reflection matrix from the water plane and multiply that with the view matrix. You'll also want to enable a user clipping-plane so that objects below the water's surface don't show up in the reflection.Once you've rendered that to a texture, you can use the reflected view-proj matrix to project this texture onto the water (during your main pass). ; Planar reflection only seems appropriate for a perfectly flat water surface though. If you had any ripples or waves in the water this would send your normals scattering out in all directions, thus the need for the cubemap (I don't know if this is OP's case though). In that case, I guess you would just have to live with the distortion, or make a cubemap that is large relative to the object so that the inconsistency is unnoticeable? ; you could render the geometry that is visible to the waterusing a paraboloid mirror into a single texturebut what will the fresnel term be for the water surface reflecting geometry behind the camera?mostly approaching 1.0 = refraction onlywhich is why you can get away with simple reflection mapno need to mess with cameras for reflection maps:vs: posWorld.y *= -1; // reflect geometryps: clip(-posWorld.y); // clip anything above waterrs: cullmode = opposite of usual // flipping y reverses triangle windingrefraction map even simpler:vs: no changeps: clip(posWorld.y);when the camera goes underwater you just need to flip the clipping(underWater is -1 or 1)clip(posWorld.y * underWater);now to sample the reflection and refraction maps you just needvs:static const float4x4 matTexProj = float4x4(0.5, 0.0, 0.0, 0.0,0.0,-0.5, 0.0, 0.0,0.0, 0.0, 1.0, 0.0,0.5, 0.5, 0.0, 1.0);//float4x4texProj = mul(posProj, matTexProj);ps:color = tex2Dproj(smpReflect, texProj);(doing it this way means you avoid the slow dependent texture read)[Edited by - skytiger on November 11, 2010 7:00:55 PM];Quote:Original post by karwostsPlanar reflection only seems appropriate for a perfectly flat water surface though. If you had any ripples or waves in the water this would send your normals scattering out in all directions, thus the need for the cubemapIt's technically not correct, but you can use the normals to offset the UVs when sampling the planar reflection texture. It will still look much better than a cube-map.Quote:Original post by skytigerno need to mess with cameras for reflection maps:*** Source Snippet Removed ***Assuming your reflection plane is horizontal and passes through the origin ;)Also, instead of changing the cullmode to be the opposite of usual, you can isntead scale by -1 in the x axis (and flip your UVs horizontally when projecting the texture to undo the scaling). I find this easier than having to manage inverted cull modes for everything. ;Quote:Original post by skytigerno need to mess with cameras for reflection maps:*** Source Snippet Removed ***thinking about it some more, my y *=-1 technique has some small issues:a) it is easier to feed an existing shader an adjusted view matrixb) any view-dependent lighting/reflections on the reflected geometry will be wrong (think specular or rendering a mirror reflected in water)which means a reflection isn't always a mirror image ... lol ; A reflection using render-targets is unnatural, that is why it is/seems wrong. You would have to use planar reflection for every triangle and that is overkill (even with gpu horsepower and very fast stencil buffer);Although this is very noneffective and thus impossible on current hardware. You can though approximate a water surface with plane and objects with cube or sphere around if (e.g. cube map, respectively sphere map).If you want a robust solution for reflection that is correct, you probably would have to use ray tracing (and probably pretty much complex solutions to achieve correct water surface). ; Thanks everybody! I'll try to do a planar reflection and change the coordinates using the normal vectors from a normal map... |
Z-Values other than 0.0f causes black screen | Graphics and GPU Programming;Programming | *sigh*Sorry for my 3rd post about that topic, but after I didn't get any answers on my last question (regarding the use of the IDXSPRITE-Interface) I spent a lot of time trying to figure it out myself - and I finally succeded. It will take a lot of time re-writing nearly my whole code from having dozens of sprites to only have on sprite and use it to render all textures at the needed possitions.. but anyway, I encounter another problem:Whethever value for z I use other than 0.0f, the grafic isn't drawn at all. First thing I checked is if the z-buffer is switched on. It is, because deactivating it will show all grafics, even with not null z-values.But beside of this, I don't have a single Idea.So, I stepped back to a former backup from somewhere around juli where I didn't have much more stuff than a background and some basic features, to make sure there is nothing in my code that could possibly cause that issues. Still, any value other than 0.0f would cause the texture not to be drawn (or, in a few cases I get a very strange looking grafic issues, seems like some parts of the texture are drawn and others are not).I uploaded a sample of that problem here:http://rapidshare.com/files/431443436/SideScrollerEngine.rarIt's basically a project showing that issue (there is some unnessacary stuff in it, sry for that), including source code and one pre-compiled exe.What you will see if you open it is: one blue grafic drawn a bit apart from 0,0 , and in between the graphic all black.Now look at this code:void CSprite::Draw(void){m_vPosition.x = 0;m_vPosition.y = 0;m_vPosition.z = 0.1f; DWORD ModulateColor = 0xFFFFFFFF; m_lpSprite->Begin(D3DXSPRITE_SORT_DEPTH_FRONTTOBACK | D3DXSPRITE_ALPHABLEND); // Sprite zeichnen m_lpSprite->Draw(m_lpTexture, NULL, NULL, &m_vPosition, ModulateColor);m_vPosition.x = 100;m_vPosition.y = 100;m_vPosition.z = 0.0f;m_lpSprite->Draw(m_lpTexture, NULL, NULL, &m_vPosition, ModulateColor); m_lpSprite->End();}If you change the linem_vPosition.z = 0.1f;to m_vPosition.z = 0.0f;the grafic will appear. Does anybode have an idea, or maybe want to take a look at the project I uploaded? I would really appreciate this, that issue is just nasty (man, I figured out all that other crap why my z-buffer aint working, now I still can't use it because it doesn't allow any other values than 0.0f?? holy crap..) and I'm currently running in more and more situations while programming where a z-value would be really nice. thx in advance.. | Post the code where you set up your projection matrix. Sounds like your near and far clip plane are too close together for what you're trying to do.-me ; Well, uhm... I don't use any projection matrix at all oO or I just don't set up one, dunno.. maybe thats the problem? I'm currently just setting up all that Direct3D-Stuff, and thats it. To move the scene/camera, I just move it. Though I read that I shouldn't do this it works quite fine, and I don't have any issues right now. But could you tell me how to use such a matrix? I would regret not to use it to move the camera, but if I have to only set it up to use z-buffer, I'd do that, if I knew how (all my books/tutorials somehow don't cover that topic, except for 3D-Graphics; btw I'm doing a 2D-Game, thought that this would be clear).. ; The projection matrix doesn't position the camera, but defines the "lens" it uses. A great reference is the DX SDK docs, ; Thanks so far for explaining this... but it won't work eigther.Tried it this way:D3DXMATRIX Matrix;D3DXMatrixOrthoLH(&Matrix, 1024, 768, 0.0f, 1.0f);m_lpD3DDevice->SetTransform(D3DTS_PROJECTION,&Matrix);in the method to set up my Direct3D-Device:BOOL CDirect3D::Init(HWND hWnd, BOOL bWindowed){ // Direct3D-Objekt erzeugen m_lpD3D = Direct3DCreate9(D3D_SDK_VERSION); if(NULL == m_lpD3D) { // Fehler, D3D-Objekt wurde nicht erzeugt return FALSE; } // Parameter fuer den Modus festlegen D3DPRESENT_PARAMETERS PParams; ZeroMemory(&PParams, sizeof(PParams)); PParams.SwapEffect = D3DSWAPEFFECT_DISCARD; PParams.hDeviceWindow = hWnd; PParams.Windowed = bWindowed;PParams.PresentationInterval = true; PParams.BackBufferWidth = 1024; PParams.BackBufferHeight = 768; PParams.BackBufferFormat = D3DFMT_A8R8G8B8;PParams.EnableAutoDepthStencil = 1;PParams.AutoDepthStencilFormat = D3DFMT_D16;PParams.PresentationInterval = D3DPRESENT_INTERVAL_ONE; HRESULT hr; // Direct3D-Geraet anlegen if(FAILED(hr = m_lpD3D->CreateDevice( D3DADAPTER_DEFAULT, D3DDEVTYPE_HAL, hWnd, D3DCREATE_SOFTWARE_VERTEXPROCESSING, &PParams, &m_lpD3DDevice))) { // Fehler, Geraet kann nicht angelegt werden const WCHAR* Err = DXGetErrorDescription(hr); DXTRACE_MSG(Err); return FALSE; } // Schrift erzeugen m_lpD3DDevice->SetRenderState ( D3DRS_ZENABLE, TRUE);D3DXMATRIX Matrix;D3DXMatrixOrthoLH(&Matrix, 1024, 768, 0.0f, 1.0f);m_lpD3DDevice->SetTransform(D3DTS_PROJECTION,&Matrix); CreateFont(); // Zeiger auf dem Hintergrundpuffer holen m_lpD3DDevice->GetBackBuffer(0, 0, D3DBACKBUFFER_TYPE_MONO, &m_lpBackBuffer);m_lpD3DDevice->Clear(0, 0, D3DCLEAR_TARGET, m_ClearColor,0, 0); return TRUE;}Did I forget anything? Maybe handing some parameter to the Device (I thought I read something about that somewhere in that forums).. ; First, are you using Debug Runtime? If not, do that. It will give you a lot of information.Second, even though you want a 2D app, you should work through several of the examples in the SDK to learn how to setup DirectX. I understand they're 3D but you need to learn the basics.With regard to the code you posted, you have several problems.If you're setting up in windowed mode, don't set the backbuffer width and height in the present parameters. CreateDevice will take the dimensions of the client area of the window to size the backbuffer for you.For readability, it's always a good idea to match variable types when setting a parameter. E.g., EnableAutoDepthStencil is a BOOL. Set it to TRUE or FALSE, not "1".Never set the near-plane of your projection to 0. You can set it to a small value if you like, such as 0.1f, etc.Also, you should set up a viewport. Look at the documentation and some example code to see how to do that. ; Thx for the advice, gonna check that out and correct it. I don't use the debug routine yet, but I tried it out, thats what I get:Direct3D9: :====> ENTER: DLLMAIN(00e2e6e0): Process Attach: 000015d8, tid=000015d4Direct3D9: :====> EXIT: DLLMAIN(00e2e6e0): Process Attach: 000015d8Direct3D9: (INFO) :Direct3D9 Debug Runtime selected.D3D9 Helper: Enhanced D3DDebugging disabled; Application was not compiled with D3D_DEBUG_INFODirect3D9: (INFO) :======================= Hal HWVP device selectedDirect3D9: (INFO) :HalDevice Driver Style 9Direct3D9: :BackBufferCount not specified, considered default 1 Direct3D9: :DoneExclusiveModeWell, anyway, is there no solution for my actual problem? It seems to be not a problem of projection, but.. chaning values in my Matrix for the projection doesn't do a damn thing, even if I use all 0.0f-values for the sprites. I'm getting fed up.. it can't be so hard making that damn z-buffer to work. I mean, how many people in the forum have done that correctly? Can't somebody say whats wrong with my code, or is everything alright here (everything that has something to do with the problem of the z-buffer)? ; This is you setting your projection matrix:D3DXMatrixOrthoLH(&Matrix, 1024, 768, 0.0f, 1.0f);0.0 -> near clip plane1.0 -> far clip planeI believe that with a projection matrix like you have, it will only render objects with z coordinates of -1.0 -> 0.0 (if your camera is pointing down the negative z axis. i.e. looking "down"). Your far clip plane is 1.0 units away along the camera's view axis. Since your camera is probably looking down the negative z axis, this is why your objects aren't showing up with > 0.0 z. You can easily test this experimentally by setting the z = -0.1. It should render. You can then either work with negative z values [-1.0..0.0] or you can change your near plane to -1.0 and your far plane to 0.0 which will allow z values of [0.0..1.0]-me ;[qoute]I believe that with a projection matrix like you have, it will only render objects with z coordinates of -1.0 -> 0.0 (if your camera is pointing down the negative z axis. i.e. looking "down"). Your far clip plane is 1.0 units away along the camera's view axis. Since your camera is probably looking down the negative z axis, this is why your objects aren't showing up with > 0.0 z. You can easily test this experimentally by setting the z = -0.1. It should render. You can then either work with negative z values [-1.0..0.0] or you can change your near plane to -1.0 and your far plane to 0.0 which will allow z values of [0.0..1.0]Thx, I tried it out, but still no render, only black screen. Tried out both, setting near and far plane to your values or changing the sprites z to a negative value. Won't work eigther..Well, anyway, a strange thing that I found out was that my screen renders at a z value of 0.0f (which we already know), BUT no matter what the Matrix I use is set to. For example, even that things like:D3DXMatrixOrthoLH(&Matrix, 232, 500, -110.0f, 120.0f);D3DXMatrixOrthoLH(&Matrix, 21488, 2400, 110.0f, 120.0f);will give me a fine render when using 0.0f for z, otherwise a black screen. Could it be that my transform isn't set correctly? Although the debugger doesn't show anything like that.. if I do this:if(!m_lpD3DDevice->SetTransform(D3DTS_PROJECTION,&Matrix))int i = 0;and put a halting point to the second line, it always will jump to that line. But i quess thats just how that function works.. I tried it out with FAILED() as well, but that value is not true, so I quess thats just speculations.. Any other ideas? Or can I somehow find a complete tutorial or source code that uses sprites with the z-stencil-buffer? DirectX SDK doc might be helpful but not if you have no idea why something isn't working.. with a source where sprites are used properly I might be able to figure out whats wrong.; YEAHHH!!!I found it finally out. Had nothing to do with Viewport or projection matrices (which aren't even used at all for 2 grafics from what I figured out. Viewport works, but if I set a special projection it doesn't change a damn thing).The solution:m_lpD3DDevice->BeginScene()m_lpD3DDevice->Clear(0,NULL,D3DCLEAR_TARGET | D3DCLEAR_ZBUFFER,D3DCOLOR_XRGB(255,255,255),1.0f,0);I didn't know that I had to clear the buffer (although it was so plain logical -.-), found it out using google.. Wasn't mentioned in my books eigther oODid nobody knew that our did everybode just assumed that I was already doing this? oOBut anyway, now it won't even matter if I use more than one Sprite-Interface, they are all aligned perfectly at the z-value.*sigh* at least I got that stuff out of the way.. only have to edit the code to only use 1 sprite interface but just for speed improvements.. |
Extreme Values of a Closed Surface / Normal Vector | Math and Physics;Programming | Hello folks, I have a question:As fas as I know, if you have an ellipsoid and a point p lying on the surface of that ellipsoid, then point p corresponds to the extreme point on the surface in the direction of the surface normal vector in point p.Which properties does a surface have to fulfill in order for this rule to be true? | Quote:Original post by DesperadoHello folks, I have a question:As fas as I know, if you have an ellipsoid and a point p lying on the surface of that ellipsoid, then point p corresponds to the extreme point on the surface in the direction of the surface normal vector in point p.Which properties does a surface have to fulfill in order for this rule to be true?Convexity. ; Thanks. If you could also provide me with a reference that formulates it that way, I would be completely satisfied. ; Sorry for being that late:Computational Geometry: Algorithms and ApplicationsThird Edition (March 2008)Mark de Berg, TU Eindhoven (the Netherlands)Otfried Cheong, KAIST (Korea)Marc van Kreveld, Mark Overmars, Utrecht University (the Netherlands) ; Very well, thank you.One more question:I have a bending operation that makes a circular bend on an ellipsoid along it's longest axis (the axis gets bent to a circle segment and the circle radius determines the curvature of the bend). This, of course, makes the ellipsoid concave. Is it still possible to efficiently calculate the extreme point into a direction for such a shape?Thanks ;Quote:Original post by DesperadoVery well, thank you.One more question:I have a bending operation that makes a circular bend on an ellipsoid along it's longest axis (the axis gets bent to a circle segment and the circle radius determines the curvature of the bend). This, of course, makes the ellipsoid concave. Is it still possible to efficiently calculate the extreme point into a direction for such a shape?ThanksYou can always use a brute force method.Sorry for the reference. The right one is:Computational Geometry in C, Second EditionJoseph O'RourkeCambridge PressThere's a subsection devoted to that specific question:Chap 7.10: Extremal polytope Queries p. 280Reading the introduction of the subsection, nothing is said about the convexity (or non convexity) of the polytope. The method exposed has an O(logN) complexity. |
What books did developer read for game development in the 1990s? | For Beginners | I want to make a game But I wonder how game developers worked in the 1990s, how they made games, how they learning before the Internet became as widespread as it is today. etc.how do they know how to build game mechanics as character ability power up system?how they know to reverse engineering game competitor company.what book I should read? | As far as I know (not being a programmer myself), books on the subject started appearing in the early 2000s. Up to that point, it was “learn by doing” and tips from one another. ;The first book that came to mind was Tricks of the Game-Programming Gurus: Lamothe, Andre, Ratcliff, John, Tyler, Denise: 9780672305078: Amazon.com: Books, which was geared toward beginners/students/amateurs. There were others, but that's the best selling pre-2000. After that point in time, game development became a hot topic in the book publishing world. Even GameDev.net has a series - Beginning Game Programming: A GameDev.net Collection (Course Technology Cengage Learning): 9781598638059: Computer Science Books @ Amazon.com.Otherwise, in the professional realm a lot was “learn by doing” as Tom said, or through word of mouth on early Usenet/IRC/websites (pre-GameDev.net in 1999 - see About GameDev.net). ;Computers in that era didn't have an OS like we have today. The machine booted, and you were dropped in a command shell or in an interactive BASIC interpreter. You basically programmed directly at the metal. Video memory was directly accessible, by writing in a known address range you could make pixels appear at the screen in various colors. The “OS” had a corner in the memory too for its data, but nothing prevented you from poking around there. Lua, Python, C#, C++ didn't exist, ANSI-C was just invented (K&R book about that was in 1989 iirc). Assembly language of course did exist (with books) and was used.Monthly computer magazines were published for all types of home computers. Tips and tricks were exchanged in that way, also program listings were printed in those magazines that you could then enter at your own computer. Studying those listings, and trying things for yourself is how you learned. There was also technical documentation about the computer.If you want to enjoy that stuff, today there is a retro-computing movement, that lives in that era, except with slight more modern hardware but still no OS, etc.;Alberth said:Computers in that era didn't have an OS like we have today.In the 1990s there was MSDOS, Several versions of Windows, and of MacOS. And that's not all the operating systems of the nineties, most likely.Like Linux, for instance.;Tom Sloper said:Alberth said:Computers in that era didn't have an OS like we have today.In the 1990s there was MSDOS, Several versions of Windows, and of MacOS. And that's not all the operating systems of the nineties, most likely.Like Linux, for instance.Yep. There were things like Windows 95, Win 98, and at the time I was still using a Commodore Amiga (AmigaOS) .To deal with the original question “what game dev books was I reading in the 90s?” Back in that era, one of my favorites was : The Black Art of 3D Game Programming by André LaMothe. ;Abrash was the guy who did the Windows NT graphics subsystem and worked on Quake.https://www.drdobbs.com/parallel/graphics-programming-black-book/184404919 ;There are a couple of" history of video games" books, that track the rise of the medium and genre.Just google for them. ;GeneralJist said:There are a couple of" history of video games" booksThat's not what the OP is looking for.;Thanks all |
Choosing a career in AI programmer? | Games Career Development;Business | Hello everyone, my name is Ramon Diaz; I am currently studying Game development and programming at SNHU. I have taken the initiative to learn about a professional career in AI programming. I have a lot of gaps in my development in the short term. I have blueprint experience with AI but not enough to choose a career in this profession. I would like to know how I can be competitive leaving the university in 5 months after finishing my studies. I am looking for knowledge from all of you who have been in the industry for years. | Entry level? Know your algorithms, it will help you at interviews. If you have made demos it can help you get jobs, but the market is wide open right now and should be relatively easy to find work for the foreseeable future. Overall, it reads like you are on the right path. When you graduate and start looking for work, be open to any positions rather than just an AI specialty. Once you have a job it is easier to transition into whatever specialty you prefer.;Thank you. ;I would like to know how I can be competitive leaving the university in 5 months after finishing my studies.Talk about last minute. Create AI projects? Or A game with character behaviors? Pathfinding examples. Crowd movements. Anything really. Learn how navigation meshes work.;@dpadam450 Character Behavior is what I doing in the project at this moment. Everything related to AI programming.;@dpadam450 Is it the same when learning C++ in AI as visual scripting Blueprint? If I were to make a demo, what kind of programming should I focus on my attention? ;@frob It is important to have a portfolio? ;Not for programming. You will need to show you know how to do the work, but it is usually some interview questions and writing some code of their choice. If you have something you want to share with them, you can do it if you want. Having done fancy demos can sometimes help get interviews, and can help show your interest and abilities, but it is generally not needed. It does not hurt, unless you do it badly and therefore becomes a cautionary warning. Build it if you want. I have interviewed and hired bunches of programmers without portfolios. ;I'm studying AI at the moment, in terms of statistical learning. I've learned so much about AI over the past few weeks. Check out: https://hastie.su.domains/ISLR2/ISLRv2_website.pdfandMachine Learning with R: Expert techniques for predictive modeling, 3rd Edition |
Newbie desperate for advice! | Games Business and Law;Business | Hi allI'm new to the game development community and need some advice.I've created 2 educational games with a simple idea but are sufficiently challenging for all ages. These could be played on pcs or phones.Is it worth patenting any parts of the games?What would be the best way to monetize?How should I market the games? | hendrix7 said:I'm new to the game development communityReally? Your profile shows that you've been a member here since 2004, and your last activity was in 2007, asking about raycasting.hendrix7 said:Is it worth patenting any parts of the games?Probably not. Expensive and there will be hurdles, and possible lawsuits after the patent is granted (if it is).hendrix7 said:What would be the best way to monetize? How should I market the games?There are several threads here in the Business and Law forum about that. While you wait for more replies from the community, you can read up on those previous answers to those questions. Mainly, “you should have thought about that before you finished your games.” (You wouldn't be “desperate” now.) Good luck with your sales!;@hendrix7 Filing for a patent can be expensive, and you need to document the solution and how it separates from anything else. I have developed software that solved problems in a way that no other software does, but there is only a very small portion of that that can actually be patented. Even though you can file an application yourself, I would recommend hiring an experienced IP attorney. This too is very expensive, though, so you are best off doing this if this idea can provide millions in income. If it can't, then it's actually not that harmful if anybody copies it.You could look at registering trademarks, design and other parts of the games. This is cheaper, but it will protect you brand more than your idea or solution.Again, if this is something that could turn a real profit, it might be worth looking into. If not, it's a very costly waste of time.As for marketing - my day job is actually creating videos and commercials etc., so naturally that's the first thing that comes to mind.Make videos for social media or other platforms where your target audience is likely to see it. Oh, and you need to define a target audience. Know where they are, what they respond to, what their struggles are and how your product will solve their problems, enhance their life experience or in other ways contribute positively to their life.There are several other ways to do this, but the list exceeds my level of expertise in the area.;patenting is costly, and time intensive. As said above, it depends on a lot if it's worth it. ;@hendrix7 Nothing is worth patenting unless you're willing and able to defend your patent. There is no patent police; you're responsible for finding and prosecuting infrigement.What you're patenting has to be novel and non-obvious to a person skilled in the art. You called your idea ‘simple’ which makes me wonder if it's obvious or already in use.;@Tom Sloper Thanks TomI have been programming for a while but not games until now.Thanks for getting back and your advice, particularly patents.;@scott8 Thanks for your reply.I see. The play of the game utilises basic maths skills so I'm guessing it'll be difficult to identify anything that's unique. I suppose, in a similar way, it would be difficult to patent something like ‘Wordle’. Am I right? |
Hi I'm new. Unreal best option ? | For Beginners | Hallo everyone. My name is BBCblkn and I'm new on this forum. Nice to virtually meet you 🙂. One of my biggest dreams is to make my own videogame. I love writing design as in text on how my dream game would be. Now I got no skills to create it. But who knows what life will bring. Is Unreal the best program to have fun with an experience ? Obviously I prefer a simple but capable program. Not pre designed auto drop. Why not install Unreal and roam into it and see if anything happens.My favorite games are in the genre of Fantasy, usually stone age with magic. Dota, Homm, Diablo and the odd one out is the genius Starcraft 1. But I played plenty of different games, especially when I way younger. I don't game currently at all but designing gets my creative juices flowing and is so inspiring and fun. Thanks for having me guys | BBCblkn said:My name is BBCblknI am truly sorry for you. Even Elons daughter has a better name than that.BBCblkn said:Is Unreal the best program to have fun with an experience ?Give it a try, but it's not meant for total beginners.Starting small always is a good idea. 2D is easier than 3D. You could try GameMaker, learn some programming language, learn some math, move on to more advanced engines like UE or Unity… ;There's honestly no perfect program for beginners. If I had to compare Unreal though at my skill level, I would probably pick Unity. However, It really comes down to your needs, and how much programming you want to learn. Furthermore, I would also keep in mind other engines.;@BBCblkn I'd recommend Gamemaker studio 2 as a first engine. It's easy to learn and I haven't had a problem making my game ideas in it yet.There are some good tutorials on YouTube to follow to learn it. Do note you'll be limited to 2D games with GMS2.Bit late to the post, but I hope it helps;gamechfo said:Bit late to the postTwo months late. Always consider whether you honestly believe that a question asked long in the past is still awaiting an answer. Thread locked. |
How to publish a book? | GDNet Lounge;Community | Hello, So, over the holidays I finished my 1st book. Do any of yall writer types know where I can find:an editorpublisherIt's like 99% done, just need to know what to do next. Also, it's cross genre, so it doesn't necessarily fit the standard model. | You've given nowhere near enough information to get a final answer, but I can suggest next steps for you. (For background, I've worked as an author, co-author, editor, and ghostwriter on 9 books so far.)Publishing is a business deal. You need to figure out what business services you need.Do you even need a publisher? Do you need a distributor? You already mention needing an editor. Do you need marketing? Do you need retail agreements? Digital or physical? If physical, POD or offset, how many each of hard or soft, what size of print run can you afford? What business services do you need? Publishers have an awful lot of potential features of what they can provide and what those services cost.Once you know the list of services you actually need, your favorite bookstore will have books that have listings of all the major publishers and hundreds of minor publishers, along with the services they provide and the specialties they work with. Work through the listings methodically, and talk to them all until you've got a deal. You'll also want to start shopping around for a lawyer at that point, both because they have connections and because they'll be working with the contracts you'll be signing.Once you know what you need and have talked with your lawyer the first few times, you will be ready to start shopping around. It's far better if you have more money and are using the publisher as a paid service. That is, you pay them for the services they provide up front. It will cost you many thousand dollars but you'll require far fewer sales to reach profitability. It can be better to do an online plus POD service starting out if you're self funded. If they need to front any of the money there will be two phases to the deal, one phase before it's profitable and another after a threshold is reached and it's profitable. The exact terms will depend on your needs and the services they'll be providing. Before you sign with anyone, you'll need to work back and forth more than once with your lawyer to help you negotiate what's fair in the agreement. Good lawyers understand the costs of the various services and can help you get fair rates.Just like publishing games, the more you need from them the harder your pitch becomes. If you need a lot of services the more it will cost you. If you're looking for them to invest in you, front you money, and pay for the books, don't expect a lot of money from the deal, and in addition your pitch needs to be amazing and you'll be rejected many times. If you've got the money to self-publish and are only looking for retail agreements that's rather easy. ;hmmmWell Self publish might work too. I'm looking for:an editor publishing distribution for ebookNo hard cover or physical book planned at this timemaking cover art. Future Audio book production. I think that's it. I'd be willing to do physical print if needed, but I don't really want to pay for that at this time. frob said:You've given nowhere near enough information to get a final answer The issue is I don't know what questions or criteria I should be asking or looking for. ;Have you considered publishing with Packt?https://www.packtpub.com/;GeneralJist said:2. publishing distribution for ebook 3. No hard cover or physical book planned at this timeFor distribution of an ebook there are plenty of options. Amazon is the biggest with kindle direct publishing requiring little more than an html file and an image for the title. If you are comfortable with software tools you can use that same document to build/compile every other format out there. You're on the hook for everything else with the business if you go that route, but it can work well if you are marketing through your own channels.There are many ebook publishers out there targeting specific platforms and specific readers or specific genres. I mentioned publisher lists, they also include electronic-only publishers. Understand the tools they use against piracy are also helpful since otherwise anybody with access to the file can make unlimited copies.Be careful of contracts, you almost certainly want something that has a non-exclusive agreement since you've done all the work yourself already. If a publisher wants an exclusive deal they need to be putting quite a lot on the negotiating table.GeneralJist said:4. making cover art.Find an artist with the style you like and contact them. Often it's in the range of a couple hundred bucks, especially for ‘unknown’ artists when they're starting with something that wouldn't have seen the light of day otherwise. Artist friends are best, and asking around at local art schools is inexpensive.GeneralJist said:5. Future Audio book production.If you don't need it now, it's something easily done later.GeneralJist said:1. an editorThis one is the most difficult. Skilled editors are amazing. If you go with a publishing house they'll provide professional editors, at professional rates. ;taby said:Have you considered publishing with Packt?https://www.packtpub.com/hmmm 1st time hearing of them.Looks like they are more of an educational option?My book is a mix of mental health journey auto bio, and Sci Fi elements. It's not really a standard “how to” for game dev. ;so I just heard back from my 1st publisher submission.https://triggerhub.org/And they essentially say they be willing to look at it deeper, and have extensive edits to focus on the mental health angle. but they would want me to cut a lot. From what they are hinting at, It sounds like they want to cut a lot of the Game dev and gaming journey, as they are a publisher focused on mental health.So, now I need to decide what to do.I sent them back an email saying I'm open to continued dialogue.Without knowing exactly what they want to cut, and edit, I don't know how to proceed.Also, would it be better to hold out, and find a publisher that is willing to accept most of the game dev journey, as I'm looking for a continued publisher to work with, aka accept most of the book as is. Any advice would be helpful.Thanks yall. ;GeneralJist said:Any advice would be helpful.Look into your own mind and heart.;hmmmok,So I've submitted to a few other places.We shall see.I submitted to this place called author House, and they got back to me really quick, but it looks like they want me to pay a couple thousand for a package:https://www.authorhouse.com/en/catalog/black-and-white-packagesI personally find that a bit frustrating.I mean, really, I wrote the book, I thought traditional publishers get paid from a % of sales?@frobWhat do you think?Is the above package a good deal?I was also a little put off, as it seems the person who called me didn't even read anything about my book, and asked me “so what's your book about?"beyond the above, how does this usually work? Edit: so, after a bit of basic research, it seems the above organization is a bit scamy. The hunt continues. ;You're unlikely to get a publisher deal, where the publisher pays you an advance and distributes your book to retail outlets.You'll have to self-publish, meaning you have to bear all the costs for printing, and nobody will distribute it for you. https://en.wikipedia.org/wiki/Vanity_press |
First-person terrain navigation frustum clipping problem | General and Gameplay Programming;Programming | I am trying to develop first-person terrain navigation. I am able to read a terrain and render it as well as to move around the terrain by interpolating the location of the camera every time I move around. The main problem I have is that depending on the terrain, i.e. moving on a sloping terrain, the near plane clips my view (see below). What is the best way to avoid this? Presumably, I can interpolate the heights for the bottom corners of the near plane … any help would be appreciated. | I believe this can aways be an issue. I mean if you are clipping to a near plane and that plane passes through geometry, it has to do something. That being said you technically don't have to clip to a near plane at all, however many graphics APIs require it. Another other thing to consider is once you have collision working, you can put your camera, including your near clipping plane inside a collidable object, for instance a sphere, such that this problem will never occur. If you are eventually going to make this a real first-person game, that should take care of the problem since your camera will be inside the players head. Even in a 3rd person game you can put them inside a floating sphere. ;Gnollrunner said:That being said you technically don't have to clip to a near plane at all, however many graphics APIs require it.The near clip plane is always needed, even if you use a software rasterizer. If you don't do the clipping, vertices would flip behind the camera, causing glitches way worse than what we get from clipping.mllobera said:What is the best way to avoid this? Presumably, I can interpolate the heights for the bottom corners of the near plane … any help would be appreciated.Yes, basically you want to ensure that the camera is in empty space (above the hightmap), not in solid space (below the heightmap).But in general you can not treat the camera as a simple point, because the front clip plane requires a distance larger than zero. So ideally you build a sphere around the camera which bounds the front clip rectangle of the frustum, and then you make sure the sphere is entirely in empty space, for example. In the specific case of your terrain not having too steep slopes however, it should work well enough to sample height below camera, add some ‘character height’, and place the camera there. That's pretty simple and usually good enough for terrain.It's quite a difficult problem mainly for 3rd person games in levels made from architecture. It's difficult to project the camera out of solid space in ways so the motion still feels smooth and predictable.Some games additionally fade out geometry which is too close, attempting to minimize the issue.Imo, the ‘true’ solution to the problem would be to let the clipping happen, but rendering the interior volume of the geometry as sliced by the clipping plane.That's pretty hard with modern rendering, which usually lacks a definition of solid or empty space. But it was easy to do in the days of Doom / Quake software rendering. When i did such engine, it was possible to render clipped solid walls in simple black color. This felt really robust and not glitchy, so while it does not solve all related problems, i wonder why no game ever did this. ;@undefinedJoeJ said:The near clip plane is always needed, even if you use a software rasterizer. If you don't do the clipping, vertices would flip behind the camera, causing glitches way worse than what we get from clipping.You can clip to a pyramid instead of a frustum. I used to do this many years ago on old hardware. So there is no near clipping plane. In fact you don't need a far clipping plane either.Edit: Just wanted to add as far as I know the near and far clipping planes mostly have to do with optimizing your Z resolution. If you are dealing with that in other ways, I think they aren't strictly necessary. I currently don't even deal with the far plane and let LOD solve Z-fighting issues.;Gnollrunner said:You can clip to a pyramid instead of a frustum.I see. You still have front clip. It is a point, formed indirectly as the intersection of the other other frustum planes.I've misunderstood your claim to be ‘you don't need a front clip’. But you didn't say say that. Sorry. But now i'm curious about the experience with z precision you have had. I guess it just worked? Which then would probably mean: All those painful compromises of ‘make front plane distant so you get acceptable depth precision for large scenes’, are a result of a bad convention being used by APIs?Or did you use no z-Buffer? ;@undefined My whole engine is based on aggressive LOD and culling. I don't do projection in the matrix. It's a post step. My Z coordinates are world distances. My current project does have a near clipping plane mainly because DirectX wants one, but it's not that relevant for my application.;Ah, so you use the pyramid for culling only. But for rasterization, the usual front clip plane at some distance i guess.Still an interesting question if ‘some distance’ is really needed, but i guess yes.I did some experiment about point splatting. It uses spherical projection, which is simple than planar projection:auto WorldToScreen = [&](Vec4 w){Vec4 local = camera.inverseWorld * w;if (local[2] < .1f) return (Vec3(-1)); // <- front clip at some distance of 0.1Vec3 screen = (Vec3&)local;screen[2] = length(screen); // if it was zero, i'd get NaN herescreen[0] = (1 + screen[0] / (screen[2] * camera.fov)) / 2;screen[1] = (1 + screen[1] / (screen[2] * camera.fov)) / 2;return screen;}; Planar projection would cause division by zero too, i guess.;Thanks for all your comments! I will need to investigate how to do what Gnollrunner proposed (about putting the camera inside of a sphere). ;This may be obvious, but in case it helps:Let me note that, as a first-person camera may be more likely than a third-person camera to draw very close to geometry, it likely makes some sense to have a smaller near-plane distance for the former than the latter.Now, this only ameliorates the problem, it doesn't remove it entirely: it means that the problem will still appear, but only if the player gets very close indeed to a surface. It's intended to be used in conjunction with one or another means of preventing the camera from approaching quite so near to a surface (such as the sphere-approach mentioned by others above).;Thaumaturge said:This may be obvious, but in case it helps:Let me note that, as a first-person camera may be more likely than a third-person camera to draw very close to geometry, I'm not sure that's so true. I mean in both cases you have to take care of the problem somehow. The case of a first-person camera is a bit easier because it should always be in the collision boundary of the player (sphere(s), ellipsoid, capsule etc.). As along as the near plane is also within that boundary, the problem should never occur. So if you have a 10cm radius sphere and put the camera in the back of it, that gives you maybe a 10 to 15 cm camera to near clipping plane distance to play with depending on the field of view you are going for. With a 3rd person camera, you can also get very close to terrain, in fact your camera can end up within terrain or some object if you don't do anything to solve that problem, and this will happen very often without separate camera collision. One typical way to handle this is just implement your following camera, ignoring terrain considerations. Then to figure out your camera's actual position, project a line back from the head of the avatar to the camera's ostensible position, and see if it intersects anything to get the camera's true position. In reality you should project a cylinder and not a line since your camera will need its own bounding sphere to contain the near clipping plane. In any case this means that as you move around your camera can jump forward to clear terrain and objects. I've seen this in a few MMOs. However, when you leave blocking terrain you have the option of implementing smooth movement back to the cameras desired location. If you want to get really fancy, I guess you could try to predict when your camera will need to jump forward ahead of time and try to do smooth moment forward too. Maybe you can have a second camera bounding sphere which is somewhat larger, that would trigger smooth movement, but I think you would still need a fallback camera jump routine to be safe. |
Student & Teacher edition? | For Beginners | I have been looking in to buying certain software, and I noticed that some of them have a Student & Teacher version. Can someone tell me what the difference is other then the insanely lower price? | While I can't say without knowing what software you're talking about, I assume the software is the same but the license is restricted to non-commercial applications, for educational purposes only.Essentially they're giving free samples of their software to those who may one day need to use it professionally, to increase their brand awareness. ; Student versions are often equals to the non-student version but you have to be a student or teacher or institution to buy it (you usually have to send some document attesting it) ans you can't use the software for commercial applications. It is basically meant to be used to learn how the software work and they hope the student will become addicted to it so he will also use it when he will become a professional. ; That's great guys, that's what I wanted to know. I was looking at buying Photoshop CS5 Student version but I wanted to make sure it wasn't a chopped up version. |
Game Interface Design Gallery | Your Announcements;Community | Hi everyone, I wasn’t sure where to post this, so please correct me if I’m wrong. I’m just trying to get some feedback on this site that I’ve built, http://codeloadplay.com – Code Load Play is a collection of inspiring game interface design patterns, where users can mark patterns they like, and learn from others game design solutions.Please let me know if it’s useful. This site was built because I was looking for examples of game design patterns for my flash game framework Origami (http://gizmoko.ky/blog/). Thanks. | wow thanks this gives me a great idea on the layout I should go for for my UI ;) ; Thanks! I'm glad you've found it useful :) |
How to detect a DX10 GPU in DX9? | Graphics and GPU Programming;Programming | I'm using DX9's sRGB reads and writes in my game, for linear rendering. The problem is that DX10 GPUs do the right thing and convert the destination color from sRGB to linear before blending while older cards don't, even when running DX9 applications in XP. This causes alpha/additive/multiply blending to look different among DX10-capable and DX9-only cards. I can get around this by allowing artists to set an "DX9 adjustment color" RGBA value which is modulate2X'ed to the material's diffuse color in DX9-only cards. The problem is that I don't know how to tell a DX9-only GPU from a DX10+ one in DX9. Are there any caps values I can read that give them away? | The "D3DPMISCCAPS_POSTBLENDSRGBCONVERT" cap tells you whether it happens...unforunately it's only available for a 9Ex device so on XP you're stuck. ; I suspected as much. I'm looking at cardCaps.xls looking for some kind of pattern to tell SM3.0 and SM4.0 cards apart. So far, seems that all SM3.0 cards always have mismatching MaxVertexShader30InstructionSlots and MaxPixelShader30InstructionSlots values. There are two glaring exceptions, both from Intel: GMA 500 and G965. However, this is very strange, because I'm pretty sure reading somewhere that the chipset behind the GMA 500 is DX10-capable. And the Mobile 965 is DX10. I don't have any of these to test, but I'll assume they are part of the Intel line of DX10 GPUs that failed DX10 certification. Since users are likely to need to use the lowest settings as possible to play on them, I hope they wouldn't be much bothered by darker transparencies if these GPUs turn out to not do gamma-correct blending. ; Check D3DPMISCCAPS_MRTINDEPENDENTBITDEPTHS, D3D9 cards doen't support it, but D3D10 (and up) does. ;Quote:Original post by SergioJdelosCheck D3DPMISCCAPS_MRTINDEPENDENTBITDEPTHS, D3D9 cards doen't support it, but D3D10 (and up) does.Nope. Radeon X1000-series most definitely supports that.;Quote:Original post by MJPQuote:Original post by SergioJdelosCheck D3DPMISCCAPS_MRTINDEPENDENTBITDEPTHS, D3D9 cards doen't support it, but D3D10 (and up) does.Nope. Radeon X1000-series most definitely supports that.Nope, I checked it in CardCaps.xls, and seems only DX10 cards support it. But, again, there are two exceptions: Intel GMA500 and Intel G965, which are listed as SM3.0 cards. I'll just ignore those and assume they do DX10-style sRGB blending.Anyway, I'll go with D3DPMISCCAPS_MRTINDEPENDENTBITDEPTHS, which looks less hack-ish than comparing shader instruction counts. |
Vertex buffer not rendering? | Graphics and GPU Programming;Programming | Hi all, i've been working on a little project to teach myself the DirectX API and game programming techniques etc. But i've ran into something that i can't work out...#define CUSTOMFVF (D3DFVF_XYZRHW | D3DFVF_DIFFUSE)struct CUSTOMVERTEX{FLOAT x, y, z, rhw;DWORD color;};void CDXRender::InitVBuffer(){d3ddev->CreateVertexBuffer(3*sizeof(CUSTOMVERTEX),0,CUSTOMFVF, D3DPOOL_MANAGED,&v_buffer,NULL);}void CDXRender::LoadVertices(CUSTOMVERTEX vertices[]){VOID* pVoid;v_buffer->Lock(0, 0, (void**)&pVoid, 0);memcpy(pVoid, vertices, sizeof(vertices));v_buffer->Unlock();}void CDXRender::RenderVertices(){d3ddev->SetFVF(CUSTOMFVF);d3ddev->SetStreamSource(0, v_buffer, 0, sizeof(CUSTOMVERTEX));d3ddev->DrawPrimitive(D3DPT_TRIANGLELIST, 0, 1);}The "v_buffer" variable is stored in the class as protected -"LPDIRECT3DVERTEXBUFFER9 v_buffer;"and in my WinMain function...CDXRender* Renderer = new CDXRender;Renderer->Initialize(hWnd, 800, 600, TRUE);Renderer->InitVBuffer();CUSTOMVERTEX vert[] ={ { 400.0f, 62.5f, 0.5f, 1.0f, D3DCOLOR_XRGB(0, 0, 255), }, { 650.0f, 500.0f, 0.5f, 1.0f, D3DCOLOR_XRGB(0, 255, 0), }, { 150.0f, 500.0f, 0.5f, 1.0f, D3DCOLOR_XRGB(255, 0, 0), }, };Renderer->LoadVertices(vert);... Main Loop here Renderer->Start(); // Just clears the screen and begins the scene Renderer->RenderVertices(); Renderer->Stop(); // End's scene and presentsAll this code compiles with no errors or warnings, it starts up and is just blank, the background colour gets set by the d3ddev->Clear() function but the vertices don't get rendered? Any help? Thanks in advance (: | Just a quick look: it appears your vertices are in CCW order, not CW order. Also, be sure your eyepoint and viewport are setup such that you can see the triangle.Just in case, see what the Debug Runtime tells you. ; Turns out that if I put CUSTOMVERTEX vertices[] ={ { 3.0f, -3.0f, 0.0f, D3DCOLOR_XRGB(0, 0, 255), }, { 0.0f, 3.0f, 0.0f, D3DCOLOR_XRGB(0, 255, 0), }, { -3.0f, -3.0f, 0.0f, D3DCOLOR_XRGB(255, 0, 0), }, };in with my "CDXRender::LoadVertices()" function the vertices then get drawn... Must be how I was copying the vertices over :S ; as noted, your vertices were improperly wound, use SetRenderState(D3DRS_CULLMODE, D3DCULL_cw) OR specify your vertices in reverse order. ALSO, if until your sure which way they are wound, D3DCULL_NONE will ensure your verts show up no matter what. ; I have been using D3DCULL_NONE the whole time... and i have copied the code into a new project and took the whole thing out of a class and it works and it also works when i declare the vertices in actual class itself, the problem is that the array of vertices wasn't getting copied into the class variable for it to put into the buffer, i'm still having problems drawing something with custom set verticies... But i've created a void "DrawRect(FLOAT x, FLOAT y, int width, int height, DWORD Color);" function in my class and this works perfectly fine! ;Quote:void CDXRender::LoadVertices(CUSTOMVERTEX vertices[])//...memcpy(pVoid, vertices, sizeof(vertices));I'm guessing that may be the problem. In that context, vertices is a pointer and the size of a pointer is 4 bytes. You're only copying 4 bytes instead of 3 vertex structures.There's no way that LoadVertices(..) can tell how big the array is. You'll have to find a way to tell it. For testing purposes, you may want to try:memcpy(pVoid, vertices, 3*sizeof(CUSTOMVERTEX));and see if that works.; Aha, thanks buckeye! I never would of thought that, it now works and insted of loading an array of CUSTOMVERTEX's i'm adding one at a time and this works perfectly, thanks again! |
Pointer problem driving me mad? | For Beginners | I have a struct for a scrolling background. I'm calling a function to create and initialize a new background and store it in an std::vector called m_Slides. When i create one background, all is well. When i create a second one, i get a violation access error whenever i try to use the Texture variable of the first Slide which is an LPDIRECT3DTEXTURE.<EDIT>Further investigation showed that whenever i create a new Slide, the Texture values (ie: Width, Height) of the first one become gibberish</EDIT>Here's the code:The function calls:PushBackground("Grass.png", D3DXVECTOR2(1.0f, 0.0f), TILE_HOR);PushBackground("Trees.png", D3DXVECTOR2(1.0f, 0.0f), TILE_HOR);The struct:struct Slide{LPDIRECT3DTEXTURE9 Texture;std::vector<PreTransformedTextured> Vertices;D3DXVECTOR2 Velocity;unsigned char Tileable;Slide() : Texture(NULL), Tileable(0x00) {}~Slide() { SAFE_RELEASE(Texture); }};The function itself://=====================================================================================================// PushBackground(): Adds a new scrolling background in increasing distance from the camera.// The third parameter can be: TILE_VER and/or TILE_HOR or TILE_NONE where the// background is tiled either vertically, horizontolly or isn't tiled at all//=====================================================================================================bool CFramework::PushBackground(LPCSTR TextureName, const D3DXVECTOR2& Velocity, UCHAR Tileable){Slide* Temp = new Slide;HRESULT hResult = D3DXCreateTextureFromFileA(m_d3ddev, TextureName, &Temp->Texture);if (FAILED(hResult)){SHOW_ERROR(hResult)return false;}D3DSURFACE_DESC Desc;Temp->Texture->GetLevelDesc(0, &Desc);float ScreenWidth = (float)m_ScreenWidth;float ScreenHeight = (float)m_ScreenHeight;float QuadWidth = 0.0f;float QuadHeight = 0.0f;if (Tileable == TILE_NONE){QuadWidth = (float)Desc.Width;QuadHeight = (float)Desc.Height;}else if (Tileable == TILE_HOR){QuadWidth = ScreenWidth;QuadHeight = (float)Desc.Height;}else if (Tileable == TILE_VER){QuadWidth = (float)Desc.Width;QuadHeight = ScreenHeight;}else if (Tileable == (TILE_VER | TILE_HOR)){QuadWidth = ScreenWidth;QuadHeight = ScreenHeight;}elsereturn false;PreTransformedTextured* Verts = new PreTransformedTextured[6];float U = QuadWidth / Desc.Width;float V = QuadHeight / Desc.Height;// To position the Quad at the Bottom Left corner, not the top left.float yOffset = (ScreenHeight - QuadHeight > 0.0f) ? ScreenHeight - QuadHeight : 0.0f;QuadHeight += yOffset;static float zDepth = 0.0f;float rhw = 1.0f;// First TriangleVerts[0] = PreTransformedTextured(0.0f, yOffset, zDepth, rhw, 0.0f, 0.0f);Verts[1] = PreTransformedTextured(QuadWidth, yOffset, zDepth, rhw, U, 0.0f);Verts[2] = PreTransformedTextured(QuadWidth, QuadHeight, zDepth, rhw, U, V);// Second TriangleVerts[3] = PreTransformedTextured(QuadWidth, QuadHeight, zDepth, rhw, U, V);Verts[4] = PreTransformedTextured(0.0f, QuadHeight, zDepth, rhw, 0.0f, V);Verts[5] = PreTransformedTextured(0.0f, yOffset, zDepth, rhw, 0.0f, 0.0f);Temp->Vertices.insert(Temp->Vertices.begin(), Verts, &Verts[5] + 1);Temp->Tileable = Tileable;Temp->Velocity = Velocity;m_Slides.push_back(*Temp);--zDepth;Temp->Texture->AddRef();delete Temp;delete [] Verts;return true;} | There are two obvious things I can see wrong at the moment. The first one is 'minor', the second is what's causing your problem.1. You instantiate a new Slide called Temp - but if the D3D fails to load the texture, you return out of the function and don't deallocate this, this will lead to a memory leak.2. You are assinging the pointer to your object Temp to the std::vector. But then you delete the object Temp at the end of the function - this means that the pointer stored in the Vector will point to an object that no longer exists. ; Thanks for the first one but the second is wrong.. I'm placing the object pointed to by Temp in the vector. Temp is a pointer not an object. ; m_Slides.push_back(*Temp);That line adds the pointer to Temp into the Vector. ; No, that lines adds the value pointed to by Temp to m_Slidesm_Slides is defined as : std::vector<Slide> m_Slides; ; My apolgies - I read the * on the wrong side of the word Temp, however Temp is of type Slide* - so Temp points to a Slide object - the Slide object is instantiated at the top of the function - as soon as you exit the function - that object is no longer within scope. So either way - what goes onto the std::vector is garbage once the function exits. ; You need to review the Rule of Three for C++ classes. You define a constructor and destructor, but not a copy constructor.When the Slide structure is copied (which is done many times by your code), you don't transfer the data from the old structure to the new. In addition, during that copy, the old structure is deleted and you release the texture.I'd suggest you change your m_Slides vector to vector<Slide*>.If you want to see what's happening, add OutputDebugString(..) messages to the Slide constructor and destructor and step through your code.FYI: That is, when you push a Slide into m_Slides, the vector resizes. When it does that, it instantiates new members in new memory spaces, copies the old members to the new ones in the new memory space and deletes the old members. ; First off thanks for your help so far :)That's legal, otherwise creating one background won't work.I'm allocating memory for an object, placing that object in a vector then deleting the pointer to that object..If what you said was true, then this wouldn't compile, but it does:#include <iostream>#include <vector>using namespace std;void func(vector<int>& v){int* p = new int;*p = 5;v.push_back(*p);delete p;} int main(){vector<int> foo;func(foo);cout << foo[0] << endl;}; Buckeye, that makes sense.. *looks embarrassed*I'll fix the code :) ; No need to be embarassed. I'd be surprised to hear from any programmer that hasn't done that. |
Far developed 2D Arcade Platformer looking for a team. [Alpha playable demo included] | Old Archive;Archive | Project name: Blockade - working title.Brief description:Blockade is a 2D platformer arcade game with an innovative concept, it has been in developement by me for about 4 monthes during the summer/fall of last year,developement of it had ceased once the tests at school had begun again, and since then, I haven't really touched it much, what I had at that time is a working alpha version which I will provide a download link to, however, feedback on it had resulted in alot of bug fixes and the addition of an adventure mode, that is a sort of a platformer game, since the release of this version.The version we will start the work off is a rather complete version of the game that just needs edge sharpening, tweaking and improving off of given materials, at the time I have made everything for the game, concept music, pixel art, code and plan, which just need to be worked upon.Target aim:Well, wish I could say for sure, but at the current state of the project it could only go as freeware, hence why I'm recruiting, I want the recontinued game to be good enough to go for a small fee of 1-5$ per copy, or peraphs a conversion to flash for it to be sold to a flash game site.Compensation:Revenue will be split between the team members if any will be gained.I wouldn't want to look at that aspect right now though, just focus on a game for our portfolios with an option for growth from there.Technology:PC, using C++ and SDL, may be converted if the team so wishes to.Artist and sound tools are up to the individuals to decide upon.Talent needed:Graphic artists: for backgrounds, menus and overall graphics that aren't pixel-levelled.Pixel artists: for the pixel art for the game, since it is 2D, that would be alot of art, but the base of it is already given in the alpha and just needs to be improved upon.Sound artists/composers: for the sfx and music in the game, again, a base is given, but needs to be improved upon.Programmers: possibly network programmers too if we decide to expand in that direction. The code is mainly done, so the work of the programmer is not needed right away, but people that still want to offer themselves will not be denied on the spot either and will be heard out, after all, this is mainly a portfolio project, and I wouldn't want to deny anyone capable of helping on it from gaining the experience.Level designers: for the adventure mode that is unpresent in the alpha, level designers would be needed to design challenging levels using the given concept of the game.All applicants should send in their resumes and portfolios.Team structure:Me: Mor Zilberman - creator of the project, been working on it for 4 monthes and provided the temporary art and sound as well as all of the coding and concept.Contacts:Mor: -email/MSN: [email protected]: KazenoZAdditional Info:The readme that has been attached to the alpha demo at the time of making:Quote:Welcome to the Blockade Explanation file.Blockade is a 2D game developed in C++/SDL, it is an addicting arcade game in which your goal is to jump your way up the screen using a bunch of random blocks that appear on thescreen, sounds simple? Why, of course there's a catch.The real challenge behind this game is not jumping upon the blocks, it's navigating betweenthem while they will no doubt try to shake you off.There are 9 types of blocks, each with a different function that will activate upon jumpingit.The game may be simple to learn, but you will soon find it challenging, for that, some very challenging modes of gameplay for you to pick up on can be found within the game, as well asthe top rank of difficulty, the Expert rank.Other than just jumping the blocks, the game features 4 different modes of play for all levels of experience, interesting for the weaks through to challenging to the pros, you willneed to really know what you are doing to complete the challenges set for you here.Learning the art of the craft might be simple, but do you think you have what it takes to master the Blockade? Think you can make it to the top and conquer the Gate? Prove yourself, pass the Blockade!------Types of blocks:The green block moves left;The blue block moves right;The yellow block will fall beneath you, dragging you with it;The teal block would act as a trampoline to give you a boost;The red block is a bomb that will send you flying;The pink block shrinks under your feet.The purple block vanishes as you approach.The gray block... is just there, does nothing.And last but not least, the wacky block, a box that randomly transforms to any other block.As well as the Gate block, your target.------Ranks:Beginner - The beginner mode focuses on letting the player get aqcuainted with the game mechanics more than anything else, the only blocks you will encounter here are friendly blocks that will help you reach the top.Easy - The easy mode is there to demonstrate to you the works of the wacky box.Intermediate - If you're familiar with the game mechanics and know what you are doing, thisis your next step, some hindering blocks make their appearance this time around.Advanced - This mode is for the top notch players, all blocks are here, aids as well as traps, here you will firstly face the last 2 blocks, the worst of the bunch.Expert - Already tired of the Advanced rank? Got the hang of it good and can conquer it easily? Fear nor, the Expert rank is here just for you. The ultimate challenge, not onlydo all blocks still make an appearance, this mode also adds a gist of strategy and memoryusage to the mix. What's so special you ask? Why, the blocks are mixed!The function of each block has been transferred around, and your goal is to quickly learnthe new allocations and find your way to the top once more.------Game modes:Free Mode - Just choose a rank of difficulty and start playing for practice.Time Mode - Time your games and try to break your own record times for finishing a stage.Score Mode - Coins are randomly spread out throughout the screen and you need to get as manyas you can within the time limit.Challenge Mode - The most challenging mode of gameplay in the game, you will be given various tasks in varying difficulties to try and test your skill.Just like the other modes, this one is split into difficulty ranks, however, it's a bit different this time around, only 4 ranks, with the last one being for only the best of thebest of players.All challenges are played off with the full block roster, so you need to be atleast at alevel to play those if you want a chance against them.Challenge Mode ranks:Easy - A few simple challenges for the new players to experience the air of the challengemode.Normal - Rather simple challenges, do require lots of practice however.Hard - Tough challenges, you WILL need alot of tries if you want a chance at these, no matterhow experienced might you be.IMPOSSIBLE! - Pretty much self explationary, you will need to have the mind of a robot andthe reflexes of a trained ninja if you want a chance to pass these, the challenges are thesame as the Hard rank, however, you play on the Expert rank with all blocks being twisterover. Good luck with that one, you WILL need it.Link to download alpha:http://www.megaupload.com/?d=IRIMU5ULFeedback:Any feedback would be much appreciated, as this game is only looking to improve from here, however, be aware that some of the feedback you would have regarding the playable demo have already been taken into account and implemented. | screenshots please ; Well, it is all just placeholder art AND an arcade, there is not much to show actually, but this is a picture of the block function explanation from within the game. |
SSE4 advantage against SS2 in matrix muliply | Math and Physics;Programming | hiwhat is SSE4 (or SSE3) advantage against SSE2 in matrix and vector multiply?and can u put here any code for SSE4 matrix multiplication? | SSE4 adds dot products |
deque point at a pointer? | For Beginners | struct Smystruct{int x;int y;int value;}deque <Smystruct*> mystruct1;deque <Smystruct*> mystruct2;if i push_back about 10 items onto mystruct1. So mystruct has a size of 10if i did:mystruct2 = mystruct1;this will copy every thing into mystruct2;but how do i make it so mystruct2 just points to mystruct1, so it does not go through the long process of copying itis it:*mystruct2 = *mystruct1; | First you need to make mystruct2 a pointer, and then take the address of mystruct1 to get a pointer to it that you can assign.deque <Smystruct*> mystruct1;deque <Smystruct*> *mystruct2;...mystruct2 = &mystruct1 |
Seperating Axis Theorem - How to Resolve Contact Points | Math and Physics;Programming | Hi, my narrow-phase-algorithm for collision detection, uses the Seperating Axis Theorem (SAT) to find the minimum penetration direction & depth.If I know which of the axis is the one with minimum overlap, how do I know what kind of collision this is? (point-face, edge-edge, edge-face, face-point, face-edge, face-face). For each the possibilities, How do I calculate the contact point(s) of a collision?Also, is SAT usually done by converting one object to the others local space, or by converting both to world space?Thanks in advance! | The separating axis that realizes the axis of minimum penetration is either a face normal or the cross product between two edges. In the first case let's call this face the "Reference Face". Now you find the most parallel face on the other shape which we call the "Incident Face". To find the contact points you clip the incident face against the side planes of the reference face and keep all points below the reference face plane. In the case where the separating axis is the cross product between two edge directions you can keep the closest points of on the edges. Note that several edge cross products can realize thhe same axis of minimum penetration. You have to make sure that the edges are actually the "Support Edges" (similar to the concept of a support point) in the direction of your separating axis. This means geometrically that the edges are actually "close" to each other. Or from a Minkowski viewpoint this means that the edges actually build a face on the Minkowski sum. You can look at ODE dBoxBox for an example. ;Quote:Original post by DonDickieDThe separating axis that realizes the axis of minimum penetration is either a face normal or the cross product between two edges. In the first case let's call this face the "Reference Face". Now you find the most parallel face on the other shape which we call the "Incident Face". To find the contact points you clip the incident face against the side planes of the reference face and keep all points below the reference face plane.In the case where the separating axis is the cross product between two edge directions you can keep the closest points of on the edges. Note that several edge cross products can realize thhe same axis of minimum penetration. You have to make sure that the edges are actually the "Support Edges" (similar to the concept of a support point) in the direction of your separating axis. This means geometrically that the edges are actually "close" to each other. Or from a Minkowski viewpoint this means that the edges actually build a face on the Minkowski sum. You can look at ODE dBoxBox for an example.DonDickieD, thanks so much for the help.I am attempting to implement 3D collision detection using Oriented Bounding Boxes (OBB), deriving a contact manifold using the SAT. If I understand, it involves identifying the "features" of the two objects (boxes in this case) that project minimally, onto the axis that is determined to be the axis that is parallel to the minimum translational vector (MTD). Once I've identified these features, I can clip them against one another to yield the contact manifold.Now, what SAT will give me, will be the normal of the collision and the depth of intersection, both combined can they compute the minimum translation distance (MTD), how?I think the support points/edges are basically the points on the objects that provide a stable base along the normal of collision. So, instead of talking about support points, is it better to consider them as supporting "feature"? If I understand, in my case these features can be either, a point, an edge and a polygon.How can the normal of collision be used to find the features on the two surface? If I consider two boxes (box A sitting on box B), one sitting on top of the other, you will get 4 support points a piece (one polygon each). The bottom face of box A, and the top face of box B. To find the contact points, will I need MTD to 'clip' one polygon against another, how?Also, how can I know that the feature are actually the "Support feature" in the direction of my separating axis, when several edge cross products can realize the same axis of minimum penetration?Can I combine SAT and GJK, with the latter only used to find the contact points?In addition, but no less important, I will test my intersection algorithm using boxes of various dimensions and orientations intersecting in various configurations, but for the collision response, I have to apply an impulse always to the box A. So, I make sure that the penetration direction and length refer always in the right way, relatively to the box A (outward box B)... But I'm still confused about it.I would appreciate any assistance, Thank you! ; These are very general questions. Please read Erin Catto's 2007 GDC presentation on contact manifolds which you can download here: http://code.google.com/p/box2d/downloads/list. It is the second PPT. Also Download the 2009 GDC presentation and look at the Box2D Lite implementation. Then extend this to 3D and add the edge cases yourself - maybe looking into dBoxBox from the ODE.The idea to extend to a support feature is correct. You can indeed have a support point, edge or face. Identifying support edges is crucial for general convex collision using SAT. As it turns out the associated arcs on the Gauss-Map must intersect. This is maybe non-trivial to understand so let me quickly try to give you the basic idea. Basically an edge has two adjacent faces. These faces have normals which you can interpret as points on a unit sphere. This is called the Gauss-Map. Now you test whether the two arcs intersect. If and only if these arcs intersect the edges are support edges and can actually realize a contact. I am editor of a book called "Game Physic Pearls" which has a nice article about Gauss-Maps. For clipping you basically clip a polygon against several planes. Christer Ericson's "Real-Time Collision Detection" has some nice code and article how to do this.If you want to write your own physic engine I absolutely recommend looking into Box2D lite and port it through 3D making sure you understand every detail. The basic engine can have a brute force broadphase and should support spheres, capsules and boxes as shapes. A simple spherical joint is sufficient initially. Finally implement an impulse solver. From there you can dive into all other topics you want, but now having some idea how things work.HTH,-Dirk |
ray-to-triangle problem | Math and Physics;Programming | HiI have a function to check if a ray from camera to mouse coordinates in 3D hits a triangle but it seems to be working somehow wrong..Could someone check the function if there's something wrong?p is the ray start pointd is the ray end pointv0, v1 and v2 are the triangle's vertices' coordinatesint RayIntersectsTriangle(float *p, float *d, float *v0, float *v1, float *v2){float e1[3],e2[3],h[3],s[3],q[3];float a,f,u,v,t;e1[0] = v1[0] - v0[0];e1[1] = v1[1] - v0[1];e1[2] = v1[2] - v0[2];e2[0] = v2[0] - v0[0];e2[1] = v2[1] - v0[1];e2[2] = v2[2] - v0[2];h[0] = (d[1] * e2[2]) - (e2[1] * d[2]);h[1] = (d[2] * e2[0]) - (e2[2] * d[0]);h[2] = (d[0] * e2[1]) - (e2[0] * d[1]);a = (e1[0] * h[0]) + (e1[1] * h[1]) + (e1[2] * h[2]);if (a > -0.00001 && a < 0.00001)return(false);f = 1/a;s[0] = p[0] - v0[0];s[1] = p[1] - v0[1];s[2] = p[2] - v0[2];u = f * ((s[0] * h[0]) + (s[1] * h[1]) + (s[2] * h[2]));if (u < 0.0 || u > 1.0)return(false);q[0] = s[1] * e1[2] - e1[1] * s[2];q[1] = s[2] * e1[0] - e1[2] * s[0];q[2] = s[0] * e1[1] - e1[0] * s[1];v = f * ((d[0] * q[0]) + (d[1] * q[1]) + (d[2] * q[2]));if (v < 0.0 || u + v > 1.0)return(false);t = f * ((e2[0] * q[0]) + (e2[1] * q[1]) + (e2[2] * q[2]));if(t > 0.00001)return(true);elsereturn(false);}I've noticed, when the ray's starting point is at (0,0,0) everything works fine, but when I move the start point the triangle's hit area seems to be moving in the opposite direction or that's what I think..In this screenshot, camera is at x = 0, z = 0 and y = 10. The triangle hit area is marked on red and the real triangle is the white one.http://img98.imageshack.us/img98/4509/asddbb.pngEDIT: I'm using C++ with SDL and openGL | Nevermind. Function had no problems, seems like my gluUnProject was in the wrong place, so it didn't give me the real 3D mouse coordinates |
fast matrix multiplication | Math and Physics;Programming | hiI'm wrote my matrix classes with SSE2 and test it against D3DX10 matrix as result DirectX matrix class is 2 and in some case 3 time faster than my own matrix class what can i do to reach this speed?my code is:// mul , Matrix * Matrixvoid Matrix::mul(Matrix &result,const Matrix& m1,const Matrix& m2){#if DGE_USE_ASM_MSVC && DGE_USE_SSE2const FLOAT* m1f = m1.elements;const FLOAT* m2f = m2.elements;FLOAT* rf = result.elements;// put transposed of m2 in xmm4-xmm7__asm{movebx, m2fmovapsxmm4, [ebx]movapsxmm5, [ebx+0x10]movapsxmm6, [ebx+0x20]movapsxmm7, [ebx+0x30]movesi, m1fmovedi, rfmovecx, 2// process two vectorsBM5_START:// process xmovssxmm1, [esi+0x00]movssxmm3, [esi+0x10]shufpsxmm1, xmm1, 0x00prefetchnta[esi+0x30]shufpsxmm3, xmm3, 0x00mulpsxmm1, xmm4prefetchnta [edi+0x30]mulpsxmm3, xmm4// process ymovssxmm0, [esi+0x04]movssxmm2, [esi+0x14]shufpsxmm0, xmm0, 0x00shufpsxmm2, xmm2, 0x00mulpsxmm0, xmm5mulpsxmm2, xmm5addpsxmm1, xmm0addpsxmm3, xmm2// process zmovssxmm0, [esi+0x08]movssxmm2, [esi+0x18]shufpsxmm0, xmm0, 0x00shufpsxmm2, xmm2, 0x00mulpsxmm0, xmm6mulpsxmm2, xmm6addpsxmm1, xmm0addpsxmm3, xmm2// process w (hiding some pointer increments between the// multiplies)movssxmm0, [esi+0x0C]movssxmm2, [esi+0x1C]shufpsxmm0, xmm0, 0x00shufpsxmm2, xmm2, 0x00mulpsxmm0, xmm7addesi, 0x20mulpsxmm2, xmm7addedi, 0x20addpsxmm1, xmm0addpsxmm3, xmm2// write output vectors to memory, and loopmovaps[edi-0x20], xmm1movaps[edi-0x10], xmm3dececxjnzBM5_START}#elseresult.set(m1.m11*m2.m11 + m1.m12*m2.m21 + m1.m13*m2.m31 + m1.m14*m2.m41,m1.m11*m2.m12 + m1.m12*m2.m22 + m1.m13*m2.m32 + m1.m14*m2.m42,m1.m11*m2.m13 + m1.m12*m2.m23 + m1.m13*m2.m33 + m1.m14*m2.m43,m1.m11*m2.m14 + m1.m12*m2.m24 + m1.m13*m2.m34 + m1.m14*m2.m44,m1.m21*m2.m11 + m1.m22*m2.m21 + m1.m23*m2.m31 + m1.m24*m2.m41,m1.m21*m2.m12 + m1.m22*m2.m22 + m1.m23*m2.m32 + m1.m24*m2.m42,m1.m21*m2.m13 + m1.m22*m2.m23 + m1.m23*m2.m33 + m1.m24*m2.m43,m1.m21*m2.m14 + m1.m22*m2.m24 + m1.m23*m2.m34 + m1.m24*m2.m44,m1.m31*m2.m11 + m1.m32*m2.m21 + m1.m33*m2.m31 + m1.m34*m2.m41,m1.m31*m2.m12 + m1.m32*m2.m22 + m1.m33*m2.m32 + m1.m34*m2.m42,m1.m31*m2.m13 + m1.m32*m2.m23 + m1.m33*m2.m33 + m1.m34*m2.m43,m1.m31*m2.m14 + m1.m32*m2.m24 + m1.m33*m2.m34 + m1.m34*m2.m44,m1.m41*m2.m11 + m1.m42*m2.m21 + m1.m43*m2.m31 + m1.m44*m2.m41,m1.m41*m2.m12 + m1.m42*m2.m22 + m1.m43*m2.m32 + m1.m44*m2.m42,m1.m41*m2.m13 + m1.m42*m2.m23 + m1.m43*m2.m33 + m1.m44*m2.m43,m1.m41*m2.m14 + m1.m42*m2.m24 + m1.m43*m2.m34 + m1.m44*m2.m44);#endif} | You can look at the D3DX implementation yourself. The short answer is use intrinsics. For a longer discussion look here: http://www.gamasutra.com/view/feature/4248/designing_fast_crossplatform_simd_.php |
Is it just me? | GDNet Lounge;Community | Is it just me or do you as well notice that young teenagers who have a passion for designing video games actually have some good ideas. I mean I have talk with some youngster's who are deffinitely interested in the field and they are very bright when it comes to design concepts. I rather they keep it to themselves, but I can deffinitely see a future of gaming in where games will have come along way in becoming the way they are now. Even college students and people in the gaming industry already starting to make a change and shift througout gaming history. Don't you agree? | I do agree. Young teens are one of the biggest customer bases for game companies. They know what's "cool" and what's not. They play the games out there, and they have good ideas about what they like and what they want to see.Yes, many of them have a great passion for game development/design. But I notice a trend with most (but NOT all) teens. They think designing a game is just getting some tools, clicking some buttons and shipping the next world-beating MMO. :) You'll often see questions like "What program do I need to make a game?"... not realizing that sure, there are design tools (like world editors), but one needs A) a programmer B) to be a programmer oneself. "Click-together" games are nothing more than a living room novelty; rarely something anyone will even want to play for 5 minutes. I can't think of a single popular/successful game made without SOMEONE writing some code. :) That can be discouraging when you're interested in learning to develop games. "Damn, I have to write this computer code mumbo-jumbo?! WTF!!?", haha. And really, this isn't just teens. Plenty of adults have the same mis-perception, and think game development is just about learning how to use some magical program which does all the work for you. I thought, when I first became interested in trying out development, "...surely technology today has made programming/writing code a rare necessity.", and how WRONG I was!My 2 cents. ;Quote:good ideas.Good by what criteria?Quote:starting to make a change and shift througout gaming history.Any examples?Quote:one of the biggest customer basesDisposable income, non-demanding life-style.Quote:about what they like and what they want to seeAka, fashion industry. Ideas have absurdly short life-span and rely on global machinery to profit from the fads before they fade. ; I totally agree. Young teens have the greatest ideas because there minds are so open. I also agree with keinmann. When I first realized that I wanted to get into the gaming industry I though it would be some kind of program that did it all for you haha. Coming to realize that it is not like that in any way, I sure am glad I stuck with it even after figuring out theres so much more into it!; I agree with Antheus' scepticism. I'm not a historian, but AFAIK all the big hits, pioneer and industry-changer games were made by people of age >23 not by teenagers. ; The problems with these kinds of ideas though, is that without any development experience, you're unable to properly flesh out the idea. It's only when you actually flesh it out that you discover the flaws in it, and refine it into a "good" idea. ;Quote:Original post by HodgmanThe problems with these kinds of ideas though, is that without any development experience, you're unable to properly flesh out the idea. It's only when you actually flesh it out that you discover the flaws in it, and refine it into a "good" idea.True. Once I had (few months ago) a pretty good idea about a puzzle game. Simple like minesweeper and that made it good. I even named it "domains". I made the game (at least the gameplay prototype), and it was just boring (luckily it took only a day to code it). ; I don't thing that teenagers have a brilliant ideas.The true brilliant idea as usualn have a huge abilities for development inside and firstly common sence.The most powerful stage of human's reason progress is laying between 25 and 35.This is my imho and my 2 coins................."Our life after 35 years old is a competition between neuron dedradation in brain and growing life experience" (c)Stanislav Lem;Quote:Original post by KrokhinI don't thing that teenagers have a brilliant ideas.They do, especially when it comes to upcoming technologies or trends.But that does not make them viable or commercially interesting. They are, as all ideas, either common sense, just not known within their world, different take on existing idea or a catchy absurdity which others just like (like memes).But ideas are also subject to luck. Even in hard science - a good idea needs to come at right time in right place among right people.There was an article a while back on how Google generates "luck". It's all about taking care of the knowns to allow unknowns to succeed. This is also what business incubators do. Which idea will succeed is not known since it depends on adoption and gaining traction. What can be done is building an environment that is encouraging and fostering to those that would want to try.Majority will still fail, but maybe a handful will gain just enough help to make it through.Simple harsh reality today is that without monetary backing an idea will not succeed. This does not need to be in form of cash, altruistic efforts and benefactors as well as social acceptance all play big role - money is just prerequisite for those to succeed.It has always been so. Galileo didn't invent all that much, he simply refined existing ideas due to having benevolent benefactors that others did not. ; if teenagers were so keen on new and innovative ideas then COD: Black Ops wouldnt have broken the sales records.NO. Teenages want explosions and guns. Alot of adults are also of this mindset.It takes a keen interest, research and refinement to come close to anything "good". |
linux asm, interrupt kernel with exit, or simply ret? | General and Gameplay Programming;Programming | Both seem to work just the same, but which is 'correct'?on exit of program, either:mov eax, exitcoderetormov eax, 1mov ebx, exitcodeint 0x80 | The C runtime contains a _start() entrypoint which basically does "exit(main())" anyway.Either way is reasonable. The first is returning from main(), the second is (effectively) what you get if you call exit(). They're both acceptable ways of terminating the program.It's probably nicer to actually call exit() rather than invoke the interrupt yourself though. Why? Because on modern CPUs, calling an interrupt can be quite slow -- especially if the machine is virtualised where it requires a switch into the hypervisor to handle the int initially (the HV sits in ring0 and displaces the OS, unless this is a hardware HV 64b machine in which case it gets even more fiddly). Then there's a transfer back to the VM supervisor mode and only then can it do the work.So these days there are fast transition instructions which switch to the OS rather than to the hypervisor, and which execute faster than interrupts (even on non-virtualised systems). Of course, there are two sets of these (AMD's & Intel's) so there's some boot-time choices to set up. The plumbing to do all that is hidden inside the system calls, so apps don't need to worry about it.; You really shouldn't call int 0x80 directly in Linux. The kernel can be subject to change so what works now, may not work later on. ;Quote:Original post by Chris_FYou really shouldn't call int 0x80 directly in Linux. The kernel can be subject to change so what works now, may not work later on.Realistically, this will not change. The conventions of the unix system calls predate Linux, I don't think there has been significant change there for some time. |
Bases to practice on | For Beginners | Hi Everyone, I'm new to the site.I have taken an interest in gameplay development as a hobby which i will be working on through reading all the information i can find on the subject etc as well as beginning my courses starting with c# in January.I've dabbled with programmes years and years ago but wondering if there are any recommended programes out now where i can put what i am learning to use, i.e. bases to work on codes etc.Any advice on where to start and where to put my learnings to practice would be really helpful :)x | |
Asynchronous Asset Loading (data streaming) | General and Gameplay Programming;Programming | Say I have two threads in my game, the main thread and an asset loader thread. For now, my system consists of the following:1. a manager class that allows you to Get() assets by name2. an actor class that references assets like textures and meshes by name3. when an actor needs to render a mesh, it calls Get() on the manager. The manager checks within a <string,asset pointer> map to see if it has the asset. If it returns non-null, it uses this mesh. Else, it uses a default pre-loaded mesh and the manager kicks off an asset loading task on the loader thread.4. same as #3 for textures when a mesh needs them.5. When an asset loading task is done, the manager adds the asset to its <string,asset pointer> map. This means that the map has a mutex or critical section that is locked whenever the user calls Get() and also whenever the loader thread is done.I think locking a mutex every time Get() is called is not a good idea. I'm trying to think of alternate ways to solve this. Can anybody help?One thing I can think of is to reference assets by pointer instead of by name. If an actor has a non-null pointer, it uses it. And the loader thread, when done, sets the pointer. This still requires a mutex though, for the actor's asset pointer.One other thing is to keep some sort of state on the actor that indicates whether or not it has the asset. If it's loading, then it'll keep calling Get() on the manager. When it gets a valid pointer, it'll cache it, and stop calling Get(). The pointer would have to be a shared_ptr or weak_ptr because multiple actors could use the same assets.Can someone please give me pointers on how to implement a good asynchronous loader? Also, would the implementation change if I had another thread that processes the loaded data (decompress/create object(s) from data)?Thanks in advance. | Quote:Original post by gsamourI think locking a mutex every time Get() is called is not a good idea. I'm trying to think of alternate ways to solve this. Can anybody help?"Think" is a poor metric for making a choice in software development. Prove it with data or a use case rather than 'think'.In reality the lock/unlock of a mutex is the safest and simplest method of doing this and should be the first method taken (and other methods can cause all manner of headaches you simple don't need).As for writing a good async loader; worry about getting it done with two threads first, as scaling up from there is a deep hole of async IO, IO completion ports, async procedure call, thread states and all manner of fun things which require a decent grounding in threaded coding to do 'right'.(I do intent on making a journal entry on this subject, in the context of a task based game system, at some point in the future, but as we are now about to hit 'beta crunch' at work it'll probably be a couple of weeks off now).; You're right, "think" is a lousy metric. I recently downloaded a trial of Intel's VTune. I'm still trying to understand the results it gives me, but here's what I've got so far:VTune shows a list of "hotspots" which seem to be the functions that get the most cpu time. My manager's Get() is listed as a hotspot, which is why I think it's a bad idea to call it so much (especially when my program "knows" that the resource is already in memory). ; If you allow the Actor to 'own' the mesh then you will avoid calling Get() so much. If your actor normally uses the same mesh each time then you could rewrite it so when the Actor requests a Mesh it gets an AssetHandle back. When it comes to render time it could do something like this:if(handle.isLoaded()) return handle.Asset();else return ActorDefaultMesh();AssetHandle::isLoaded() could examine a flag and if you're super careful with memory barriers etc, then you can use atomic operations to read and set the value of that flag from different threads. Bear in mind you are opening yourself up to all kinds of horrendous bugs when you start messing with this stuff.It would be so much easier if you ensured all assets are loaded during some kind of loading screen! ;Quote:Original post by gsamourYou're right, "think" is a lousy metric. I recently downloaded a trial of Intel's VTune. I'm still trying to understand the results it gives me, but here's what I've got so far:VTune shows a list of "hotspots" which seem to be the functions that get the most cpu time. My manager's Get() is listed as a hotspot, which is why I think it's a bad idea to call it so much (especially when my program "knows" that the resource is already in memory).That might be but how much other work is your program doing? If its doing a trival amount of work and hitting the code alot then yes, it will show up as a hotspot, however when it is doing a realistic work load that might well not be the case. ; Thanks Noggs & phantom for your replies so far :)@ Noggs:I'd like to have streaming, and I found your comment about flags and memory barriers interesting. Could you please go into more detail? Or do you have a link to an article or tutorial?@ phantom:I'll see if I can post more information, like the VTune output. My program has hitches every now and then, and I'm trying to track them down. From the responses and my previous knowledge, I'm starting to doubt that mutexes in general are my problem.---One of the asset types I'm streaming are textures, and when a texture is loaded, my processing thread calls D3DXCreateTextureFromFileInMemoryEx(). The direct3d device can't be accessed from multiple threads, which means I use a mutex for the device. This means my main thread blocks. If this function takes a long time, this would explain the hitches.EDIT: I double checked my code as I was not sure about the "D3DXCreateTextureFromFileInMemoryEx" part (I wrote that section a while ago). I'm not using D3DXCreateTextureFromFileInMemoryEx anymore. I'm just using D3DXCreateTexture() to create an empty texture, then using LockRect() and Unlock() to fill it. Is there a faster way to do it? ; If you are locking/unlocking the mutex you use to check if something is loaded then you are unlikely to see 'hitches' every now and then, it would be a pretty stable impact on your update rate.That said, now that I'm more awake, it occurs to me that you technically shouldn't need a mutex; mutexs are good when you are going to have multiple threads writing to a resource and thus you need to prevent out of ordered updates and other data hazards. However, you only have a single thread writing and a single thread reading as such this doesn't matter too much. Worse case while you reading the var in the 'get' function it gets updated in the 'loading' thread and you don't see it for an extra frame.The only time you need to setup a mutex is if you are going to modify the map in the 'get' function. ; I'm fairly certain a std::map is in no way thread safe, which means that if you have one thread adding to it while another is reading from it you may get a crash or other unexpected behaviour. For example consider what might happen if one thread is rebalancing the tree, while the other is trying to use it. Two threads reading the same std::map should be safe, although I don't think there's any guarantees in the standard.My guess for what's causing the hitching would be that you're creating lots of textures in one frame. Try spreading the work out over multiple frames.Smaller textures can also be loaded and created more quickly, so consider storing textures using D3DFMT_DXT1 or D3DFMT_DXT5 where appropriate. ; Do some research on InterlockedCompareExchange(). Memory barriers are used to ensure that memory writes that you would expect to have occurred when you call the function have definitely occurred - but it looks like the MS Interlocked functions implicitly have memory barriers built in.Basically:Thread A requests asset X. This creates an Asset entry with mState=LoadPending. Load Thread picks up the load request and use CompareExchange to set the state to LoadingLoad Thread finishes loading the asset and uses CompareExchange to set the state to LoadedAt any time any thread can query the mState and should only use it if the state becomes Loaded (that's what the isLoaded() function would do).The reason CompareExchange must be used will become apparent when you come to handle unloading (imagine the case where Thread A decides to unload when the state is Loading). This is where things start to get complicated!The key is to manage the state transitions very carefully and to always be aware of which thread has control of the asset in which state.Not that I'm trying to discourage you but lock-free async loading can be a big time sink while you try and iron out all the niggly little edge cases. I would suggest sticking with the mutex version until you're sure that it needs optimising. ;Quote:Original post by Adam_42I'm fairly certain a std::map is in no way thread safe, which means that if you have one thread adding to it while another is reading from it you may get a crash or other unexpected behaviour. For example consider what might happen if one thread is rebalancing the tree, while the other is trying to use it.Hmmm, you make a good point I hadn't considered at the time of my posting... That said, inserting/deleting doesn't seem to invalidate iterators into the container, which seems to imply that things shouldn't go wonky if you were reading while something was adding; but I wouldn't swear to that without seeing the code for it of course [smile]Edit;Truth be told I wouldn't touch the map for this anyways.A simple solution would be;- On requesting the data I would pass back a handle which has a bool you can query for 'ready'ness.- Renderer/main thread queries this value when it goes to use it- Loader set to 'true' when the data is readyAnother option is a callback to an object to let it know that 'data X is ready', which maps to the handle you obtained earlier. |
C++ and Python compile errors | General and Gameplay Programming;Programming | Hi,I am trying to use Python from inside a C++ program.At the time I am trying to use tutorials:http://docs.python.org/extending/embedding.htmlAs I am trying to build the simpiliest tutorial:#include <Python.h>intmain(int argc, char *argv[]){ Py_Initialize(); PyRun_SimpleString("from time import time,ctime\n" "print 'Today is',ctime(time())\n"); Py_Finalize(); return 0;}I get like thousands of errors (similar to those below):1>C:\Program Files (x86)\Microsoft Visual Studio 10.0\VC\include\math.h(162): error C2373: '_hypot' : redefinition; different type modifiers1>C:\Program Files (x86)\Microsoft Visual Studio 10.0\VC\include\math.h(138) : see declaration of '_hypot'C:\Program Files (x86)\Microsoft Visual Studio 10.0\VC\include\math.h(162): error C2491: '_hypot' : definition of dllimport function not allowedI am using VC++ EE 2010, and Python 2.6. I have included (only) Python folder with include files *.h.What am I doing wrong? Should I include something else? | This doesn't look right. You have 2 separate string arguments in PyRun_SimpleString with no comma separating them. Also, it looks like PyRun_SimpleString only accepts one argument anyway. This should either be 2 separate calls or concatenated into a single stringPyRun_SimpleString("from time import time,ctime\n""print 'Today is',ctime(time())\n");-me ; Two adjacentent string literals are concatenated at compile time automatically. Arguably, it is a misfeature as it makes it really easy to mess up a string array:const char *array[] = { "Monday", "Tuesday", "Wednesday" // Whoops! "Thursday", "Friday", // ...};As for the actual problem, have you looking into Python.h to see if it has any declarations that might interfere with _hypot? Searching your include path for this might yield results... ; Well, thanks for Your answers, but...just including python.h causes same errors so I don't think that's the reason.I can't even include python.h without getting an error (or bunch of them)It happens only when I make a windows form application. In case of console app. it works.[Edited by - Misery on November 19, 2010 5:10:19 AM] |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.