mapbox unity3d sdk openstreetmap mesh generation

New job, new project, new horizons

I know it has been a while since the last update on MapzenGo, sorry about that. I had lots of stuff going on and couldn’t find time to blog in that rush. Well actually title says it all right? MapzenGo project landed me a new awesome job at Mapbox and now I’ll be doing pretty much the same thing, map/city generation in Unity for them! OK maybe not New Horizons cool but it’s still pretty fucking cool, eh?

Mapbox is a huge custom map provider and they’ve been one of the top player in the scene for years. They have some awesome terrain (height), vector, satellite imagery APIs and most of their project are open source and hosted on Github! Now they (well it’s “we” now I guess) are going into gaming scene and started this Mapbox SDK for Unity3D project a short while ago. Aaannnd before you ask, yes, this SDK will be open source after the launch as well!

So that’s pretty much the whole story I guess, let’s try this for the rest;

-What will you be doing there?
I’ll mostly do the mesh generation and unity integration, so same as MapzenGO.

-What will happen to MapzenGo?
It really isn’t an easy job building worlds from scratch, there’s millions of thing to do. I can’t do it all for two project at the same time so I’ll switch MapzenGo to maintanence mode. I’ll keep fixing bugs and answering everything as much as I can but I won’t add new features and stuff anymore. It’ll be like an “Introduction to GeoJson mesh generation in Unity3D”. Again Mapbox will be open source anyway so you won’t miss out on anything!

-And blog posts?
I probably won’t have much time for detailed technical posts, at least until the release. I’ll post images, videos or anything though. I’ll keep this blog alive and try to write technical stuff as much as I can. Meanwhile you can follow me on Twitter for updates and mail me for anything. You may already know that I love talking, so don’t hesitate to say hi!

Thanks for everything guy, it has been awesome working on MapzenGo and doing this blog. Please try out the Mapbox SDK Unity beta and tell us what you think. It’s a developer tool afterall, your feedback is extremely important for us.

Cheers,
Baran

 

MapzenGo Part 7 : Plugins

Well yes, I decided to change the name of the series to simply “MapzenGo”. It’s shorter and admittedly, “PokemonGo clone” was a bit of a click bait. But hey, advertisement eh??
Anyway, we have another big update here. Mainly infrastructure stuff but I think you’ll all find them useful.

mapzen pokemongo openstreetmap layers offline maps buildings tokyoGood old Manhattan

-Major thing here is the new plugin system. Well I changed the factories a bit…again but nothing big really. First of all, I introduced a new base class called “Plugin”. It has a simple “Create” function and will be used for both factories and additional… plugins. So plugins are classes which operates on Tiles. Simple as that. Factories take tiles and creates buildings, roads etc. Other plugins, takes tiles and puts map images on them, add custom objects, maybe create forests or something.

So now you can create a class, inherit it from plugin, fill up the create method and put it under the World object in the scene. It’ll work right away.
That being said, I’m not done with refactoring the factories yet, I’ll remove the create from base factory class and leave that part to sub classes as well. That won’t effect the plugin system though, you’ll be able to work on your own plugins unaffected.

-Then I implement as very simple CustomObjectPlugin. People has been asking about how to visualized their own custom locations for weeks now. And yes it wasn’t really straight forward how to convert lat/long to unity3d position but this new plugin should help you with that. It’s just a sample really, nothing fancy going on there and you’ll probably need something much more complex for your needs but this should be enough to get you started.

-Then there is a great editor script, written by Roman (thanks mate!), to search places and use their lat/long right away. Admittedly I haven’t checked the code in detail but it uses Mapzen search api to find places, retrieve their lat/long and pass it to the tile manager. It’s so much easier now to navigate between different places, be it Manhatta, Paris or Istanbul.

mapzen pokemongo openstreetmap layers offline maps buildings tokyo search mapzengoSo much easier to test different place now.

