demo.odin 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601
  1. import (
  2. "fmt.odin";
  3. "strconv.odin";
  4. "mem.odin";
  5. "thread.odin" when ODIN_OS == "windows";
  6. win32 "sys/windows.odin" when ODIN_OS == "windows";
  7. /*
  8. "atomics.odin";
  9. "bits.odin";
  10. "hash.odin";
  11. "math.odin";
  12. "opengl.odin";
  13. "os.odin";
  14. "raw.odin";
  15. "sort.odin";
  16. "strings.odin";
  17. "sync.odin";
  18. "types.odin";
  19. "utf8.odin";
  20. "utf16.odin";
  21. */
  22. )
  23. general_stuff :: proc() {
  24. { // `do` for inline statmes rather than block
  25. foo :: proc() do fmt.println("Foo!");
  26. if false do foo();
  27. for false do foo();
  28. when false do foo();
  29. if false do foo();
  30. else do foo();
  31. }
  32. { // Removal of `++` and `--` (again)
  33. x: int;
  34. x += 1;
  35. x -= 1;
  36. }
  37. { // Casting syntaxes
  38. i := i32(137);
  39. ptr := &i;
  40. fp1 := (^f32)(ptr);
  41. // ^f32(ptr) == ^(f32(ptr))
  42. fp2 := cast(^f32)ptr;
  43. f1 := (^f32)(ptr)^;
  44. f2 := (cast(^f32)ptr)^;
  45. // Questions: Should there be two ways to do it?
  46. }
  47. /*
  48. * Remove *_val_of built-in procedures
  49. * size_of, align_of, offset_of
  50. * type_of, type_info_of
  51. */
  52. { // `expand_to_tuple` built-in procedure
  53. Foo :: struct {
  54. x: int;
  55. b: bool;
  56. }
  57. f := Foo{137, true};
  58. x, b := expand_to_tuple(f);
  59. fmt.println(f);
  60. fmt.println(x, b);
  61. fmt.println(expand_to_tuple(f));
  62. }
  63. {
  64. // .. half-closed range
  65. // ... open range
  66. for in 0..2 {} // 0, 1
  67. for in 0...2 {} // 0, 1, 2
  68. }
  69. }
  70. nested_struct_declarations :: proc() {
  71. {
  72. FooInteger :: int;
  73. Foo :: struct {
  74. i: FooInteger;
  75. };
  76. f := Foo{FooInteger(137)};
  77. }
  78. {
  79. Foo :: struct {
  80. Integer :: int;
  81. i: Integer;
  82. }
  83. f := Foo{Foo.Integer(137)};
  84. }
  85. }
  86. default_struct_values :: proc() {
  87. {
  88. Vector3 :: struct {
  89. x: f32;
  90. y: f32;
  91. z: f32;
  92. }
  93. v: Vector3;
  94. fmt.println(v);
  95. }
  96. {
  97. // Default values must be constants
  98. Vector3 :: struct {
  99. x: f32 = 1;
  100. y: f32 = 4;
  101. z: f32 = 9;
  102. }
  103. v: Vector3;
  104. fmt.println(v);
  105. v = Vector3{};
  106. fmt.println(v);
  107. // Uses the same semantics as a default values in a procedure
  108. v = Vector3{137};
  109. fmt.println(v);
  110. v = Vector3{z = 137};
  111. fmt.println(v);
  112. }
  113. {
  114. Vector3 :: struct {
  115. x := 1.0;
  116. y := 4.0;
  117. z := 9.0;
  118. }
  119. stack_default: Vector3;
  120. stack_literal := Vector3{};
  121. heap_one := new(Vector3); defer free(heap_one);
  122. heap_two := new_clone(Vector3{}); defer free(heap_two);
  123. fmt.println("stack_default - ", stack_default);
  124. fmt.println("stack_literal - ", stack_literal);
  125. fmt.println("heap_one - ", heap_one^);
  126. fmt.println("heap_two - ", heap_two^);
  127. N :: 4;
  128. stack_array: [N]Vector3;
  129. heap_array := new([N]Vector3); defer free(heap_array);
  130. heap_slice := make([]Vector3, N); defer free(heap_slice);
  131. fmt.println("stack_array[1] - ", stack_array[1]);
  132. fmt.println("heap_array[1] - ", heap_array[1]);
  133. fmt.println("heap_slice[1] - ", heap_slice[1]);
  134. }
  135. }
  136. union_type :: proc() {
  137. {
  138. val: union{int, bool};
  139. val = 137;
  140. if i, ok := val.(int); ok {
  141. fmt.println(i);
  142. }
  143. val = true;
  144. fmt.println(val);
  145. val = nil;
  146. match v in val {
  147. case int: fmt.println("int", v);
  148. case bool: fmt.println("bool", v);
  149. case: fmt.println("nil");
  150. }
  151. }
  152. {
  153. // There is a duality between `any` and `union`
  154. // An `any` has a pointer to the data and allows for any type (open)
  155. // A `union` has as binary blob to store the data and allows only certain types (closed)
  156. // The following code is with `any` but has the same syntax
  157. val: any;
  158. val = 137;
  159. if i, ok := val.(int); ok {
  160. fmt.println(i);
  161. }
  162. val = true;
  163. fmt.println(val);
  164. val = nil;
  165. match v in val {
  166. case int: fmt.println("int", v);
  167. case bool: fmt.println("bool", v);
  168. case: fmt.println("nil");
  169. }
  170. }
  171. Vector3 :: struct {
  172. x, y, z: f32;
  173. };
  174. Quaternion :: struct {
  175. x, y, z: f32;
  176. w: f32 = 1;
  177. };
  178. // More realistic examples
  179. {
  180. // NOTE(bill): For the above basic examples, you may not have any
  181. // particular use for it. However, my main use for them is not for these
  182. // simple cases. My main use is for hierarchical types. Many prefer
  183. // subtyping, embedding the base data into the derived types. Below is
  184. // an example of this for a basic game Entity.
  185. Entity :: struct {
  186. id: u64;
  187. name: string;
  188. position: Vector3;
  189. orientation: Quaternion;
  190. derived: any;
  191. }
  192. Frog :: struct {
  193. using entity: Entity;
  194. jump_height: f32;
  195. }
  196. Monster :: struct {
  197. using entity: Entity;
  198. is_robot: bool;
  199. is_zombie: bool;
  200. }
  201. // See `parametric_polymorphism` procedure for details
  202. new_entity :: proc(T: type) -> ^Entity {
  203. t := new(T);
  204. t.derived = t^;
  205. return t;
  206. }
  207. entity := new_entity(Monster);
  208. match e in entity.derived {
  209. case Frog:
  210. fmt.println("Ribbit");
  211. case Monster:
  212. if e.is_robot do fmt.println("Robotic");
  213. if e.is_zombie do fmt.println("Grrrr!");
  214. }
  215. }
  216. {
  217. // NOTE(bill): A union can be used to achieve something similar. Instead
  218. // of embedding the base data into the derived types, the derived data
  219. // in embedded into the base type. Below is the same example of the
  220. // basic game Entity but using an union.
  221. Entity :: struct {
  222. id: u64;
  223. name: string;
  224. position: Vector3;
  225. orientation: Quaternion;
  226. derived: union {Frog, Monster};
  227. }
  228. Frog :: struct {
  229. using entity: ^Entity;
  230. jump_height: f32;
  231. }
  232. Monster :: struct {
  233. using entity: ^Entity;
  234. is_robot: bool;
  235. is_zombie: bool;
  236. }
  237. // See `parametric_polymorphism` procedure for details
  238. new_entity :: proc(T: type) -> ^Entity {
  239. t := new(Entity);
  240. t.derived = T{entity = t};
  241. return t;
  242. }
  243. entity := new_entity(Monster);
  244. match e in entity.derived {
  245. case Frog:
  246. fmt.println("Ribbit");
  247. case Monster:
  248. if e.is_robot do fmt.println("Robotic");
  249. if e.is_zombie do fmt.println("Grrrr!");
  250. }
  251. // NOTE(bill): As you can see, the usage code has not changed, only its
  252. // memory layout. Both approaches have their own advantages but they can
  253. // be used together to achieve different results. The subtyping approach
  254. // can allow for a greater control of the memory layout and memory
  255. // allocation, e.g. storing the derivatives together. However, this is
  256. // also its disadvantage. You must either preallocate arrays for each
  257. // derivative separation (which can be easily missed) or preallocate a
  258. // bunch of "raw" memory; determining the maximum size of the derived
  259. // types would require the aid of metaprogramming. Unions solve this
  260. // particular problem as the data is stored with the base data.
  261. // Therefore, it is possible to preallocate, e.g. [100]Entity.
  262. // It should be noted that the union approach can have the same memory
  263. // layout as the any and with the same type restrictions by using a
  264. // pointer type for the derivatives.
  265. /*
  266. Entity :: struct {
  267. ...
  268. derived: union{^Frog, ^Monster};
  269. }
  270. Frog :: struct {
  271. using entity: Entity;
  272. ...
  273. }
  274. Monster :: struct {
  275. using entity: Entity;
  276. ...
  277. }
  278. new_entity :: proc(T: type) -> ^Entity {
  279. t := new(T);
  280. t.derived = t;
  281. return t;
  282. }
  283. */
  284. }
  285. }
  286. parametric_polymorphism :: proc() {
  287. print_value :: proc(value: $T) {
  288. fmt.printf("print_value: %T %v\n", value, value);
  289. }
  290. v1: int = 1;
  291. v2: f32 = 2.1;
  292. v3: f64 = 3.14;
  293. v4: string = "message";
  294. print_value(v1);
  295. print_value(v2);
  296. print_value(v3);
  297. print_value(v4);
  298. fmt.println();
  299. add :: proc(p, q: $T) -> T {
  300. x: T = p + q;
  301. return x;
  302. }
  303. a := add(3, 4);
  304. fmt.printf("a: %T = %v\n", a, a);
  305. b := add(3.2, 4.3);
  306. fmt.printf("b: %T = %v\n", b, b);
  307. // This is how `new` is implemented
  308. alloc_type :: proc(T: type) -> ^T {
  309. t := cast(^T)alloc(size_of(T), align_of(T));
  310. t^ = T{}; // Use default initialization value
  311. return t;
  312. }
  313. copy_slice :: proc(dst, src: []$T) -> int {
  314. n := min(len(dst), len(src));
  315. if n > 0 {
  316. mem.copy(&dst[0], &src[0], n*size_of(T));
  317. }
  318. return n;
  319. }
  320. double_params :: proc(a: $A, b: $B) -> A {
  321. return a + A(b);
  322. }
  323. fmt.println(double_params(12, 1.345));
  324. { // Polymorphic Types and Type Specialization
  325. Table :: struct(Key, Value: type) {
  326. Slot :: struct {
  327. occupied: bool;
  328. hash: u32;
  329. key: Key;
  330. value: Value;
  331. }
  332. SIZE_MIN :: 32;
  333. count: int;
  334. allocator: Allocator;
  335. slots: []Slot;
  336. }
  337. // Only allow types that are specializations of a (polymorphic) slice
  338. make_slice :: proc(T: type/[]$E, len: int) -> T {
  339. return make(T, len);
  340. }
  341. // Only allow types that are specializations of `Table`
  342. allocate :: proc(table: ^$T/Table, capacity: int) {
  343. c := context;
  344. if table.allocator.procedure != nil do c.allocator = table.allocator;
  345. push_context c {
  346. table.slots = make_slice([]T.Slot, max(capacity, T.SIZE_MIN));
  347. }
  348. }
  349. expand :: proc(table: ^$T/Table) {
  350. c := context;
  351. if table.allocator.procedure != nil do c.allocator = table.allocator;
  352. push_context c {
  353. old_slots := table.slots;
  354. cap := max(2*cap(table.slots), T.SIZE_MIN);
  355. allocate(table, cap);
  356. for s in old_slots do if s.occupied {
  357. put(table, s.key, s.value);
  358. }
  359. free(old_slots);
  360. }
  361. }
  362. // Polymorphic determination of a polymorphic struct
  363. // put :: proc(table: ^$T/Table, key: T.Key, value: T.Value) {
  364. put :: proc(table: ^Table($Key, $Value), key: Key, value: Value) {
  365. hash := get_hash(key); // Ad-hoc method which would fail in a different scope
  366. index := find_index(table, key, hash);
  367. if index < 0 {
  368. if f64(table.count) >= 0.75*f64(cap(table.slots)) {
  369. expand(table);
  370. }
  371. assert(table.count <= cap(table.slots));
  372. hash := get_hash(key);
  373. index = int(hash % u32(cap(table.slots)));
  374. for table.slots[index].occupied {
  375. if index += 1; index >= cap(table.slots) {
  376. index = 0;
  377. }
  378. }
  379. table.count += 1;
  380. }
  381. slot := &table.slots[index];
  382. slot.occupied = true;
  383. slot.hash = hash;
  384. slot.key = key;
  385. slot.value = value;
  386. }
  387. // find :: proc(table: ^$T/Table, key: T.Key) -> (T.Value, bool) {
  388. find :: proc(table: ^Table($Key, $Value), key: Key) -> (Value, bool) {
  389. hash := get_hash(key);
  390. index := find_index(table, key, hash);
  391. if index < 0 {
  392. return Value{}, false;
  393. }
  394. return table.slots[index].value, true;
  395. }
  396. find_index :: proc(table: ^Table($Key, $Value), key: Key, hash: u32) -> int {
  397. if cap(table.slots) <= 0 do return -1;
  398. index := int(hash % u32(cap(table.slots)));
  399. for table.slots[index].occupied {
  400. if table.slots[index].hash == hash {
  401. if table.slots[index].key == key {
  402. return index;
  403. }
  404. }
  405. if index += 1; index >= cap(table.slots) {
  406. index = 0;
  407. }
  408. }
  409. return -1;
  410. }
  411. get_hash :: proc(s: string) -> u32 { // fnv32a
  412. h: u32 = 0x811c9dc5;
  413. for i in 0..len(s) {
  414. h = (h ~ u32(s[i])) * 0x01000193;
  415. }
  416. return h;
  417. }
  418. table: Table(string, int);
  419. for i in 0..36 do put(&table, "Hellope", i);
  420. for i in 0..42 do put(&table, "World!", i);
  421. found, _ := find(&table, "Hellope");
  422. fmt.printf("`found` is %v\n", found);
  423. found, _ = find(&table, "World!");
  424. fmt.printf("`found` is %v\n", found);
  425. // I would not personally design a hash table like this in production
  426. // but this is a nice basic example
  427. // A better approach would either use a `u64` or equivalent for the key
  428. // and let the user specify the hashing function or make the user store
  429. // the hashing procedure with the table
  430. }
  431. }
  432. prefix_table := [...]string{
  433. "White",
  434. "Red",
  435. "Green",
  436. "Blue",
  437. "Octarine",
  438. "Black",
  439. };
  440. threading_example :: proc() {
  441. when ODIN_OS == "windows" {
  442. unordered_remove :: proc(array: ^[]$T, index: int, loc := #caller_location) {
  443. __bounds_check_error_loc(loc, index, len(array));
  444. array[index] = array[len(array)-1];
  445. pop(array);
  446. }
  447. ordered_remove :: proc(array: ^[]$T, index: int, loc := #caller_location) {
  448. __bounds_check_error_loc(loc, index, len(array));
  449. copy(array[index..], array[index+1..]);
  450. pop(array);
  451. }
  452. worker_proc :: proc(t: ^thread.Thread) -> int {
  453. for iteration in 1...5 {
  454. fmt.printf("Thread %d is on iteration %d\n", t.user_index, iteration);
  455. fmt.printf("`%s`: iteration %d\n", prefix_table[t.user_index], iteration);
  456. // win32.sleep(1);
  457. }
  458. return 0;
  459. }
  460. threads := make([]^thread.Thread, 0, len(prefix_table));
  461. defer free(threads);
  462. for i in 0..len(prefix_table) {
  463. if t := thread.create(worker_proc); t != nil {
  464. t.init_context = context;
  465. t.use_init_context = true;
  466. t.user_index = len(threads);
  467. append(&threads, t);
  468. thread.start(t);
  469. }
  470. }
  471. for len(threads) > 0 {
  472. for i := 0; i < len(threads); {
  473. if t := threads[i]; thread.is_done(t) {
  474. fmt.printf("Thread %d is done\n", t.user_index);
  475. thread.destroy(t);
  476. ordered_remove(&threads, i);
  477. } else {
  478. i += 1;
  479. }
  480. }
  481. }
  482. }
  483. }
  484. main :: proc() {
  485. when true {
  486. fmt.println("\n# general_stuff"); general_stuff();
  487. fmt.println("\n# nested_struct_declarations"); nested_struct_declarations();
  488. fmt.println("\n# default_struct_values"); default_struct_values();
  489. fmt.println("\n# union_type"); union_type();
  490. fmt.println("\n# parametric_polymorphism"); parametric_polymorphism();
  491. fmt.println("\n# threading_example"); threading_example();
  492. }
  493. }