1 /*
2  * Copyright 2015 Google Inc. All rights reserved.
3  *
4  * Licensed under the Apache License, Version 2.0 (the "License");
5  * you may not use this file except in compliance with the License.
6  * You may obtain a copy of the License at
7  *
8  *     http://www.apache.org/licenses/LICENSE-2.0
9  *
10  * Unless required by applicable law or agreed to in writing, software
11  * distributed under the License is distributed on an "AS IS" BASIS,
12  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13  * See the License for the specific language governing permissions and
14  * limitations under the License.
15  */
16 
17 // To run, use the `csharp_sample.sh` script.
18 
19 using System;
20 using FlatBuffers;
21 using MyGame.Sample;
22 
23 class SampleBinary
24 {
25   // Example how to use FlatBuffers to create and read binary buffers.
Main()26   static void Main()
27   {
28     var builder = new FlatBufferBuilder(1);
29 
30     // Create some weapons for our Monster ('Sword' and 'Axe').
31     var weapon1Name = builder.CreateString("Sword");
32     var weapon1Damage = 3;
33     var weapon2Name = builder.CreateString("Axe");
34     var weapon2Damage = 5;
35 
36     // Use the `CreateWeapon()` helper function to create the weapons, since we set every field.
37     var weaps = new Offset<Weapon>[2];
38     weaps[0] = Weapon.CreateWeapon(builder, weapon1Name, (short)weapon1Damage);
39     weaps[1] = Weapon.CreateWeapon(builder, weapon2Name, (short)weapon2Damage);
40 
41     // Serialize the FlatBuffer data.
42     var name = builder.CreateString("Orc");
43     var treasure =  new byte[] {0, 1, 2, 3, 4, 5, 6, 7, 8, 9};
44     var inv = Monster.CreateInventoryVector(builder, treasure);
45     var weapons = Monster.CreateWeaponsVector(builder, weaps);
46     var pos = Vec3.CreateVec3(builder, 1.0f, 2.0f, 3.0f);
47 
48     Monster.StartMonster(builder);
49     Monster.AddPos(builder, pos);
50     Monster.AddHp(builder, (short)300);
51     Monster.AddName(builder, name);
52     Monster.AddInventory(builder, inv);
53     Monster.AddColor(builder, Color.Red);
54     Monster.AddWeapons(builder, weapons);
55     Monster.AddEquippedType(builder, Equipment.Weapon);
56     Monster.AddEquipped(builder, weaps[1].Value);
57     var orc = Monster.EndMonster(builder);
58 
59     builder.Finish(orc.Value); // You could also call `Monster.FinishMonsterBuffer(builder, orc);`.
60 
61     // We now have a FlatBuffer that we could store on disk or send over a network.
62 
63     // ...Code to store to disk or send over a network goes here...
64 
65     // Instead, we are going to access it right away, as if we just received it.
66 
67     var buf = builder.DataBuffer;
68 
69     // Get access to the root:
70     var monster = Monster.GetRootAsMonster(buf);
71 
72     // For C#, unlike other languages, most values (except for vectors and unions) are available as
73     // properties instead of accessor methods.
74 
75     // Note: We did not set the `Mana` field explicitly, so we get back the default value.
76     Assert(monster.Mana == 150, "monster.Mana", Convert.ToString(monster.Mana),
77            Convert.ToString(150));
78     Assert(monster.Hp == 300, "monster.Hp", Convert.ToString(monster.Hp), Convert.ToString(30));
79     Assert(monster.Name.Equals("Orc", StringComparison.Ordinal), "monster.Name", monster.Name,
80            "Orc");
81     Assert(monster.Color == Color.Red, "monster.Color", Convert.ToString(monster.Color),
82            Convert.ToString(Color.Red));
83 
84     var vec = monster.Pos.Value;
85     Assert(vec.X == 1.0f, "vec.X",
86            Convert.ToString(vec.X), Convert.ToString(1.0f));
87     Assert(vec.Y == 2.0f, "vec.Y",
88            Convert.ToString(vec.Y), Convert.ToString(2.0f));
89     Assert(vec.Z == 3.0f, "vec.Z",
90            Convert.ToString(vec.Z), Convert.ToString(3.0f));
91 
92     // Get and test the `Inventory` FlatBuffer `vector`.
93     for (int i = 0; i < monster.InventoryLength; i++)
94     {
95       Assert(monster.Inventory(i) == i, "monster.Inventory",
96              Convert.ToString(monster.Inventory(i)), Convert.ToString(i));
97     }
98 
99     // Get and test the `Weapons` FlatBuffer `vector` of `table`s.
100     var expectedWeaponNames = new string[] {"Sword", "Axe"};
101     var expectedWeaponDamages = new short[] {3, 5};
102     for (int i = 0; i < monster.WeaponsLength; i++)
103     {
104       Assert(monster.Weapons(i).Value.Name.Equals(expectedWeaponNames[i], StringComparison.Ordinal),
105              "monster.Weapons", monster.Weapons(i).Value.Name, expectedWeaponNames[i]);
106       Assert(monster.Weapons(i).Value.Damage == expectedWeaponDamages[i], "monster.GetWeapons",
107              Convert.ToString(monster.Weapons(i).Value.Damage),
108              Convert.ToString(expectedWeaponDamages[i]));
109     }
110 
111     // Get and test the `Equipped` FlatBuffer `union`.
112     Assert(monster.EquippedType == Equipment.Weapon, "monster.EquippedType",
113            Convert.ToString(monster.EquippedType), Convert.ToString(Equipment.Weapon));
114     var equipped = monster.Equipped<Weapon>().Value;
115     Assert(equipped.Name.Equals("Axe", StringComparison.Ordinal), "equipped.Name", equipped.Name,
116            "Axe");
117     Assert(equipped.Damage == 5, "equipped.Damage", Convert.ToString(equipped.Damage),
118            Convert.ToString(5));
119 
120     Console.WriteLine("The FlatBuffer was successfully created and verified!");
121   }
122 
123   // A helper function to handle assertions.
Assert(bool assertPassed, string codeExecuted, string actualValue, string expectedValue)124   static void Assert(bool assertPassed, string codeExecuted, string actualValue,
125                      string expectedValue)
126   {
127     if (assertPassed == false)
128     {
129       Console.WriteLine("Assert failed! " + codeExecuted + " (" + actualValue +
130           ") was not equal to " + expectedValue + ".");
131       System.Environment.Exit(1);
132     }
133   }
134 }
135