-And I also fixed namespaces to match file locations. Should have done this much earlier, no idea how I missed it.

-Oh wait I actually forgot the biggest thing, entity settings and filtering! Well I did talked about this a little in previous posts but extended it a lot since then.
Ok, what is it? Remember, we didn’t have much chance to customize stuff before; hust some hard coded materials which wasn’t enough for anything really. No chance to set road widths, materials by building type etc.
So we have a new settings system to fix that! If you check the factory objects in the scene, you’ll see that there is a new Settings list under it. Using that list, you can customize, let’s say highway roads width or religious buildings material.

Even better, some factories (not all) are using those settings to filter entities, i.e. Road factory won’t render “ferry” routes if you don’t have a settings for that! This saves us from all the mess in big cities and helps us get a cleaner look. If I recall correctly, only building factory doesn’t use this filtering method. Building factory will render every single building and use custom settings on selected typed buildings.
We have only a few customization properties for now but it’s quite easy to add anything whenever we need. Ah and Roman is also working on moving all those settings to ScriptableObjects, it’ll get much easier to use as well.

mapzen pokemongo openstreetmap layers offline maps buildings stockholmStockholm

And that’s all for now I guess. I’ll try to look into gps, UV maps and other stuff next few weeks, no promises though, day job is getting quite intense these days.

Let me know what you think! You can mail me, post here or create issues on MapzenGo Github page. I also added a donation button at the right column (and at the bottom of this post), consider that as buying me a coffee or a beer. Oh I can definitely use a weihenstephaner right now…

Cheers,
Baran

MapzenGo Github Page
Twitter (started posting beauty shots and whatever there)
Download MapzenGo Part 7: Plugins

Save

Voronoi in Unity

Hey there!

Well I’ll keep this one short. I just got bored last week and decided to play with unity a bit.
I had the idea of converting my map generator stuff into Unity for a long time now but never had chance/time to do so.
And yea started with Voronoi stuff. Turns out that my old code is a horrible nightmare so rewritten most of the stuff, fixed some serious bugs etc etc.

 

Anyway, you can find the Unity Solution below.
And let me know if you have any questions! brnkahyaoglu@gmail.com
Cheers!

PS: Yea I don’t know how to package Unity projects so I just zipped the whole thing. Please do let me know if there is a proper way.

MapGen.zip (310.96 kb)

Hexagons in Unity – Part 2

OK I decided to write a small post about that part where we create the vertices, UV coordinates etc in the previous post.
I’ll try to make it clear for the people who’re new in 3D stuff.

 

So yeah, we created a hexagon in our previous post, by creating every vertex and triangle by hand, instead of using a pre-build 3D model. For the simplicity, I’ll do a basic version of our hex this time and create only the top face of the hexagon. If you remember the previous post, it had a height, sides and a bottom etc.

Anyway, first have a look at this;

Our hex has a radius of r, this is the distance from the center to any corner. In a standard hex, this is also equals to the edge length. And we have “Half Width”, well it’s the width divided by two really. Nothing fancy.
Remember that we’ll be using center of the hexagon as origin for creating the vertices. So for example, the coordinates for the top corner should be; ( 0, -R ).

UV mapping is a little bit different though. First of all, origin for UV mapping is always bottom left corner, this is fixed and you really can’t change it. Also the width and height of the UV map is scaled down to 1 ( see blue coordinates in the picture ). So again, UV coordinates for the top corner should be; ( 0.5, 1 ).

Let’s have a look at the function;

