demo007.odin 13 KB

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