//top
Vertices[0] =new Vector3(0, 0, Globals.Radius);
UV[0] =new Vector2(0.5f, 1);
//topright
Vertices[1] =new Vector3(Globals.HalfWidth, 0, Globals.Radius /2);
UV[1] =new Vector2(1, 0.75f);
//bottomright
Vertices[2] =new Vector3(Globals.HalfWidth, 0, Globals.Radius /2);
UV[2] =new Vector2(1, 0.25f);
//bottom
Vertices[3] =new Vector3(0, 0, Globals.Radius);
UV[3] =new Vector2(0.5f, 0);
//bottomleft
Vertices[4] =new Vector3(Globals.HalfWidth, 0, Globals.Radius /2);
UV[4] =new Vector2(0, 0.25f);
//topleft
Vertices[5] =new Vector3(Globals.HalfWidth, 0, Globals.Radius /2);
UV[5] =new Vector2(0, 0.75f);

 

Array indexing for these stuff is actually important so be careful with that. Other than that, yea I guess that’s all for this one right?

So now we have bunch of vertices in the space but that doesn’t mean much in a 3D world. To create something visible, we need surfaces and for that we need triangles. Next thing we need to do is to set the triangle information, in other words, let the system know which 3 vertices will be used for a triangle.

 

Now check this out;

 

 

Notice that numbers right by the corners are the index numbers of vertices in the Vertices array. So now we divided our hexagon into 4 triangles and all we have to do is;

2f3″>};

Triangles =new int[]
{
1, 0, 5, 2, 4, 3, 2, 1, 4, 1, 5, 4
};

This array will take integer three by three and generate triangles out of them. So 1,0,5 will be our first triangle, 2,4,3 will be the second etc.
Important thing to note here is that, order of the vertices do matter. In our situation, we ordered them counter clockwise so the surface will be above ( it’s all one sided ). If we had them clockwise, surface would have been below. So if you want to turn it over, you can just change the order of vertices, ie 1,0,5 to 1,5,0.

 

There is one more little thing in the code I posted earlier; Normals.
Normals aren’t always necessary ( depending on the shader ) but it’s good to know really. They are small vectors, showing UP for every single vertex. Yea, Up as in the opposite of down. Normals are used for lighting calculations so pretty damn important as well. For this example though, our normals array will be extremely simple as our shape is simple itself. It’s a simple surface so we can just set all vertex normals to 0,1,0 ( world up in my sample ).

22282a;color:#ffcd22

Normals =new Vector3[]
{
new Vector3(0, 1, 0),
new Vector3(0, 1, 0),
new Vector3(0, 1, 0),
new Vector3(0, 1, 0),
new Vector3(0, 1, 0),
new Vector3(0, 1, 0)
     };

Again the indexes should be in sync with other array indexes, so first vector3 is the normal for vertex 0 etc.

Aaaand that should be it. You can find the whole sample code in the previous post.

Let me know if you have any question, liked the post or wanted to say hi.
I had to close the comments due to increasing spams but you sure can always mail me for anything; brnkahyaoglu@gmail.com
See you later everyone!

Unity

Soooo it has been a while eh?

I know I know, I really should start posting again. It’s not that I’m not doing but I’m terribly busy and doing some oh-not-so-cool stuff these days. ie. master course homeworks -_-

Yeah, boring days, development wise.

Anyway, I had little free time yesterday and decided to check out Unity3D. I actually was looking for a chance to check it out for… a few years now? Finally yesterday was the day!

My first experimental work was on hexagons as usual. I just love hexagons.

I learned a decent amount of stuff about code management and structure of unity. It’s quite fun really, even felt a little bit toooo easy haha.

Even after switching from XNA to Unity, I’m still creating every object vertex by vertex by the way, not sure if it’s a good habit or not but sure feels weird.

Anyway you can check it out here; ( WASD for movement and mouse for camera )

http://www.barankahyaoglu.com/unity/smallshooter.html

Oh yea I’m also LOVING this web player thing. A few seconds of gameplay is sooo much better than thousands of screenshots afterall.

I’ll try to post more and especially about Unity in the future.

Cyaaa!

Robotics & Voronoi

So my 3rd homework in Robot Motion Planning class was about voronoi diagrams. Nice isn’t it?

 

It’s about generating a voronoi diagram of environment so that robot can move safely as that diagram using it as a roadmap. Neat idea actually, surely not the best and somewhat cumbersome but still good one.

But the diagram generation technique was different this time, we were supposed to create the diagram by walking on it while keeping the distances in balance etc etc.

 

Anyway the paper is here, not my best work but it’s there anyway so it could be on my blog as well right?

 

www.barankahyaoglu.com/robotics/voronoirobot

 

Shadow Casting

I did this a few weeks ago actually but didn’t have time to write a post about it.

Well I was planing to write a longer post about it but considering it’s not that fast ( not as fast as it should be ) and buggy ( got some corner cases ), I decided to skip the post thingy and just put it here as is ( mainly because I have no intention to fix&improve it further )

Oh and again, it is inspired by Amit and his Shadow Casting post.

 

 

And here it is;

http://barankahyaoglu.com/shadowcasting/

( You might need to refresh the page right away )

 

Potential Fields

There isnt much to say really.  

Potential fields and navigation function was my Robotic Motion Planning  2nd homework. Implementing both algorithms, comparing them etc.  

 

There it is in all details;

www.barankahyaoglu.com/robotics/potential/

 

Metro Style Application & Horizontal Scrolling

So I’ve been playing with Windows 8 and WinRT for a while now, had a little problem the other day and thought it would worth to post the workaround I found.

If you ever saw a metro style application demonstration, you probably noticed that applications using metro design style prefers horizontal scrolling over vertical for big bodies. Obviously they thought that horizontal scrolling feel much more natural on a touch device ( which I actually agree ).

The problem is, it’s flat out horrible for Keyboard&Mouse devices ( aka. 99.9% of Windows users ). And for some reason, they didn’t implemented a function to bind mouse wheel scroll to horizontal scroll by default. Weird.

But well it’s not hard anyway, you just have to remember that you’re pretty much coding for IE. Which means you can use some IE functions that other browsers don’t support ( and that seems why they’re kinda forgotten I guess? )

So this is what you got to do;

    document.documentElement.onmousewheel = function (event) {
        $(‘#contenthost’).scrollLeft($(‘#contenthost’).scrollLeft() event.wheelDelta);
    };

Obviously ContentHost should be the element with scrollbar. And you should be careful using this because you obviously don’t want it in snapped view so

    updateLayout: function (element, viewState) {
        if (viewState != appViewState.snapped) {
            document.documentElement.onmousewheel = function (event) { $(‘#contenthost’).scrollLeft($(‘#contenthost’).scrollLeft() – event.wheelDelta); };
        }
    }
So that’s it, now your mouse wheel should scroll the page horizontally!
I hope you find it useful., see you in another post.

Skinning a WPF Application

Hello again!

This time I’ll talk a little about skinning/theming a WPF application. I honestly believe this is an important feature for WPF application for a few reasons ;

1) It’s really easy to do so there is no excuse for not doing it

2) Visualization is supposed to be the strong suit of any WPF application

3) Everybody loves customization, especially if it’s a high-end user application ( like towel )

And one more key thing before going into technical stuff; style files should be external so users would be able to edit exiting styles or create new ones by just using notepad! Remember users would never bother with it if it’s not easy to do.

 

OK so here is our plan;

1) We’ll extract all style information to external xaml files and call those styles using Static or Dynamic Resource binding.

2) Search folders for any acceptable Theme/Skin folder

3) Put those Theme/Skin names in a combo box so users can easily change the theme

4) Add all new style entries to Application Resource pool ( and they’ll override the old entries )

Now if you use DynamicResource for style bindings, everything will be updated as soon as user selects a new item from combo box. If you use StaticResource though, you’ll have to save selection as a setting and load those style files next time user runs the application. ( remember “you need to restart the application for settings to take effect” thingy )

 

Let’s start, first of all you should extract every single style information from your page/window/usercontrol xaml to an external resource dictionary. I believe this is not only important for Theming but also for a better workflow since xaml’s tend to get VERY messy with style information inside.

Theme file structure;

WindowClipping (20)

And sample Page/Window/UserControl xaml;

<StackPanel Margin=“212,40,40,40” Orientation=“Vertical”>
    <Border Style=”{DynamicResource BorderStyle}>
        <TextBlock Style=”{DynamicResource TextStyle1} Text=“CheapTowel” />
    </Border>
    <Border Style=”{DynamicResource BorderStyle2}>
        <TextBlock Style=”{DynamicResource TextStyle2} Text=“Fluffy Towel” />
    </Border>
    <Border Style=”{DynamicResource BorderStyle3}>
        <TextBlock Style=”{DynamicResource TextStyle3} Text=“Glorious Towel” />
    </Border>
</StackPanel>

If you check that xaml sample, you’ll see that I extracted the style information from TextBlocks and Borders so they’ll be skinable but Margin and Orientation values of StackPanel are still static so we won’t be able to change those using skins.

I also haven’t included Text into styles as I’ll talk about Localization in a future post.

OK now this xaml means, those 3 Borders and 3 TextBlocks will check Application Resource pool for those particular style entry keys and use them. So every Theme should have style entries exactly by those names. If a textblock demands “TextStyle3”, it’ll go use the current theme’s “TextStyle3” entry. Easy peasy.

Now let’s populate our combo box with themes in our directory;

First, ThemeData helper class;

    public class ThemeData
    {
        public string ThemeName { get; set; }
        public string ThemePath { get; set; }
    }

And the rest;

var themes =
    from dir in
        Directory.GetDirectories(Directory.GetParent(Assembly.GetEntryAssembly().Location) + “/Themes/”)
    select new ThemeData()
                {
                    ThemeName = new FileInfo(dir).Name,
                    ThemePath = dir
                };

foreach (ThemeData td in themes)
{
    combo.Items.Add(td);
}

As you can see, we look for “Themes” folder, which expected to be on the same level as our executable. There isn’t a existence check but you can add those stuff as you wish. Notice we’re looking for directories inside “Themes” folder, not files since we’ll have folders for different Themes and then theme files in those folder. Guess I should have talked about file structure before eh? Anyway, we need just folder names and paths for combo box and we’re saving all those into ThemeData helper class.

Now that we’ve populated the combo box with our Themes, all we have to do now, is creating a “SelectionChanged” event and add selected theme’s files to the application pool.

    private void ThemeChanged(object sender, SelectionChangedEventArgs e)
    {
        if (combo.SelectedIndex == 1) return;

        foreach (var command in Directory.GetFiles(((ThemeData)combo.SelectedValue).ThemePath).Where(x => x.EndsWith(“.xaml”)))
        {
            var stream = new FileStream(command, FileMode.Open);

            foreach (DictionaryEntry dictionaryEntry in (ResourceDictionary)XamlReader.Load(stream))
            {
                Application.Current.Resources[dictionaryEntry.Key] = dictionaryEntry.Value;
            }
        }
    }

This should be pretty straight forward, we get the theme name from combo box, then search the theme folder for xaml files, read&parse and add them to Application Resources. New entries will override the old entries with same Key, so all entries of old theme will be replaced.

 

WindowClipping (21)

 

Best part of this theming thing is that users can easily change whatever they want using just notepad.

All users have to do;

1) Duplicate an existing theme folder;

WindowClipping (22)

 

Optional ) You can name files whatever you want

WindowClipping (23)

3) Edit style as you wish, just keep the style x:Key and TargetType same.

LolThemeFile.xaml - Notepad2 (Administrator)

4) ???

5) Profit

MainWindow (16)

That’s it!

 

I hope you like it or find it useful, next post will be a Towel Theming Sample OR something about WPF Localization. Oh and you can find the sample code of this post below, see you next time!

 

Visual Studio 2010 Sample Solution File