diff options
| author | 2026-11-11 22:28:13 +0000 | |
|---|---|---|
| committer | 2026-11-11 22:47:34 +0000 | |
| commit | cb070b2d3f2b6e241e3be1b7e0eeb90fc755255f (patch) | |
| tree | c7d90c0abe9533c87d51b5196871846855efa1ba /src | |
| download | thesis-master.tar.gz | |
Diffstat (limited to 'src')
36 files changed, 6530 insertions, 0 deletions
diff --git a/src/arena.c b/src/arena.c new file mode 100644 index 0000000..461bc7a --- /dev/null +++ b/src/arena.c | |||
| @@ -0,0 +1,469 @@ | |||
| 1 | /// src/arena.c --- chunked arena allocator | ||
| 2 | // | ||
| 3 | // Copyright (C) 2026 by Martin Michalec <martin@michalec.dev> | ||
| 4 | // | ||
| 5 | // SPDX-License-Identifier: MIT | ||
| 6 | // | ||
| 7 | /// Commentary: | ||
| 8 | // | ||
| 9 | /// Code: | ||
| 10 | |||
| 11 | #define _GNU_SOURCE // TODO(cmmm): remove hard dependency on GNU extensions | ||
| 12 | #include <stdint.h> | ||
| 13 | #include <string.h> | ||
| 14 | |||
| 15 | // TODO(cmmm): rethink alignment in relation to coalescing, it seems | ||
| 16 | // really hard to get right... Verdict, use obstack (keeping track of | ||
| 17 | // base) for making sure fields are aligned (by adding extra padding). | ||
| 18 | // Coalescing stays the same and can still be used without obstack, if | ||
| 19 | // you know that there won't be need for extra alignment ensuring | ||
| 20 | // padding | ||
| 21 | |||
| 22 | #include "arena.h" | ||
| 23 | |||
| 24 | #ifndef ARENA_ASSERT | ||
| 25 | #include <assert.h> | ||
| 26 | #define ASSERT assert | ||
| 27 | #define ASSERT_PERROR assert_perror | ||
| 28 | #else | ||
| 29 | #define ASSERT ARENA_ASSERT | ||
| 30 | #endif | ||
| 31 | |||
| 32 | #include <stdlib.h> | ||
| 33 | #define MALLOC malloc | ||
| 34 | #define ALIGNED_ALLOC aligned_alloc | ||
| 35 | #define FREE free | ||
| 36 | |||
| 37 | #define MAX(A, B) ((A) > (B) ? (A) : (B)) | ||
| 38 | |||
| 39 | // NOTE(cmmm): address of chunk == chunk's end | ||
| 40 | #define CHUNK_END(CHUNK) ((void *) (CHUNK)) | ||
| 41 | |||
| 42 | static size_t | ||
| 43 | chunk_size (const struct arena_chunk *chunk) | ||
| 44 | { | ||
| 45 | ASSERT (chunk != NULL); | ||
| 46 | |||
| 47 | return CHUNK_END (chunk) - chunk->begin; | ||
| 48 | } | ||
| 49 | |||
| 50 | static size_t | ||
| 51 | chunk_used (struct arena_chunk *chunk) | ||
| 52 | { | ||
| 53 | ASSERT (chunk != NULL); | ||
| 54 | |||
| 55 | return chunk->free - chunk->begin; | ||
| 56 | } | ||
| 57 | |||
| 58 | static struct arena_chunk * | ||
| 59 | new_chunk (size_t size, size_t alignment) | ||
| 60 | { | ||
| 61 | ASSERT ((alignment & (alignment + 1)) == 0); | ||
| 62 | |||
| 63 | alignment += 1; | ||
| 64 | alignment += alignment % sizeof (void *); | ||
| 65 | |||
| 66 | void *chunk_begin = | ||
| 67 | ALIGNED_ALLOC (alignment, size + sizeof (struct arena_chunk)); | ||
| 68 | ASSERT (chunk_begin != NULL); | ||
| 69 | |||
| 70 | struct arena_chunk *chunk = chunk_begin + size; | ||
| 71 | chunk->next = NULL; | ||
| 72 | chunk->begin = chunk_begin; | ||
| 73 | chunk->free = chunk_begin; | ||
| 74 | |||
| 75 | return chunk; | ||
| 76 | } | ||
| 77 | |||
| 78 | static struct arena_chunk * | ||
| 79 | append_chunk (struct arena *arena, size_t size, size_t alignment) | ||
| 80 | { | ||
| 81 | ASSERT (arena != NULL); | ||
| 82 | |||
| 83 | size = arena->tail != NULL | ||
| 84 | ? MAX (ARENA_CHUNK_GROWTH_FACTOR*chunk_size (arena->tail), size) | ||
| 85 | : MAX (ARENA_FIRST_CHUNK_SIZE, size); | ||
| 86 | |||
| 87 | struct arena_chunk *chunk = new_chunk (size, alignment); | ||
| 88 | |||
| 89 | if (arena->tail != NULL) { | ||
| 90 | arena->tail->next = chunk; | ||
| 91 | arena->tail = chunk; | ||
| 92 | } else { | ||
| 93 | arena->head = chunk; | ||
| 94 | arena->tail = chunk; | ||
| 95 | } | ||
| 96 | |||
| 97 | return chunk; | ||
| 98 | } | ||
| 99 | |||
| 100 | static void * | ||
| 101 | alignto (void *ptr, size_t alignment) | ||
| 102 | { | ||
| 103 | return (void *) ((ptrdiff_t) (ptr + alignment) & ~alignment); | ||
| 104 | } | ||
| 105 | |||
| 106 | void * | ||
| 107 | arena_reserve (struct arena *arena, size_t size, size_t alignment) | ||
| 108 | { | ||
| 109 | ASSERT (arena != NULL); | ||
| 110 | |||
| 111 | if (arena->tail != NULL) { | ||
| 112 | void *aligned_free = alignto (arena->tail->free, alignment); | ||
| 113 | if (CHUNK_END (arena->tail) - aligned_free >= (ssize_t) size) { | ||
| 114 | return aligned_free; | ||
| 115 | } | ||
| 116 | } | ||
| 117 | |||
| 118 | // FIXME(cmmm): use arena->tail->next when available | ||
| 119 | append_chunk (arena, size, alignment); | ||
| 120 | return alignto (arena->tail->free, alignment); | ||
| 121 | } | ||
| 122 | |||
| 123 | void * | ||
| 124 | arena_allocate (struct arena *arena, size_t size, size_t alignment) | ||
| 125 | { | ||
| 126 | ASSERT (arena != NULL); | ||
| 127 | |||
| 128 | void *ptr = arena_reserve (arena, size, alignment); | ||
| 129 | arena->tail->free = ptr + size; | ||
| 130 | return ptr; | ||
| 131 | } | ||
| 132 | |||
| 133 | void * | ||
| 134 | arena_allocate_fast (struct arena *arena, size_t size, size_t alignment) | ||
| 135 | { | ||
| 136 | ASSERT (arena != NULL); | ||
| 137 | ASSERT (arena->tail != NULL); | ||
| 138 | |||
| 139 | void *ptr = alignto (arena->tail->free, alignment); | ||
| 140 | arena->tail->free = ptr + size; | ||
| 141 | return ptr; | ||
| 142 | } | ||
| 143 | |||
| 144 | size_t | ||
| 145 | arena_used (const struct arena *arena) | ||
| 146 | { | ||
| 147 | ASSERT (arena != NULL); | ||
| 148 | |||
| 149 | size_t used = 0; | ||
| 150 | const struct arena_chunk *chunk; | ||
| 151 | for (chunk = arena->head; chunk; chunk = chunk->next) | ||
| 152 | used += chunk_size (chunk); | ||
| 153 | |||
| 154 | return used; | ||
| 155 | } | ||
| 156 | |||
| 157 | size_t | ||
| 158 | arena_room (const struct arena *arena, size_t alignment) | ||
| 159 | { | ||
| 160 | ASSERT (arena != NULL); | ||
| 161 | |||
| 162 | if (arena->tail == NULL) | ||
| 163 | return 0; | ||
| 164 | |||
| 165 | void *aligned_free = alignto (arena->tail->free, alignment); | ||
| 166 | return CHUNK_END (arena->tail) - aligned_free; | ||
| 167 | } | ||
| 168 | |||
| 169 | static void * | ||
| 170 | next_free (const struct arena_chunk *chunk, size_t alignment) | ||
| 171 | { | ||
| 172 | ASSERT (chunk != NULL); | ||
| 173 | |||
| 174 | void *aligned_free = alignto (chunk->free, alignment); | ||
| 175 | if (aligned_free > CHUNK_END (chunk)) | ||
| 176 | aligned_free = alignto (chunk->next->begin, alignment); | ||
| 177 | |||
| 178 | return aligned_free; | ||
| 179 | } | ||
| 180 | |||
| 181 | // REVIEW(cmmm): probably bugged, contract unclear | ||
| 182 | void * | ||
| 183 | arena_next_free (const struct arena *a, size_t alignment) | ||
| 184 | { | ||
| 185 | ASSERT (a != NULL); | ||
| 186 | ASSERT (a->tail != NULL); | ||
| 187 | |||
| 188 | return next_free (a->tail, alignment); | ||
| 189 | } | ||
| 190 | |||
| 191 | void * | ||
| 192 | arena_copy (struct arena *a, const void *from, | ||
| 193 | size_t size, size_t alignment) | ||
| 194 | { | ||
| 195 | ASSERT (a != NULL); | ||
| 196 | ASSERT (from != NULL); | ||
| 197 | |||
| 198 | void *ptr = arena_allocate (a, size, alignment); | ||
| 199 | memcpy (ptr, from, size); | ||
| 200 | return ptr; | ||
| 201 | } | ||
| 202 | |||
| 203 | void * | ||
| 204 | arena_copy_fast (struct arena *a, const void *from, | ||
| 205 | size_t size, size_t alignment) | ||
| 206 | { | ||
| 207 | ASSERT (a != NULL); | ||
| 208 | ASSERT (from != NULL); | ||
| 209 | |||
| 210 | void *ptr = arena_allocate_fast (a, size, alignment); | ||
| 211 | memcpy (ptr, from, size); | ||
| 212 | return ptr; | ||
| 213 | } | ||
| 214 | |||
| 215 | char * | ||
| 216 | arena_copy_cstr (struct arena *a, const char *cstr) | ||
| 217 | { | ||
| 218 | ASSERT (a != NULL); | ||
| 219 | ASSERT (cstr != NULL); | ||
| 220 | |||
| 221 | size_t size = strlen (cstr) + 1; | ||
| 222 | return arena_copy (a, cstr, size, 1); | ||
| 223 | } | ||
| 224 | |||
| 225 | void | ||
| 226 | arena_reset (struct arena *a) | ||
| 227 | { | ||
| 228 | ASSERT (a != NULL); | ||
| 229 | |||
| 230 | if (a->head == NULL) | ||
| 231 | return; | ||
| 232 | |||
| 233 | a->tail = a->head; | ||
| 234 | a->head->free = a->head->begin; | ||
| 235 | } | ||
| 236 | |||
| 237 | void * | ||
| 238 | arena_pop (struct arena *a, size_t size) | ||
| 239 | { | ||
| 240 | ASSERT (a != NULL); | ||
| 241 | |||
| 242 | // FIXME(cmmm): handle chunk boundaries | ||
| 243 | a->tail->free -= size; | ||
| 244 | |||
| 245 | ASSERT (a->tail->free >= a->tail->begin); | ||
| 246 | |||
| 247 | return a->tail->free; | ||
| 248 | } | ||
| 249 | |||
| 250 | struct arena_checkpoint | ||
| 251 | arena_checkpoint (struct arena *a, size_t alignment) | ||
| 252 | { | ||
| 253 | ASSERT (a != NULL); | ||
| 254 | |||
| 255 | if (a->tail == NULL) | ||
| 256 | arena_reserve (a, 0, alignment); | ||
| 257 | |||
| 258 | void *aligned_free = alignto (a->tail->free, alignment); | ||
| 259 | if (aligned_free > CHUNK_END (a->tail)) { | ||
| 260 | arena_reserve (a, 0, alignment); | ||
| 261 | aligned_free = alignto (a->tail->free, alignment); | ||
| 262 | } | ||
| 263 | |||
| 264 | struct arena_checkpoint cp = { | ||
| 265 | .tail = a->tail, | ||
| 266 | .free = a->tail->free, | ||
| 267 | .alignment = alignment, | ||
| 268 | }; | ||
| 269 | |||
| 270 | a->tail->free = aligned_free; | ||
| 271 | return cp; | ||
| 272 | } | ||
| 273 | |||
| 274 | void | ||
| 275 | arena_rollback_to (struct arena *a, struct arena_checkpoint cp) | ||
| 276 | { | ||
| 277 | ASSERT (a != NULL); | ||
| 278 | ASSERT (cp.tail != NULL); | ||
| 279 | ASSERT (cp.free != NULL); | ||
| 280 | |||
| 281 | a->tail = cp.tail; | ||
| 282 | a->tail->free = cp.free; | ||
| 283 | } | ||
| 284 | |||
| 285 | size_t | ||
| 286 | arena_checkpoint_size_from (struct arena_checkpoint cp) | ||
| 287 | { | ||
| 288 | ASSERT (cp.tail != NULL); | ||
| 289 | ASSERT (cp.free != NULL); | ||
| 290 | |||
| 291 | size_t size = cp.tail->free == cp.free | ||
| 292 | ? 0 : cp.tail->free - alignto (cp.free, cp.alignment); | ||
| 293 | for (struct arena_chunk *chunk = cp.tail; chunk; chunk = chunk->next) | ||
| 294 | size += chunk_size (chunk); | ||
| 295 | return size; | ||
| 296 | } | ||
| 297 | |||
| 298 | void * | ||
| 299 | arena_checkpoint_next_from (struct arena_checkpoint cp) | ||
| 300 | { | ||
| 301 | ASSERT (cp.tail != NULL); | ||
| 302 | ASSERT (cp.free != NULL); | ||
| 303 | |||
| 304 | void *aligned_free = alignto (cp.free, cp.alignment); | ||
| 305 | if (aligned_free > CHUNK_END (cp.tail)) | ||
| 306 | aligned_free = alignto (cp.tail->next->begin, cp.alignment); | ||
| 307 | |||
| 308 | return aligned_free; | ||
| 309 | } | ||
| 310 | |||
| 311 | void * | ||
| 312 | arena_coalesce_from (struct arena *a, struct arena_checkpoint cp) | ||
| 313 | { | ||
| 314 | ASSERT (a != NULL); | ||
| 315 | |||
| 316 | if (a->tail == cp.tail) // already coalesced | ||
| 317 | return cp.free; | ||
| 318 | |||
| 319 | size_t size = arena_checkpoint_size_from (cp); | ||
| 320 | return arena_coalesce_from_fast (a, cp, size); | ||
| 321 | } | ||
| 322 | |||
| 323 | void * | ||
| 324 | arena_coalesce_from_fast (struct arena *a, struct arena_checkpoint cp, | ||
| 325 | size_t size) | ||
| 326 | { | ||
| 327 | ASSERT (a != NULL); | ||
| 328 | |||
| 329 | if (a->tail == cp.tail) // already coalesced | ||
| 330 | return cp.free; | ||
| 331 | |||
| 332 | // make new chunk, add old chunks after it | ||
| 333 | struct arena_chunk *chunk = new_chunk (size, cp.alignment); | ||
| 334 | chunk->next = cp.free == cp.tail->begin ? cp.tail : cp.tail->next; | ||
| 335 | |||
| 336 | // copy old chunks into new chunk | ||
| 337 | // BUG(cmmm): check if data actually starts in checkpoints chunk | ||
| 338 | if (cp.free != cp.tail->free) { | ||
| 339 | size_t other_size = | ||
| 340 | alignto (cp.tail->free, cp.alignment) - arena_checkpoint_next_from (cp); | ||
| 341 | memcpy (chunk->free, cp.free, other_size); | ||
| 342 | chunk->free += other_size; | ||
| 343 | } | ||
| 344 | for (struct arena_chunk *other_chunk = cp.tail->next; | ||
| 345 | other_chunk; other_chunk = other_chunk->next) { | ||
| 346 | size_t other_size = chunk_used (other_chunk); | ||
| 347 | memcpy (chunk->free, other_chunk->begin, other_size); | ||
| 348 | chunk->free += other_size; | ||
| 349 | } | ||
| 350 | |||
| 351 | // link in new chunk | ||
| 352 | for (struct arena_chunk **other_chunk = &a->head; | ||
| 353 | *other_chunk; other_chunk = &(*other_chunk)->next) { | ||
| 354 | if (*other_chunk != chunk->next) | ||
| 355 | continue; | ||
| 356 | *other_chunk = chunk; | ||
| 357 | break; | ||
| 358 | } | ||
| 359 | |||
| 360 | return chunk->begin; | ||
| 361 | } | ||
| 362 | |||
| 363 | void * | ||
| 364 | arena_coalesce_from_into (struct arena *a, struct arena_checkpoint cp, | ||
| 365 | struct arena *into) | ||
| 366 | { | ||
| 367 | size_t size = arena_checkpoint_size_from (cp); | ||
| 368 | return arena_coalesce_from_into_fast (a, cp, into, size); | ||
| 369 | } | ||
| 370 | |||
| 371 | // TODO(cmmm): Handle the case where we can just reassign one chunk to | ||
| 372 | // the other arena. | ||
| 373 | void * | ||
| 374 | arena_coalesce_from_into_fast (struct arena *a, struct arena_checkpoint cp, | ||
| 375 | struct arena *into, size_t size) | ||
| 376 | { | ||
| 377 | ASSERT (a != NULL); | ||
| 378 | ASSERT (into != NULL); | ||
| 379 | |||
| 380 | void *ptr = arena_allocate (into, size, cp.alignment); | ||
| 381 | |||
| 382 | // copy chunks | ||
| 383 | void *free = ptr; | ||
| 384 | void *aligned_src = alignto (cp.free, cp.alignment); | ||
| 385 | if (aligned_src < cp.tail->free) { | ||
| 386 | size_t other_size = cp.tail->free - aligned_src; | ||
| 387 | memcpy (free, aligned_src, other_size); | ||
| 388 | free += other_size; | ||
| 389 | } | ||
| 390 | for (struct arena_chunk *other_chunk = cp.tail->next; | ||
| 391 | other_chunk != a->tail->next; other_chunk = other_chunk->next) { | ||
| 392 | size_t other_size = chunk_used (other_chunk); | ||
| 393 | memcpy (free, other_chunk->begin, other_size); | ||
| 394 | free += other_size; | ||
| 395 | } | ||
| 396 | |||
| 397 | arena_rollback_to (a, cp); | ||
| 398 | return ptr; | ||
| 399 | } | ||
| 400 | |||
| 401 | void | ||
| 402 | arena_trim (struct arena *a) | ||
| 403 | { | ||
| 404 | ASSERT (a != NULL); | ||
| 405 | |||
| 406 | if (a->tail == NULL) | ||
| 407 | return; | ||
| 408 | |||
| 409 | struct arena_chunk *chunk = a->tail->next; | ||
| 410 | while (chunk) { | ||
| 411 | struct arena_chunk *next = chunk->next; | ||
| 412 | FREE (chunk->begin); | ||
| 413 | chunk = next; | ||
| 414 | } | ||
| 415 | } | ||
| 416 | |||
| 417 | void | ||
| 418 | arena_free (struct arena *a) | ||
| 419 | { | ||
| 420 | ASSERT (a != NULL); | ||
| 421 | |||
| 422 | struct arena_chunk *chunk = a->head; | ||
| 423 | while (chunk) { | ||
| 424 | struct arena_chunk *next = chunk->next; | ||
| 425 | FREE (chunk->begin); | ||
| 426 | chunk = next; | ||
| 427 | } | ||
| 428 | |||
| 429 | a->head = NULL; | ||
| 430 | a->tail = NULL; | ||
| 431 | } | ||
| 432 | |||
| 433 | #ifndef ARENA_NO_STDIO | ||
| 434 | #include <stdio.h> | ||
| 435 | |||
| 436 | char * | ||
| 437 | arena_printf (struct arena *a, const char *format, ...) | ||
| 438 | { | ||
| 439 | ASSERT (a != NULL); | ||
| 440 | ASSERT (format != NULL); | ||
| 441 | |||
| 442 | va_list ap; | ||
| 443 | va_start (ap, format); | ||
| 444 | char *cstr = arena_vprintf (a, format, ap); | ||
| 445 | va_end (ap); | ||
| 446 | |||
| 447 | return cstr; | ||
| 448 | } | ||
| 449 | |||
| 450 | char * | ||
| 451 | arena_vprintf (struct arena *a, const char *format, va_list ap) | ||
| 452 | { | ||
| 453 | ASSERT (a != NULL); | ||
| 454 | ASSERT (format != NULL); | ||
| 455 | |||
| 456 | va_list ap_copy; | ||
| 457 | va_copy (ap_copy, ap); | ||
| 458 | int len = vsnprintf (NULL, 0, format, ap_copy); | ||
| 459 | va_end (ap_copy); | ||
| 460 | |||
| 461 | ASSERT (len >= 0); | ||
| 462 | char *cstr = ARENA_ALLOCATE_ARRAY (a, len + 1, char); | ||
| 463 | vsnprintf (cstr, len + 1, format, ap); | ||
| 464 | |||
| 465 | return cstr; | ||
| 466 | } | ||
| 467 | #endif | ||
| 468 | |||
| 469 | /// src/arena.c ends here | ||
diff --git a/src/arena.h b/src/arena.h new file mode 100644 index 0000000..b87be87 --- /dev/null +++ b/src/arena.h | |||
| @@ -0,0 +1,102 @@ | |||
| 1 | /// src/arena.h --- chunked arena allocator | ||
| 2 | // | ||
| 3 | // Copyright (C) 2026 by Martin Michalec <martin@michalec.dev> | ||
| 4 | // | ||
| 5 | // SPDX-License-Identifier: MIT | ||
| 6 | // | ||
| 7 | /// Commentary: | ||
| 8 | // | ||
| 9 | /// Code: | ||
| 10 | |||
| 11 | #ifndef INCLUDED_ARENA_H | ||
| 12 | #define INCLUDED_ARENA_H | ||
| 13 | |||
| 14 | #include <stddef.h> | ||
| 15 | |||
| 16 | // #define ARENA_NO_STDIO | ||
| 17 | |||
| 18 | #ifndef ARENA_FIRST_CHUNK_SIZE | ||
| 19 | # define ARENA_FIRST_CHUNK_SIZE (4 << 10) | ||
| 20 | #endif | ||
| 21 | |||
| 22 | #ifndef ARENA_CHUNK_GROWTH_FACTOR | ||
| 23 | # define ARENA_CHUNK_GROWTH_FACTOR 2 | ||
| 24 | #endif | ||
| 25 | |||
| 26 | struct arena_chunk { | ||
| 27 | struct arena_chunk *next; | ||
| 28 | void *begin; | ||
| 29 | void *free; | ||
| 30 | }; | ||
| 31 | |||
| 32 | struct arena { | ||
| 33 | struct arena_chunk *head; | ||
| 34 | struct arena_chunk *tail; | ||
| 35 | }; | ||
| 36 | |||
| 37 | struct arena_checkpoint { | ||
| 38 | struct arena_chunk *tail; | ||
| 39 | void *free; | ||
| 40 | size_t alignment; | ||
| 41 | }; | ||
| 42 | |||
| 43 | #ifndef ALIGNOF | ||
| 44 | # if _STDC_VERSION_ >= 202311L | ||
| 45 | # define ALIGNOF alignof | ||
| 46 | # elif _STDC_VERSION_ >= 201112L | ||
| 47 | # define ALIGNOF _Alignof | ||
| 48 | # else | ||
| 49 | # define ALIGNOF(O) offsetof (struct { char _; typeof (O) x; }, x) | ||
| 50 | # endif | ||
| 51 | #endif | ||
| 52 | |||
| 53 | #define ARENA_RESERVE( A, T) arena_reserve ((A), sizeof (T), ALIGNOF (T) - 1) | ||
| 54 | #define ARENA_RESERVE_ARRAY( A, N, T) arena_reserve ((A), (N)*sizeof (T), ALIGNOF (T) - 1) | ||
| 55 | #define ARENA_ALLOCATE( A, T) arena_allocate ((A), sizeof (T), ALIGNOF (T) - 1) | ||
| 56 | #define ARENA_ALLOCATE_ARRAY( A, N, T) arena_allocate ((A), (N)*sizeof (T), ALIGNOF (T) - 1) | ||
| 57 | #define ARENA_ALLOCATE_FAST( A, T) arena_allocate_fast ((A), sizeof (T), ALIGNOF (T) - 1) | ||
| 58 | #define ARENA_ALLOCATE_ARRAY_FAST(A, N, T) arena_allocate_fast ((A), (N)*sizeof (T), ALIGNOF (T) - 1) | ||
| 59 | #define ARENA_ZERO( A, T) arena_zero ((A), sizeof (T), ALIGNOF (T) - 1) | ||
| 60 | #define ARENA_ZERO_ARRAY( A, N, T) arena_zero ((A), (N)*sizeof (T), ALIGNOF (T) - 1) | ||
| 61 | void *arena_reserve (struct arena *, size_t size, size_t alignment); | ||
| 62 | void *arena_allocate (struct arena *, size_t size, size_t alignment); | ||
| 63 | void *arena_allocate_fast (struct arena *, size_t size, size_t alignment); | ||
| 64 | void *arena_zero (struct arena *, size_t size, size_t alignment); | ||
| 65 | |||
| 66 | size_t arena_used (const struct arena *); | ||
| 67 | size_t arena_room (const struct arena *, size_t alignment); | ||
| 68 | void *arena_next_free (const struct arena *, size_t alignment); | ||
| 69 | |||
| 70 | #define ARENA_COPY( A, F ) arena_copy ((A), &(F), sizeof ( F), ALIGNOF ( F) - 1) | ||
| 71 | #define ARENA_COPY_FAST( A, F ) arena_copy_fast ((A), &(F), sizeof ( F), ALIGNOF ( F) - 1) | ||
| 72 | #define ARENA_COPY_ARRAY(A, F, N) arena_copy ((A), (F), (N)*sizeof (*F), ALIGNOF (*F) - 1) | ||
| 73 | void *arena_copy (struct arena *, const void *, size_t size, size_t alignment); | ||
| 74 | void *arena_copy_fast (struct arena *, const void *, size_t size, size_t alignment); | ||
| 75 | char *arena_copy_cstr (struct arena *, const char *); | ||
| 76 | |||
| 77 | void arena_reset (struct arena *); | ||
| 78 | |||
| 79 | // NOTE(cmmm): doesn't handle alignments | ||
| 80 | void *arena_pop (struct arena *, size_t size); | ||
| 81 | |||
| 82 | struct arena_checkpoint arena_checkpoint (struct arena *, size_t alignment); | ||
| 83 | size_t arena_checkpoint_size_from (struct arena_checkpoint); | ||
| 84 | void *arena_checkpoint_next_from (struct arena_checkpoint); | ||
| 85 | void arena_rollback_to (struct arena *, struct arena_checkpoint); | ||
| 86 | void *arena_coalesce_from (struct arena *, struct arena_checkpoint); | ||
| 87 | void *arena_coalesce_from_fast (struct arena *, struct arena_checkpoint, size_t size); | ||
| 88 | void *arena_coalesce_from_into (struct arena *, struct arena_checkpoint, struct arena *); | ||
| 89 | void *arena_coalesce_from_into_fast (struct arena *, struct arena_checkpoint, struct arena *, size_t size); | ||
| 90 | |||
| 91 | void arena_trim (struct arena *); | ||
| 92 | void arena_free (struct arena *); | ||
| 93 | |||
| 94 | #ifndef ARENA_NO_STDIO | ||
| 95 | # include <stdarg.h> | ||
| 96 | char *arena_printf (struct arena *, const char *format, ...); | ||
| 97 | char *arena_vprintf (struct arena *, const char *format, va_list ap); | ||
| 98 | #endif | ||
| 99 | |||
| 100 | #endif // INCLUDED_ARENA_H | ||
| 101 | |||
| 102 | /// src/arena.h ends here | ||
diff --git a/src/compensations.c b/src/compensations.c new file mode 100644 index 0000000..5d87c22 --- /dev/null +++ b/src/compensations.c | |||
| @@ -0,0 +1,181 @@ | |||
| 1 | #include "compensations.h" | ||
| 2 | #include <math.h> | ||
| 3 | #include "da.h" | ||
| 4 | #include "transition.h" | ||
| 5 | |||
| 6 | static double | ||
| 7 | distance_to_change_speed (double v0, double v1, double vmax, double amax, double jmax) | ||
| 8 | { | ||
| 9 | double dv = fabs (v1 - v0); | ||
| 10 | if (dv <= 1e-12) | ||
| 11 | return 0; | ||
| 12 | |||
| 13 | double dv_crit = amax*amax/jmax; | ||
| 14 | double t = dv <= dv_crit ? 2*sqrt (dv/jmax) : dv/amax + amax/jmax; | ||
| 15 | |||
| 16 | return t*(v0 + v1)/2; | ||
| 17 | } | ||
| 18 | |||
| 19 | double vmax = 100/1.41421356237; | ||
| 20 | double amax = 800/1.41421356237; | ||
| 21 | double jmax = 16000/1.41421356237; | ||
| 22 | |||
| 23 | static struct compensation | ||
| 24 | synthesize_compensation_loop (const struct critical_point *cp) | ||
| 25 | { | ||
| 26 | struct compensation comp = { | ||
| 27 | .initial_position = cp->r, | ||
| 28 | .from = cp->left, | ||
| 29 | .to = cp->left, | ||
| 30 | .replace = CR_FROM_END_TO_END, | ||
| 31 | }; | ||
| 32 | |||
| 33 | // struct tr_transition tr; | ||
| 34 | // tr_build (&tr, cp->r, cp->r, cp->v_left, cp->v_right, vmax, amax, jmax); | ||
| 35 | // for (double s = 0.1; s < tr.length; s += 0.1) { | ||
| 36 | // struct tr_sample sample; | ||
| 37 | // tr_sample_at_s (&tr, s, &sample); | ||
| 38 | // DA_APPEND (comp.polyline, sample.r); | ||
| 39 | // } | ||
| 40 | |||
| 41 | double s0 = distance_to_change_speed (cp->left->f, 0, vmax, amax, jmax); | ||
| 42 | double s1 = distance_to_change_speed (0, cp->right->f, vmax, amax, jmax); | ||
| 43 | |||
| 44 | struct vec2 out = vec2_add (cp->r, vec2_scale (cp->t_left , s0)); | ||
| 45 | struct vec2 in = vec2_sub (cp->r, vec2_scale (cp->t_right, s1)); | ||
| 46 | |||
| 47 | DA_APPEND (comp.polyline, out); | ||
| 48 | DA_APPEND (comp.polyline, in ); | ||
| 49 | DA_APPEND (comp.polyline, cp->r); | ||
| 50 | |||
| 51 | return comp; | ||
| 52 | } | ||
| 53 | |||
| 54 | static struct compensation | ||
| 55 | synthesize_compensation_transfer (const struct critical_point *cp_out, | ||
| 56 | const struct critical_point *cp_in) | ||
| 57 | { | ||
| 58 | struct compensation comp = { | ||
| 59 | .initial_position = cp_out->r, | ||
| 60 | .from = cp_out->right, | ||
| 61 | .to = cp_in ->left, | ||
| 62 | .replace = CR_FROM_BEG_TO_END, | ||
| 63 | }; | ||
| 64 | |||
| 65 | // struct tr_transition tr; | ||
| 66 | // tr_build (&tr, cp_out->r, cp_in->r, cp_out->v_left, cp_in->v_right, vmax, amax, jmax); | ||
| 67 | // for (double s = 0.1; s < tr.length; s += 0.1) { | ||
| 68 | // struct tr_sample sample; | ||
| 69 | // tr_sample_at_s (&tr, s, &sample); | ||
| 70 | // DA_APPEND (comp.polyline, sample.r); | ||
| 71 | // } | ||
| 72 | |||
| 73 | double s0 = distance_to_change_speed (cp_out->left->f, 0, vmax, amax, jmax); | ||
| 74 | double s1 = distance_to_change_speed (0, cp_in->right->f, vmax, amax, jmax); | ||
| 75 | |||
| 76 | struct vec2 out = vec2_add (cp_out->r, vec2_scale (cp_out->t_left , s0)); | ||
| 77 | struct vec2 in = vec2_sub (cp_in ->r, vec2_scale (cp_in ->t_right, s1)); | ||
| 78 | |||
| 79 | DA_APPEND (comp.polyline, out); | ||
| 80 | DA_APPEND (comp.polyline, in ); | ||
| 81 | DA_APPEND (comp.polyline, cp_in->r); | ||
| 82 | |||
| 83 | return comp; | ||
| 84 | } | ||
| 85 | |||
| 86 | static struct compensation | ||
| 87 | synthesize_compensation_in (const struct critical_point *cp) | ||
| 88 | { | ||
| 89 | struct compensation comp = { | ||
| 90 | .initial_position = cp->s, | ||
| 91 | .from = cp->left, | ||
| 92 | .to = cp->left, | ||
| 93 | .replace = CR_FROM_BEG_TO_END, | ||
| 94 | }; | ||
| 95 | |||
| 96 | double s = distance_to_change_speed (0, cp->right->f, vmax, amax, jmax); | ||
| 97 | struct vec2 in = vec2_sub (cp->r, vec2_scale (cp->t_right, s)); | ||
| 98 | |||
| 99 | DA_APPEND (comp.polyline, in); | ||
| 100 | DA_APPEND (comp.polyline, cp->r); | ||
| 101 | |||
| 102 | return comp; | ||
| 103 | } | ||
| 104 | |||
| 105 | static struct compensation | ||
| 106 | synthesize_compensation_beg (const struct critical_point *cp) | ||
| 107 | { | ||
| 108 | struct compensation comp = { | ||
| 109 | .initial_position = cp->r, | ||
| 110 | .from = cp->right, | ||
| 111 | .to = cp->right, | ||
| 112 | .replace = CR_FROM_BEG_TO_BEG, | ||
| 113 | }; | ||
| 114 | |||
| 115 | double s = distance_to_change_speed (0, cp->right->f, vmax, amax, jmax); | ||
| 116 | struct vec2 in = vec2_sub (cp->r, vec2_scale (cp->t_right, s)); | ||
| 117 | |||
| 118 | DA_APPEND (comp.polyline, in); | ||
| 119 | DA_APPEND (comp.polyline, cp->r); | ||
| 120 | |||
| 121 | return comp; | ||
| 122 | } | ||
| 123 | |||
| 124 | static struct compensation | ||
| 125 | synthesize_compensation_end (const struct critical_point *cp) | ||
| 126 | { | ||
| 127 | struct compensation comp = { | ||
| 128 | .initial_position = cp->r, | ||
| 129 | .from = cp->left, | ||
| 130 | .to = cp->left, | ||
| 131 | .replace = CR_FROM_END_TO_END, | ||
| 132 | }; | ||
| 133 | |||
| 134 | double s = distance_to_change_speed (cp->left->f, 0, vmax, amax, jmax); | ||
| 135 | struct vec2 out = vec2_add (cp->r, vec2_scale (cp->t_left, s)); | ||
| 136 | |||
| 137 | DA_APPEND (comp.polyline, out); | ||
| 138 | |||
| 139 | return comp; | ||
| 140 | } | ||
| 141 | |||
| 142 | struct compensations | ||
| 143 | synthesize_compensations (const struct critical_points *cps) | ||
| 144 | { | ||
| 145 | struct compensations comps = {0}; | ||
| 146 | |||
| 147 | for (uint32_t i = 0; i < cps->count; ++i) { | ||
| 148 | struct critical_point *cp = &cps->items[i]; | ||
| 149 | struct compensation comp = {0}; | ||
| 150 | switch (cp->type) { | ||
| 151 | case CPT_IN: { | ||
| 152 | comp = synthesize_compensation_in (cp); | ||
| 153 | } break; | ||
| 154 | case CPT_OUT: { // TRANSFER | ||
| 155 | i += 1; | ||
| 156 | if (i == cps->count) { | ||
| 157 | comp = synthesize_compensation_end (cp); | ||
| 158 | } else { | ||
| 159 | struct critical_point *out = cp; | ||
| 160 | struct critical_point *in = &cps->items[i]; | ||
| 161 | ASSERT (in->type == CPT_IN); | ||
| 162 | comp = synthesize_compensation_transfer (out, in); | ||
| 163 | } | ||
| 164 | } break; | ||
| 165 | case CPT_LOOP: { | ||
| 166 | comp = synthesize_compensation_loop (cp); | ||
| 167 | } break; | ||
| 168 | case CPT_BEG: { | ||
| 169 | comp = synthesize_compensation_beg (cp); | ||
| 170 | } break; | ||
| 171 | case CPT_END: { | ||
| 172 | comp = synthesize_compensation_end (cp); | ||
| 173 | } break; | ||
| 174 | default: ASSERT (!"unexpected critical point type"); | ||
| 175 | } | ||
| 176 | |||
| 177 | DA_APPEND (comps, comp); | ||
| 178 | } | ||
| 179 | |||
| 180 | return comps; | ||
| 181 | } | ||
diff --git a/src/compensations.h b/src/compensations.h new file mode 100644 index 0000000..f034abc --- /dev/null +++ b/src/compensations.h | |||
| @@ -0,0 +1,42 @@ | |||
| 1 | #ifndef INCLUDED_COMPENSATIONS_H | ||
| 2 | #define INCLUDED_COMPENSATIONS_H | ||
| 3 | |||
| 4 | #include "critical_points.h" | ||
| 5 | |||
| 6 | enum compensation_replace { | ||
| 7 | CR_FROM_BEG_TO_BEG = 0b00, | ||
| 8 | CR_FROM_BEG_TO_END = 0b01, | ||
| 9 | CR_FROM_END_TO_BEG = 0b10, | ||
| 10 | CR_FROM_END_TO_END = 0b11, | ||
| 11 | }; | ||
| 12 | |||
| 13 | enum compensation_type { | ||
| 14 | CT_IN, | ||
| 15 | CT_OUT, | ||
| 16 | CT_TRANSFER, | ||
| 17 | CT_LOOP, | ||
| 18 | }; | ||
| 19 | |||
| 20 | struct polyline { | ||
| 21 | struct vec2 *items; | ||
| 22 | uint32_t count; | ||
| 23 | uint32_t capacity; | ||
| 24 | }; | ||
| 25 | |||
| 26 | struct compensation { | ||
| 27 | struct vec2 initial_position; | ||
| 28 | struct polyline polyline; | ||
| 29 | struct path_element *from; | ||
| 30 | struct path_element *to; | ||
| 31 | enum compensation_replace replace; | ||
| 32 | }; | ||
| 33 | |||
| 34 | struct compensations { | ||
| 35 | struct compensation *items; | ||
| 36 | uint32_t count; | ||
| 37 | uint32_t capacity; | ||
| 38 | }; | ||
| 39 | |||
| 40 | struct compensations synthesize_compensations (const struct critical_points *); | ||
| 41 | |||
| 42 | #endif // INCLUDED_COMPENSATIONS_H | ||
diff --git a/src/critical_points.c b/src/critical_points.c new file mode 100644 index 0000000..f11dfe7 --- /dev/null +++ b/src/critical_points.c | |||
| @@ -0,0 +1,126 @@ | |||
| 1 | #include "critical_points.h" | ||
| 2 | #include <math.h> | ||
| 3 | #include "da.h" | ||
| 4 | |||
| 5 | static double | ||
| 6 | angle_sweep (double a0, double a1, int ccw) | ||
| 7 | { | ||
| 8 | double sweep = a1 - a0; | ||
| 9 | |||
| 10 | if (ccw) { | ||
| 11 | while (sweep <= 0) | ||
| 12 | sweep += 2*M_PI; | ||
| 13 | } else { | ||
| 14 | while (sweep >= 0) | ||
| 15 | sweep -= 2*M_PI; | ||
| 16 | } | ||
| 17 | |||
| 18 | // NOTE(cmmm): might need some eps | ||
| 19 | |||
| 20 | return sweep; | ||
| 21 | } | ||
| 22 | |||
| 23 | |||
| 24 | static struct vec2 | ||
| 25 | tangent_beg (struct vec2 p0, struct path_element *pe) | ||
| 26 | { | ||
| 27 | ASSERT (pe); | ||
| 28 | |||
| 29 | struct vec2 p1 = { pe->x, pe->y }; | ||
| 30 | if (~pe->flags & PEF_ARC) | ||
| 31 | return vec2_unit (vec2_sub (p1, p0)); | ||
| 32 | |||
| 33 | struct vec2 c = { pe->i, pe->j }; | ||
| 34 | double a0 = vec2_angle0 (vec2_sub (p0, c)); | ||
| 35 | double a1 = vec2_angle0 (vec2_sub (p1, c)); | ||
| 36 | double sweep = angle_sweep (a0, a1, pe->flags & PEF_CCW); | ||
| 37 | double sgn = sweep < 0 ? -1 : 1; | ||
| 38 | double a = a0; | ||
| 39 | return (struct vec2) { -sgn*sin (a), sgn*cos (a) }; | ||
| 40 | } | ||
| 41 | |||
| 42 | static struct vec2 | ||
| 43 | tangent_end (struct vec2 p0, struct path_element *pe) | ||
| 44 | { | ||
| 45 | ASSERT (pe); | ||
| 46 | |||
| 47 | struct vec2 p1 = { pe->x, pe->y }; | ||
| 48 | if (~pe->flags & PEF_ARC) | ||
| 49 | return vec2_unit (vec2_sub (p1, p0)); | ||
| 50 | |||
| 51 | struct vec2 c = { pe->i, pe->j }; | ||
| 52 | double a0 = vec2_angle0 (vec2_sub (p0, c)); | ||
| 53 | double a1 = vec2_angle0 (vec2_sub (p1, c)); | ||
| 54 | double sweep = angle_sweep (a0, a1, pe->flags & PEF_CCW); | ||
| 55 | double sgn = sweep < 0 ? -1 : 1; | ||
| 56 | double a = a0 + sweep; | ||
| 57 | return (struct vec2) { -sgn*sin (a), sgn*cos (a) }; | ||
| 58 | } | ||
| 59 | |||
| 60 | struct critical_points | ||
| 61 | find_critical_points (const struct path *path) | ||
| 62 | { | ||
| 63 | struct critical_points cps = {0}; | ||
| 64 | |||
| 65 | if (path->count == 0) | ||
| 66 | return cps; | ||
| 67 | |||
| 68 | struct critical_point cp = { | ||
| 69 | .right = &path->items[0], | ||
| 70 | .r = { | ||
| 71 | .x = path->initial_x, | ||
| 72 | .y = path->initial_y, | ||
| 73 | } | ||
| 74 | }; | ||
| 75 | if (~cp.right->flags & PEF_TRAVERSING) { | ||
| 76 | cp.type = CPT_BEG; | ||
| 77 | cp.t_right = tangent_beg (cp.r, cp.right); | ||
| 78 | DA_APPEND (cps, cp); | ||
| 79 | } | ||
| 80 | |||
| 81 | struct vec2 beg = cp.r; | ||
| 82 | for (uint32_t i = 1; i < path->count; ++i) { | ||
| 83 | cp.left = cp.right; | ||
| 84 | cp.right = &path->items[i]; | ||
| 85 | |||
| 86 | cp.s = beg; | ||
| 87 | cp.r.x = cp.left->x; | ||
| 88 | cp.r.y = cp.left->y; | ||
| 89 | |||
| 90 | if (cp.left ->flags & PEF_TRAVERSING && | ||
| 91 | cp.right->flags & PEF_TRAVERSING) { | ||
| 92 | goto next; | ||
| 93 | } | ||
| 94 | |||
| 95 | struct vec2 end = { | ||
| 96 | .x = cp.right->x, | ||
| 97 | .y = cp.right->y, | ||
| 98 | }; | ||
| 99 | |||
| 100 | cp.t_left = tangent_end (beg, cp.left ); | ||
| 101 | cp.t_right = tangent_beg (cp.r, cp.right); | ||
| 102 | |||
| 103 | double min_turn = M_PI/16; | ||
| 104 | double turn = vec2_angle (cp.t_left, cp.t_right); | ||
| 105 | |||
| 106 | if (cp.left ->flags & PEF_TRAVERSING) cp.type = CPT_IN; | ||
| 107 | else if (cp.right->flags & PEF_TRAVERSING) cp.type = CPT_OUT; | ||
| 108 | else if (turn < min_turn) goto next; | ||
| 109 | else cp.type = CPT_LOOP; | ||
| 110 | |||
| 111 | DA_APPEND (cps, cp); | ||
| 112 | next: | ||
| 113 | beg = cp.r; | ||
| 114 | } | ||
| 115 | |||
| 116 | cp.left = &DA_LAST (*path); | ||
| 117 | if (~cp.left->flags & PEF_TRAVERSING) { | ||
| 118 | cp.type = CPT_END; | ||
| 119 | cp.r.x = cp.left->x; | ||
| 120 | cp.r.y = cp.left->y; | ||
| 121 | cp.t_left = tangent_end (beg, cp.left); | ||
| 122 | DA_APPEND (cps, cp); | ||
| 123 | } | ||
| 124 | |||
| 125 | return cps; | ||
| 126 | } | ||
diff --git a/src/critical_points.h b/src/critical_points.h new file mode 100644 index 0000000..b7e8cbb --- /dev/null +++ b/src/critical_points.h | |||
| @@ -0,0 +1,35 @@ | |||
| 1 | #ifndef INCLUDED_CRITICAL_POINTS_H | ||
| 2 | #define INCLUDED_CRITICAL_POINTS_H | ||
| 3 | |||
| 4 | #include "path.h" | ||
| 5 | #include "vec2.h" | ||
| 6 | |||
| 7 | enum critical_point_type { | ||
| 8 | CPT_IN, | ||
| 9 | CPT_OUT, | ||
| 10 | CPT_LOOP, | ||
| 11 | CPT_BEG, | ||
| 12 | CPT_END, | ||
| 13 | }; | ||
| 14 | |||
| 15 | struct critical_point { | ||
| 16 | enum critical_point_type type; | ||
| 17 | |||
| 18 | struct path_element *left; | ||
| 19 | struct path_element *right; | ||
| 20 | |||
| 21 | struct vec2 s; | ||
| 22 | struct vec2 r; | ||
| 23 | struct vec2 t_left; | ||
| 24 | struct vec2 t_right; | ||
| 25 | }; | ||
| 26 | |||
| 27 | struct critical_points { | ||
| 28 | struct critical_point *items; | ||
| 29 | uint32_t count; | ||
| 30 | uint32_t capacity; | ||
| 31 | }; | ||
| 32 | |||
| 33 | struct critical_points find_critical_points (const struct path *); | ||
| 34 | |||
| 35 | #endif // INCLUDED_CRITICAL_POINTS_H | ||
diff --git a/src/da.h b/src/da.h new file mode 100644 index 0000000..8eb0237 --- /dev/null +++ b/src/da.h | |||
| @@ -0,0 +1,68 @@ | |||
| 1 | // src/da.h --- Dynamic Array | ||
| 2 | #ifndef INCLUDED_DA_H | ||
| 3 | #define INCLUDED_DA_H | ||
| 4 | |||
| 5 | #ifndef DA_REALLOC | ||
| 6 | void *realloc (void *_ptr, size_t _size); | ||
| 7 | #define DA_REALLOC realloc | ||
| 8 | #endif | ||
| 9 | |||
| 10 | #ifndef DA_ASSERT | ||
| 11 | #include <assert.h> | ||
| 12 | #define DA_ASSERT assert | ||
| 13 | #endif | ||
| 14 | |||
| 15 | #ifndef DA_INIT_CAP | ||
| 16 | #define DA_INIT_CAP 256 | ||
| 17 | #endif | ||
| 18 | |||
| 19 | #define DA_ENSURE_CAPACITY(DA, COUNT) \ | ||
| 20 | ({ \ | ||
| 21 | if ((DA).count + (COUNT) > (DA).capacity) { \ | ||
| 22 | if ((DA).capacity == 0) \ | ||
| 23 | (DA).capacity = DA_INIT_CAP; \ | ||
| 24 | while ((DA).count + (COUNT) > (DA).capacity) \ | ||
| 25 | (DA).capacity *= 2; \ | ||
| 26 | (DA).items = DA_REALLOC ((DA).items, \ | ||
| 27 | (DA).capacity*sizeof (*(DA).items)); \ | ||
| 28 | DA_ASSERT((DA).items); \ | ||
| 29 | } \ | ||
| 30 | }) | ||
| 31 | |||
| 32 | #define DA_SHRINK(DA) \ | ||
| 33 | ({ \ | ||
| 34 | (DA).capacity = (DA).count; \ | ||
| 35 | (DA).items = REALLOC((DA).items, \ | ||
| 36 | (DA).capacity * \ | ||
| 37 | sizeof (*(DA).items)); \ | ||
| 38 | DA_ASSERT((DA).items); \ | ||
| 39 | }) | ||
| 40 | |||
| 41 | #define DA_APPEND(DA, ITEM) \ | ||
| 42 | ({ \ | ||
| 43 | DA_ENSURE_CAPACITY((DA), 1); \ | ||
| 44 | (DA).items[(DA).count++] = (ITEM); \ | ||
| 45 | }) | ||
| 46 | |||
| 47 | #define DA_APPEND_MANY(DA, NEW_ITEMS, NEW_ITEMS_COUNT) \ | ||
| 48 | ({ \ | ||
| 49 | DA_ENSURE_CAPACITY ((DA), (NEW_ITEMS_COUNT)); \ | ||
| 50 | memcpy ((DA).items + (DA).count, (NEW_ITEMS), \ | ||
| 51 | (NEW_ITEMS_COUNT)*sizeof (*(DA).items)); \ | ||
| 52 | (DA).count += (NEW_ITEMS_COUNT); \ | ||
| 53 | }) | ||
| 54 | |||
| 55 | #define DA_FIRST(DA) (DA).items[0] | ||
| 56 | #define DA_LAST(DA) (DA).items[(DA).count - 1] | ||
| 57 | |||
| 58 | #define DA_RESET(DA) ({ (DA).count = 0; }) | ||
| 59 | |||
| 60 | #define DA_FREE(DA) (void) DA_REALLOC ((DA).items, 0) | ||
| 61 | |||
| 62 | #define DA_FOR_EACH(ITEM, DA) for ( \ | ||
| 63 | typeof ((DA).items) ITEM = (DA).items; \ | ||
| 64 | ITEM < (DA).items + (DA).count; ++ITEM) | ||
| 65 | |||
| 66 | #endif // INCLUDED_DA_H | ||
| 67 | |||
| 68 | // src/da.h ends here | ||
diff --git a/src/diagnose.c b/src/diagnose.c new file mode 100644 index 0000000..041019a --- /dev/null +++ b/src/diagnose.c | |||
| @@ -0,0 +1,123 @@ | |||
| 1 | #include <errno.h> | ||
| 2 | #include <math.h> | ||
| 3 | #include <stdio.h> | ||
| 4 | #include <stdlib.h> | ||
| 5 | #include <fcntl.h> | ||
| 6 | #include <unistd.h> | ||
| 7 | |||
| 8 | #include "utils.h" | ||
| 9 | #include "rs274ngc_lexer.h" | ||
| 10 | #include "rs274ngc_cst.h" | ||
| 11 | #include "path.h" | ||
| 12 | #include "motion_planner.h" | ||
| 13 | #include "diagnostics.h" | ||
| 14 | |||
| 15 | static void | ||
| 16 | usage (const char *progname) | ||
| 17 | { | ||
| 18 | fprintf (stderr, "usage: %s INPUT.ngc OUTPUT.csv [dt]\n", progname); | ||
| 19 | } | ||
| 20 | |||
| 21 | static double | ||
| 22 | parse_dt (const char *s) | ||
| 23 | { | ||
| 24 | char *end = NULL; | ||
| 25 | errno = 0; | ||
| 26 | double dt = strtod (s, &end); | ||
| 27 | |||
| 28 | if (errno || end == s || *end != '\0' || !(dt > 0.0) || !isfinite (dt)) { | ||
| 29 | fprintf (stderr, "invalid dt: %s\n", s); | ||
| 30 | exit (EXIT_FAILURE); | ||
| 31 | } | ||
| 32 | |||
| 33 | return dt; | ||
| 34 | } | ||
| 35 | |||
| 36 | static struct path | ||
| 37 | read_path_from_file (struct arena *a, | ||
| 38 | struct arena *t, | ||
| 39 | const char *filename) | ||
| 40 | { | ||
| 41 | int fd = open (filename, O_RDONLY); | ||
| 42 | if (fd < 0) { | ||
| 43 | perror (filename); | ||
| 44 | exit (EXIT_FAILURE); | ||
| 45 | } | ||
| 46 | |||
| 47 | struct sv rs274ngc = read_until_eof (a, fd); | ||
| 48 | close (fd); | ||
| 49 | |||
| 50 | rs274ngc_lexer_compile_regexes (); | ||
| 51 | struct rs274ngc_lexer lexer = rs274ngc_lexer_from_sv (rs274ngc, filename); | ||
| 52 | |||
| 53 | struct rs274ngc_cst_parser parser = { | ||
| 54 | .lexer = &lexer, | ||
| 55 | .output = a, | ||
| 56 | .temporary = t, | ||
| 57 | }; | ||
| 58 | |||
| 59 | return build_path (parser); | ||
| 60 | } | ||
| 61 | |||
| 62 | int | ||
| 63 | main (int argc, char **argv) | ||
| 64 | { | ||
| 65 | progname = argv[0]; | ||
| 66 | |||
| 67 | if (argc != 3 && argc != 4) { | ||
| 68 | usage (argv[0]); | ||
| 69 | return EXIT_FAILURE; | ||
| 70 | } | ||
| 71 | |||
| 72 | const char *input_filename = argv[1]; | ||
| 73 | const char *output_filename = argv[2]; | ||
| 74 | double dt = argc == 4 ? parse_dt (argv[3]) : 0.001; | ||
| 75 | |||
| 76 | struct arena a = {0}; | ||
| 77 | struct arena t = {0}; | ||
| 78 | |||
| 79 | struct path path = read_path_from_file (&a, &t, input_filename); | ||
| 80 | if (path.count == 0u) { | ||
| 81 | fprintf (stderr, "%s: empty path\n", input_filename); | ||
| 82 | return EXIT_FAILURE; | ||
| 83 | } | ||
| 84 | |||
| 85 | struct mp_limits limits = { | ||
| 86 | .vmax = 80, | ||
| 87 | .rapid_vmax = 125, | ||
| 88 | .amax = 800, | ||
| 89 | .jmax = 16000, | ||
| 90 | .corner_tol = .05, | ||
| 91 | .min_segment_len = 1e-6, | ||
| 92 | .default_feed = 50, | ||
| 93 | |||
| 94 | .straight_angle_tol = 1e-5, | ||
| 95 | .stop_angle = M_PI/16, | ||
| 96 | .corner_speed_deadband = .02, | ||
| 97 | |||
| 98 | .curvature_blend_len = 0.05, | ||
| 99 | }; | ||
| 100 | |||
| 101 | struct motion_plan plan = {0}; | ||
| 102 | int rc = mp_plan_build (&path, 0.0, 0.0, &limits, &plan); | ||
| 103 | if (rc != MP_OK) { | ||
| 104 | fprintf (stderr, "%s: mp_plan_build failed: %d\n", input_filename, rc); | ||
| 105 | return EXIT_FAILURE; | ||
| 106 | } | ||
| 107 | |||
| 108 | FILE *csv = fopen (output_filename, "w"); | ||
| 109 | if (!csv) { | ||
| 110 | perror (output_filename); | ||
| 111 | mp_plan_free (&plan); | ||
| 112 | return EXIT_FAILURE; | ||
| 113 | } | ||
| 114 | |||
| 115 | motion_diag_write_csv (&plan, dt, csv, 1); | ||
| 116 | fclose (csv); | ||
| 117 | |||
| 118 | fprintf (stderr, "%s: total_time=%g s, total_length=%g mm, dt=%g s\n", | ||
| 119 | output_filename, plan.total_time, plan.total_length, dt); | ||
| 120 | |||
| 121 | mp_plan_free (&plan); | ||
| 122 | return EXIT_SUCCESS; | ||
| 123 | } | ||
diff --git a/src/diagnostics.c b/src/diagnostics.c new file mode 100644 index 0000000..458a0ad --- /dev/null +++ b/src/diagnostics.c | |||
| @@ -0,0 +1,84 @@ | |||
| 1 | #include "diagnostics.h" | ||
| 2 | |||
| 3 | #include <math.h> | ||
| 4 | #include <stdint.h> | ||
| 5 | |||
| 6 | static double | ||
| 7 | diag_segment_v_cmd (const struct motion_plan *plan, | ||
| 8 | const struct mp_sample *sample) | ||
| 9 | { | ||
| 10 | if (!plan || !sample) | ||
| 11 | return 0.0; | ||
| 12 | |||
| 13 | if (sample->segment_index >= plan->segment_count) | ||
| 14 | return 0.0; | ||
| 15 | |||
| 16 | return plan->segments[sample->segment_index].v_nominal; | ||
| 17 | } | ||
| 18 | |||
| 19 | static void | ||
| 20 | diag_write_sample (const struct motion_plan *plan, | ||
| 21 | const struct mp_sample *sample, | ||
| 22 | FILE *out) | ||
| 23 | { | ||
| 24 | int is_traverse = (sample->source_flags & PEF_TRAVERSING) != 0; | ||
| 25 | int is_work = !is_traverse; | ||
| 26 | |||
| 27 | double v_cmd = diag_segment_v_cmd (plan, sample); | ||
| 28 | |||
| 29 | /* На G0 ошибка скорости по определению равна нулю. */ | ||
| 30 | double v_ref = is_traverse ? sample->v : v_cmd; | ||
| 31 | double v_err = sample->v - v_ref; | ||
| 32 | double v_err_abs = fabs (v_err); | ||
| 33 | |||
| 34 | fprintf (out, | ||
| 35 | "%.9f,%.9f,%.9f,%.9f,%.9f,%.9f,%.9f,%.9f,%.9f," | ||
| 36 | "%.9f,%.9f,%.9f,%.9f,%d,%d,%u,%u,%d\n", | ||
| 37 | sample->t, | ||
| 38 | sample->s, | ||
| 39 | sample->p.x, | ||
| 40 | sample->p.y, | ||
| 41 | sample->v, | ||
| 42 | v_cmd, | ||
| 43 | v_ref, | ||
| 44 | v_err, | ||
| 45 | v_err_abs, | ||
| 46 | sample->j_t, | ||
| 47 | sample->j_abs, | ||
| 48 | sample->jerk.x, | ||
| 49 | sample->jerk.y, | ||
| 50 | is_work, | ||
| 51 | is_traverse, | ||
| 52 | sample->segment_index, | ||
| 53 | sample->source_index, | ||
| 54 | sample->source_flags); | ||
| 55 | } | ||
| 56 | |||
| 57 | void | ||
| 58 | motion_diag_write_csv (const struct motion_plan *plan, | ||
| 59 | double dt, | ||
| 60 | FILE *out, | ||
| 61 | int write_header) | ||
| 62 | { | ||
| 63 | if (!plan || !out || !(dt > 0.0) || !isfinite (dt)) | ||
| 64 | return; | ||
| 65 | |||
| 66 | if (write_header) { | ||
| 67 | fputs ("t,s,x,y,v,v_cmd,v_ref,v_err,v_err_abs," | ||
| 68 | "j_t,j_abs,jx,jy,is_work,is_traverse," | ||
| 69 | "segment_index,source_index,source_flags\n", out); | ||
| 70 | } | ||
| 71 | |||
| 72 | if (plan->segment_count == 0u) | ||
| 73 | return; | ||
| 74 | |||
| 75 | for (double t = 0.0; t < plan->total_time; t += dt) { | ||
| 76 | struct mp_sample sample; | ||
| 77 | mp_plan_sample (plan, t, &sample); | ||
| 78 | diag_write_sample (plan, &sample, out); | ||
| 79 | } | ||
| 80 | |||
| 81 | struct mp_sample last; | ||
| 82 | mp_plan_sample (plan, plan->total_time, &last); | ||
| 83 | diag_write_sample (plan, &last, out); | ||
| 84 | } | ||
diff --git a/src/diagnostics.h b/src/diagnostics.h new file mode 100644 index 0000000..501abe6 --- /dev/null +++ b/src/diagnostics.h | |||
| @@ -0,0 +1,19 @@ | |||
| 1 | #ifndef INCLUDED_DIAGNOSTICS_H | ||
| 2 | #define INCLUDED_DIAGNOSTICS_H | ||
| 3 | |||
| 4 | #include <stdio.h> | ||
| 5 | #include "motion_planner.h" | ||
| 6 | |||
| 7 | /* | ||
| 8 | * CSV-выгрузка кинематической диагностики по времени. | ||
| 9 | * | ||
| 10 | * Скоростная ошибка считается только на рабочих участках. Для G0 она | ||
| 11 | * принудительно равна 0, потому что rapid-перемещения не задают качество | ||
| 12 | * обработки. | ||
| 13 | */ | ||
| 14 | void motion_diag_write_csv (const struct motion_plan *plan, | ||
| 15 | double dt, | ||
| 16 | FILE *out, | ||
| 17 | int write_header); | ||
| 18 | |||
| 19 | #endif // INCLUDED_DIAGNOSTICS_H | ||
diff --git a/src/generator.c b/src/generator.c new file mode 100644 index 0000000..ac98b5b --- /dev/null +++ b/src/generator.c | |||
| @@ -0,0 +1,95 @@ | |||
| 1 | #include "generator.h" | ||
| 2 | #include "da.h" | ||
| 3 | #include <stdio.h> | ||
| 4 | |||
| 5 | static struct replacement | ||
| 6 | generate_replacement (struct arena *a, const struct compensation *comp) | ||
| 7 | { | ||
| 8 | ASSERT (comp->polyline.count > 0); | ||
| 9 | |||
| 10 | struct replacement rep = {0}; | ||
| 11 | |||
| 12 | int len = 1; | ||
| 13 | for (uint32_t i = 0; i < comp->polyline.count; ++i) { | ||
| 14 | struct vec2 to = comp->polyline.items[i]; | ||
| 15 | int n = snprintf (NULL, 0, "G0 X%f Y%f\n", to.x, to.y); | ||
| 16 | len += n; | ||
| 17 | } | ||
| 18 | |||
| 19 | char *head = arena_allocate (a, len, 1); | ||
| 20 | rep.new.beg = head; | ||
| 21 | rep.new.end = head + len - 1; | ||
| 22 | |||
| 23 | for (uint32_t i = 0; i < comp->polyline.count; ++i) { | ||
| 24 | struct vec2 to = comp->polyline.items[i]; | ||
| 25 | int n = snprintf (head, len, "G0 X%f Y%f\n", to.x, to.y); | ||
| 26 | head += n; | ||
| 27 | len -= n; | ||
| 28 | } | ||
| 29 | |||
| 30 | switch (comp->replace) { | ||
| 31 | case CR_FROM_BEG_TO_BEG: { | ||
| 32 | rep.old.beg = comp->from->line.beg; | ||
| 33 | rep.old.end = comp->to ->line.beg; | ||
| 34 | } break; | ||
| 35 | case CR_FROM_BEG_TO_END: { | ||
| 36 | rep.old.beg = comp->from->line.beg; | ||
| 37 | rep.old.end = comp->to ->line.end; | ||
| 38 | } break; | ||
| 39 | case CR_FROM_END_TO_BEG: { | ||
| 40 | rep.old.beg = comp->from->line.end; | ||
| 41 | rep.old.end = comp->to ->line.beg; | ||
| 42 | } break; | ||
| 43 | case CR_FROM_END_TO_END: { | ||
| 44 | rep.old.beg = comp->from->line.end; | ||
| 45 | rep.old.end = comp->to ->line.end; | ||
| 46 | } break; | ||
| 47 | } | ||
| 48 | |||
| 49 | return rep; | ||
| 50 | } | ||
| 51 | |||
| 52 | struct replacements | ||
| 53 | generate_replacements (struct arena *a, const struct compensations *comps) | ||
| 54 | { | ||
| 55 | struct replacements reps = {0}; | ||
| 56 | |||
| 57 | for (uint32_t i = 0; i < comps->count; ++i) { | ||
| 58 | const struct compensation *comp = &comps->items[i]; | ||
| 59 | DA_APPEND (reps, generate_replacement (a, comp)); | ||
| 60 | } | ||
| 61 | |||
| 62 | return reps; | ||
| 63 | } | ||
| 64 | |||
| 65 | void | ||
| 66 | write_code_with_replacements (int fd, struct sv orig, | ||
| 67 | const struct replacements *reps) | ||
| 68 | { | ||
| 69 | const char *head = orig.beg; | ||
| 70 | for (uint32_t i = 0; i < reps->count; ++i) { | ||
| 71 | const struct replacement *rep = &reps->items[i]; | ||
| 72 | struct sv before = { | ||
| 73 | .beg = head, | ||
| 74 | .end = rep->old.beg, | ||
| 75 | }; | ||
| 76 | head = rep->old.end; | ||
| 77 | // puts ("(v orig --)"); | ||
| 78 | printf (SV_FMT, SV_FMTA (before)); | ||
| 79 | // puts ("(^ orig --)"); | ||
| 80 | // puts ("(v old --)"); | ||
| 81 | // printf (SV_FMT, SV_FMTA (rep->old)); | ||
| 82 | // puts ("(^ old --)"); | ||
| 83 | // puts ("(v new --)"); | ||
| 84 | printf (SV_FMT, SV_FMTA (rep->new)); | ||
| 85 | // puts ("(^ new --)"); | ||
| 86 | } | ||
| 87 | |||
| 88 | struct sv before = { | ||
| 89 | .beg = head, | ||
| 90 | .end = orig.end, | ||
| 91 | }; | ||
| 92 | // puts ("(v last orig --)"); | ||
| 93 | printf (SV_FMT, SV_FMTA (before)); | ||
| 94 | // puts ("(^ last orig --)"); | ||
| 95 | } | ||
diff --git a/src/generator.h b/src/generator.h new file mode 100644 index 0000000..cab8687 --- /dev/null +++ b/src/generator.h | |||
| @@ -0,0 +1,21 @@ | |||
| 1 | #ifndef INCLUDED_GENERATOR_H | ||
| 2 | #define INCLUDED_GENERATOR_H | ||
| 3 | |||
| 4 | #include "compensations.h" | ||
| 5 | #include "arena.h" | ||
| 6 | |||
| 7 | struct replacement { | ||
| 8 | struct sv old; // replace this | ||
| 9 | struct sv new; // with this | ||
| 10 | }; | ||
| 11 | |||
| 12 | struct replacements { | ||
| 13 | struct replacement *items; | ||
| 14 | uint32_t count; | ||
| 15 | uint32_t capacity; | ||
| 16 | }; | ||
| 17 | |||
| 18 | struct replacements generate_replacements (struct arena *, const struct compensations *); | ||
| 19 | void write_code_with_replacements (int fd, struct sv original, const struct replacements *); | ||
| 20 | |||
| 21 | #endif // INCLUDED_GENERATOR_H | ||
diff --git a/src/motion_planner.c b/src/motion_planner.c new file mode 100644 index 0000000..313e3e9 --- /dev/null +++ b/src/motion_planner.c | |||
| @@ -0,0 +1,1245 @@ | |||
| 1 | #include "motion_planner.h" | ||
| 2 | |||
| 3 | #include <stdlib.h> | ||
| 4 | #include <string.h> | ||
| 5 | #include <math.h> | ||
| 6 | #include <float.h> | ||
| 7 | |||
| 8 | static double | ||
| 9 | mp_clamp (double x, double lo, double hi) | ||
| 10 | { | ||
| 11 | return x < lo ? lo : (x > hi ? hi : x); | ||
| 12 | } | ||
| 13 | |||
| 14 | static int | ||
| 15 | mp_finite_pos (double x) | ||
| 16 | { | ||
| 17 | return isfinite (x) && x > 0.0; | ||
| 18 | } | ||
| 19 | |||
| 20 | static int | ||
| 21 | mp_limits_valid (const struct mp_limits *l) | ||
| 22 | { | ||
| 23 | return l && | ||
| 24 | mp_finite_pos (l->vmax) && | ||
| 25 | mp_finite_pos (l->amax) && | ||
| 26 | mp_finite_pos (l->jmax) && | ||
| 27 | isfinite (l->rapid_vmax) && | ||
| 28 | isfinite (l->corner_tol) && | ||
| 29 | isfinite (l->min_segment_len) && | ||
| 30 | mp_finite_pos (l->default_feed) && | ||
| 31 | isfinite (l->straight_angle_tol) && | ||
| 32 | isfinite (l->stop_angle) && | ||
| 33 | isfinite (l->corner_speed_deadband) && | ||
| 34 | isfinite (l->curvature_blend_len); | ||
| 35 | } | ||
| 36 | |||
| 37 | static double | ||
| 38 | mp_rapid_vmax (const struct mp_limits *l) | ||
| 39 | { | ||
| 40 | return l->rapid_vmax > 0.0 ? l->rapid_vmax : l->vmax; | ||
| 41 | } | ||
| 42 | |||
| 43 | static double | ||
| 44 | mp_straight_angle_tol (const struct mp_limits *l) | ||
| 45 | { | ||
| 46 | return l->straight_angle_tol > 0.0 ? l->straight_angle_tol : 1e-5; | ||
| 47 | } | ||
| 48 | |||
| 49 | static double | ||
| 50 | mp_stop_angle (const struct mp_limits *l) | ||
| 51 | { | ||
| 52 | if (l->stop_angle > 0.0 && l->stop_angle < M_PI) | ||
| 53 | return l->stop_angle; | ||
| 54 | |||
| 55 | return M_PI; | ||
| 56 | } | ||
| 57 | |||
| 58 | static double | ||
| 59 | mp_corner_deadband (const struct mp_limits *l) | ||
| 60 | { | ||
| 61 | return l->corner_speed_deadband > 0.0 ? l->corner_speed_deadband : 0.0; | ||
| 62 | } | ||
| 63 | |||
| 64 | static double | ||
| 65 | mp_min_segment_len (const struct mp_limits *l) | ||
| 66 | { | ||
| 67 | return l->min_segment_len > 0.0 ? l->min_segment_len : 1e-8; | ||
| 68 | } | ||
| 69 | |||
| 70 | static struct mp_vec2 | ||
| 71 | mp_vec2 (double x, double y) | ||
| 72 | { | ||
| 73 | struct mp_vec2 v; | ||
| 74 | v.x = x; | ||
| 75 | v.y = y; | ||
| 76 | return v; | ||
| 77 | } | ||
| 78 | |||
| 79 | static struct mp_vec2 | ||
| 80 | mp_vec2_add (struct mp_vec2 a, struct mp_vec2 b) | ||
| 81 | { | ||
| 82 | return mp_vec2 (a.x + b.x, a.y + b.y); | ||
| 83 | } | ||
| 84 | |||
| 85 | static struct mp_vec2 | ||
| 86 | mp_vec2_sub (struct mp_vec2 a, struct mp_vec2 b) | ||
| 87 | { | ||
| 88 | return mp_vec2 (a.x - b.x, a.y - b.y); | ||
| 89 | } | ||
| 90 | |||
| 91 | static struct mp_vec2 | ||
| 92 | mp_vec2_mul (struct mp_vec2 a, double k) | ||
| 93 | { | ||
| 94 | return mp_vec2 (a.x*k, a.y*k); | ||
| 95 | } | ||
| 96 | |||
| 97 | static double | ||
| 98 | mp_vec2_dot (struct mp_vec2 a, struct mp_vec2 b) | ||
| 99 | { | ||
| 100 | return a.x*b.x + a.y*b.y; | ||
| 101 | } | ||
| 102 | |||
| 103 | static double | ||
| 104 | mp_vec2_cross (struct mp_vec2 a, struct mp_vec2 b) | ||
| 105 | { | ||
| 106 | return a.x*b.y - a.y*b.x; | ||
| 107 | } | ||
| 108 | |||
| 109 | static double | ||
| 110 | mp_vec2_len (struct mp_vec2 a) | ||
| 111 | { | ||
| 112 | return hypot (a.x, a.y); | ||
| 113 | } | ||
| 114 | |||
| 115 | static double | ||
| 116 | mp_vec2_dist (struct mp_vec2 a, struct mp_vec2 b) | ||
| 117 | { | ||
| 118 | return mp_vec2_len (mp_vec2_sub (a, b)); | ||
| 119 | } | ||
| 120 | |||
| 121 | static struct mp_vec2 | ||
| 122 | mp_vec2_unit (struct mp_vec2 a) | ||
| 123 | { | ||
| 124 | double n = mp_vec2_len (a); | ||
| 125 | |||
| 126 | if (!(n > MP_EPS)) | ||
| 127 | return mp_vec2 (1.0, 0.0); | ||
| 128 | |||
| 129 | return mp_vec2_mul (a, 1.0/n); | ||
| 130 | } | ||
| 131 | |||
| 132 | static int | ||
| 133 | mp_reserve_segments (struct motion_plan *p, uint32_t want) | ||
| 134 | { | ||
| 135 | if (p->segment_capacity >= want) | ||
| 136 | return MP_OK; | ||
| 137 | |||
| 138 | uint32_t cap = p->segment_capacity ? p->segment_capacity : 16u; | ||
| 139 | while (cap < want) | ||
| 140 | cap *= 2u; | ||
| 141 | |||
| 142 | void *mem = realloc (p->segments, (size_t) cap * sizeof p->segments[0]); | ||
| 143 | if (!mem) | ||
| 144 | return MP_ERR_ALLOC; | ||
| 145 | |||
| 146 | p->segments = (struct mp_segment *) mem; | ||
| 147 | p->segment_capacity = cap; | ||
| 148 | return MP_OK; | ||
| 149 | } | ||
| 150 | |||
| 151 | static int | ||
| 152 | mp_reserve_nodes (struct motion_plan *p, uint32_t want) | ||
| 153 | { | ||
| 154 | if (p->node_capacity >= want) | ||
| 155 | return MP_OK; | ||
| 156 | |||
| 157 | uint32_t cap = p->node_capacity ? p->node_capacity : 16u; | ||
| 158 | while (cap < want) | ||
| 159 | cap *= 2u; | ||
| 160 | |||
| 161 | void *mem = realloc (p->nodes, (size_t) cap * sizeof p->nodes[0]); | ||
| 162 | if (!mem) | ||
| 163 | return MP_ERR_ALLOC; | ||
| 164 | |||
| 165 | p->nodes = (struct mp_node *) mem; | ||
| 166 | p->node_capacity = cap; | ||
| 167 | return MP_OK; | ||
| 168 | } | ||
| 169 | |||
| 170 | static int | ||
| 171 | mp_reserve_phases (struct motion_plan *p, uint32_t want) | ||
| 172 | { | ||
| 173 | if (p->phase_capacity >= want) | ||
| 174 | return MP_OK; | ||
| 175 | |||
| 176 | uint32_t cap = p->phase_capacity ? p->phase_capacity : 64u; | ||
| 177 | while (cap < want) | ||
| 178 | cap *= 2u; | ||
| 179 | |||
| 180 | void *mem = realloc (p->phases, (size_t) cap * sizeof p->phases[0]); | ||
| 181 | if (!mem) | ||
| 182 | return MP_ERR_ALLOC; | ||
| 183 | |||
| 184 | p->phases = (struct mp_phase *) mem; | ||
| 185 | p->phase_capacity = cap; | ||
| 186 | return MP_OK; | ||
| 187 | } | ||
| 188 | |||
| 189 | void | ||
| 190 | mp_plan_init (struct motion_plan *plan) | ||
| 191 | { | ||
| 192 | if (plan) | ||
| 193 | memset (plan, 0, sizeof *plan); | ||
| 194 | } | ||
| 195 | |||
| 196 | void | ||
| 197 | mp_plan_free (struct motion_plan *plan) | ||
| 198 | { | ||
| 199 | if (!plan) | ||
| 200 | return; | ||
| 201 | |||
| 202 | free (plan->segments); | ||
| 203 | free (plan->nodes); | ||
| 204 | free (plan->phases); | ||
| 205 | |||
| 206 | memset (plan, 0, sizeof *plan); | ||
| 207 | } | ||
| 208 | |||
| 209 | static void | ||
| 210 | mp_arc_sweep (struct mp_vec2 p0, | ||
| 211 | struct mp_vec2 p1, | ||
| 212 | struct mp_vec2 c, | ||
| 213 | int ccw, | ||
| 214 | double *a0_out, | ||
| 215 | double *sweep_out, | ||
| 216 | double *r_out) | ||
| 217 | { | ||
| 218 | double r0 = mp_vec2_dist (p0, c); | ||
| 219 | double r1 = mp_vec2_dist (p1, c); | ||
| 220 | double a0 = atan2 (p0.y - c.y, p0.x - c.x); | ||
| 221 | double a1 = atan2 (p1.y - c.y, p1.x - c.x); | ||
| 222 | double sweep = a1 - a0; | ||
| 223 | |||
| 224 | if (ccw) { | ||
| 225 | while (sweep <= 0) | ||
| 226 | sweep += 2*M_PI; | ||
| 227 | } else { | ||
| 228 | while (sweep >= 0) | ||
| 229 | sweep -= 2*M_PI; | ||
| 230 | } | ||
| 231 | |||
| 232 | if (r0 > MP_EPS && mp_vec2_dist (p0, p1) <= 1e-7*r0) | ||
| 233 | sweep = ccw ? 2*M_PI : -2*M_PI; | ||
| 234 | |||
| 235 | *a0_out = a0; | ||
| 236 | *sweep_out = sweep; | ||
| 237 | *r_out = (r0 + r1)/2; | ||
| 238 | } | ||
| 239 | |||
| 240 | static struct mp_vec2 | ||
| 241 | mp_tangent_start (const struct mp_segment *g) | ||
| 242 | { | ||
| 243 | if (g->type == MP_GEOM_LINE) | ||
| 244 | return mp_vec2_unit (mp_vec2_sub (g->p1, g->p0)); | ||
| 245 | |||
| 246 | double sgn = g->sweep >= 0 ? 1 : -1; | ||
| 247 | double a = g->a0; | ||
| 248 | |||
| 249 | return mp_vec2 (-sgn*sin (a), sgn*cos (a)); | ||
| 250 | } | ||
| 251 | |||
| 252 | static struct mp_vec2 | ||
| 253 | mp_tangent_end (const struct mp_segment *g) | ||
| 254 | { | ||
| 255 | if (g->type == MP_GEOM_LINE) | ||
| 256 | return mp_vec2_unit (mp_vec2_sub (g->p1, g->p0)); | ||
| 257 | |||
| 258 | double sgn = g->sweep >= 0 ? 1 : -1; | ||
| 259 | double a = g->a0 + g->sweep; | ||
| 260 | |||
| 261 | return mp_vec2 (-sgn*sin (a), sgn*cos (a)); | ||
| 262 | } | ||
| 263 | |||
| 264 | static void | ||
| 265 | mp_geom_eval_frame (const struct mp_segment *g, double s, | ||
| 266 | struct mp_vec2 *pos_out, | ||
| 267 | struct mp_vec2 *tangent_out, | ||
| 268 | struct mp_vec2 *normal_out, | ||
| 269 | double *kappa_out) | ||
| 270 | { | ||
| 271 | s = mp_clamp (s, 0.0, g->length); | ||
| 272 | |||
| 273 | if (g->type == MP_GEOM_ARC) { | ||
| 274 | double u = g->length > MP_EPS ? s/g->length : 1.0; | ||
| 275 | double a = g->a0 + g->sweep*u; | ||
| 276 | double ca = cos (a); | ||
| 277 | double sa = sin (a); | ||
| 278 | double sgn = g->sweep >= 0.0 ? 1.0 : -1.0; | ||
| 279 | |||
| 280 | *pos_out = mp_vec2 (g->c.x + g->r*ca, | ||
| 281 | g->c.y + g->r*sa); | ||
| 282 | *tangent_out = mp_vec2 (-sgn*sa, sgn*ca); | ||
| 283 | *normal_out = mp_vec2 (-ca, -sa); | ||
| 284 | *kappa_out = g->r > MP_EPS ? 1.0/g->r : 0.0; | ||
| 285 | return; | ||
| 286 | } | ||
| 287 | |||
| 288 | double u = g->length > MP_EPS ? s/g->length : 1.0; | ||
| 289 | struct mp_vec2 d = mp_vec2_sub (g->p1, g->p0); | ||
| 290 | struct mp_vec2 t = mp_vec2_unit (d); | ||
| 291 | |||
| 292 | *pos_out = mp_vec2 (g->p0.x + d.x*u, | ||
| 293 | g->p0.y + d.y*u); | ||
| 294 | *tangent_out = t; | ||
| 295 | *normal_out = mp_vec2 (-t.y, t.x); | ||
| 296 | *kappa_out = 0.0; | ||
| 297 | } | ||
| 298 | |||
| 299 | |||
| 300 | static double | ||
| 301 | mp_smoothstep (double x) | ||
| 302 | { | ||
| 303 | x = mp_clamp (x, 0.0, 1.0); | ||
| 304 | return x*x*(3.0 - 2.0*x); | ||
| 305 | } | ||
| 306 | |||
| 307 | static double | ||
| 308 | mp_segment_curvature (const struct mp_segment *g) | ||
| 309 | { | ||
| 310 | if (g && g->type == MP_GEOM_ARC && g->r > MP_EPS) | ||
| 311 | return 1.0/g->r; | ||
| 312 | |||
| 313 | return 0.0; | ||
| 314 | } | ||
| 315 | |||
| 316 | static int | ||
| 317 | mp_node_allows_curvature_blend (const struct mp_node *node) | ||
| 318 | { | ||
| 319 | if (!node) | ||
| 320 | return 0; | ||
| 321 | |||
| 322 | if (node->flags & (MP_NODE_GEOM_GAP | MP_NODE_HARD_STOP)) | ||
| 323 | return 0; | ||
| 324 | |||
| 325 | return 1; | ||
| 326 | } | ||
| 327 | |||
| 328 | static double | ||
| 329 | mp_effective_kappa (const struct motion_plan *plan, | ||
| 330 | uint32_t segment_index, | ||
| 331 | double local_s, | ||
| 332 | double kappa_geom) | ||
| 333 | { | ||
| 334 | if (!plan || !(plan->curvature_blend_len > 0.0) || !isfinite (plan->curvature_blend_len)) | ||
| 335 | return kappa_geom; | ||
| 336 | |||
| 337 | if (segment_index >= plan->segment_count) | ||
| 338 | return kappa_geom; | ||
| 339 | |||
| 340 | const struct mp_segment *cur = &plan->segments[segment_index]; | ||
| 341 | double kappa = kappa_geom; | ||
| 342 | double blend = plan->curvature_blend_len; | ||
| 343 | |||
| 344 | if (segment_index > 0u && local_s < blend) { | ||
| 345 | const struct mp_node *node = &plan->nodes[segment_index]; | ||
| 346 | |||
| 347 | if (mp_node_allows_curvature_blend (node)) { | ||
| 348 | const struct mp_segment *prev = &plan->segments[segment_index - 1u]; | ||
| 349 | double b = fmin (blend, 0.5*fmin (prev->length, cur->length)); | ||
| 350 | |||
| 351 | if (b > MP_EPS && local_s < b) { | ||
| 352 | double k_prev = mp_segment_curvature (prev); | ||
| 353 | double w = mp_smoothstep (local_s/b); | ||
| 354 | kappa = (1.0 - w)*k_prev + w*kappa; | ||
| 355 | } | ||
| 356 | } | ||
| 357 | } | ||
| 358 | |||
| 359 | if (segment_index + 1u < plan->segment_count && cur->length - local_s < blend) { | ||
| 360 | const struct mp_node *node = &plan->nodes[segment_index + 1u]; | ||
| 361 | |||
| 362 | if (mp_node_allows_curvature_blend (node)) { | ||
| 363 | const struct mp_segment *next = &plan->segments[segment_index + 1u]; | ||
| 364 | double b = fmin (blend, 0.5*fmin (cur->length, next->length)); | ||
| 365 | double d = cur->length - local_s; | ||
| 366 | |||
| 367 | if (b > MP_EPS && d < b) { | ||
| 368 | double k_next = mp_segment_curvature (next); | ||
| 369 | double w = mp_smoothstep (1.0 - d/b); | ||
| 370 | kappa = (1.0 - w)*kappa + w*k_next; | ||
| 371 | } | ||
| 372 | } | ||
| 373 | } | ||
| 374 | |||
| 375 | return kappa; | ||
| 376 | } | ||
| 377 | |||
| 378 | static double | ||
| 379 | mp_segment_speed_cap (const struct mp_segment *g, | ||
| 380 | const struct mp_limits *l, | ||
| 381 | double v) | ||
| 382 | { | ||
| 383 | if (g->type == MP_GEOM_ARC && g->r > MP_EPS) { | ||
| 384 | double vc = sqrt (l->amax * g->r); | ||
| 385 | if (vc > 0.0 && isfinite (vc)) | ||
| 386 | v = fmin (v, vc); | ||
| 387 | } | ||
| 388 | |||
| 389 | return v; | ||
| 390 | } | ||
| 391 | |||
| 392 | static int | ||
| 393 | mp_push_segment (struct motion_plan *p, const struct mp_segment *g) | ||
| 394 | { | ||
| 395 | int rc = mp_reserve_segments (p, p->segment_count + 1u); | ||
| 396 | if (rc != MP_OK) | ||
| 397 | return rc; | ||
| 398 | |||
| 399 | p->segments[p->segment_count++] = *g; | ||
| 400 | return MP_OK; | ||
| 401 | } | ||
| 402 | |||
| 403 | static int | ||
| 404 | mp_build_segments (const struct path *path, | ||
| 405 | double initial_x, | ||
| 406 | double initial_y, | ||
| 407 | const struct mp_limits *limits, | ||
| 408 | struct motion_plan *out) | ||
| 409 | { | ||
| 410 | struct mp_vec2 p0 = mp_vec2 (initial_x, initial_y); | ||
| 411 | double min_len = mp_min_segment_len (limits); | ||
| 412 | double rapid = mp_rapid_vmax (limits); | ||
| 413 | |||
| 414 | if (!(rapid > 0.0) || !isfinite (rapid)) | ||
| 415 | return MP_ERR_LIMITS; | ||
| 416 | |||
| 417 | for (uint32_t i = 0; i < path->count; ++i) { | ||
| 418 | const struct path_element *el = &path->items[i]; | ||
| 419 | struct mp_vec2 p1 = mp_vec2 (el->x, el->y); | ||
| 420 | |||
| 421 | struct mp_segment g; | ||
| 422 | memset (&g, 0, sizeof g); | ||
| 423 | |||
| 424 | g.source_index = i; | ||
| 425 | g.flags = el->flags; | ||
| 426 | g.p0 = p0; | ||
| 427 | g.p1 = p1; | ||
| 428 | |||
| 429 | if (el->flags & PEF_ARC) { | ||
| 430 | g.type = MP_GEOM_ARC; | ||
| 431 | g.c = mp_vec2 (el->i, el->j); | ||
| 432 | mp_arc_sweep (g.p0, g.p1, g.c, el->flags & PEF_CCW, &g.a0, &g.sweep, &g.r); | ||
| 433 | |||
| 434 | if (!(g.r > MP_EPS) || !isfinite (g.r) || !isfinite (g.sweep)) | ||
| 435 | return MP_ERR_GEOMETRY; | ||
| 436 | |||
| 437 | g.length = fabs (g.sweep) * g.r; | ||
| 438 | } else { | ||
| 439 | g.type = MP_GEOM_LINE; | ||
| 440 | g.length = mp_vec2_dist (g.p0, g.p1); | ||
| 441 | } | ||
| 442 | |||
| 443 | p0 = p1; | ||
| 444 | |||
| 445 | if (!(g.length > min_len)) | ||
| 446 | continue; | ||
| 447 | |||
| 448 | if (el->flags & PEF_TRAVERSING) { | ||
| 449 | g.feed = rapid; | ||
| 450 | g.v_nominal = rapid; | ||
| 451 | } else { | ||
| 452 | g.feed = el->f > 0.0 ? el->f : limits->default_feed; | ||
| 453 | g.v_nominal = fmin (g.feed, limits->vmax); | ||
| 454 | } | ||
| 455 | |||
| 456 | g.v_nominal = mp_segment_speed_cap (&g, limits, g.v_nominal); | ||
| 457 | |||
| 458 | if (!(g.v_nominal > 0.0) || !isfinite (g.v_nominal)) | ||
| 459 | return MP_ERR_LIMITS; | ||
| 460 | |||
| 461 | g.s_begin = out->total_length; | ||
| 462 | g.s_end = g.s_begin + g.length; | ||
| 463 | out->total_length = g.s_end; | ||
| 464 | |||
| 465 | int rc = mp_push_segment (out, &g); | ||
| 466 | if (rc != MP_OK) | ||
| 467 | return rc; | ||
| 468 | } | ||
| 469 | |||
| 470 | return MP_OK; | ||
| 471 | } | ||
| 472 | |||
| 473 | static double | ||
| 474 | mp_junction_speed (const struct mp_segment *left, | ||
| 475 | const struct mp_segment *right, | ||
| 476 | const struct mp_limits *limits, | ||
| 477 | double *theta_out, | ||
| 478 | uint32_t *flags_out) | ||
| 479 | { | ||
| 480 | double cap = fmin (left->v_nominal, right->v_nominal); | ||
| 481 | uint32_t flags = 0; | ||
| 482 | |||
| 483 | if (!(cap > 0.0) || !isfinite (cap)) { | ||
| 484 | if (theta_out) *theta_out = 0.0; | ||
| 485 | if (flags_out) *flags_out = MP_NODE_HARD_STOP; | ||
| 486 | return 0.0; | ||
| 487 | } | ||
| 488 | |||
| 489 | if (mp_vec2_dist (left->p1, right->p0) > 1e-5) { | ||
| 490 | if (theta_out) *theta_out = 0.0; | ||
| 491 | if (flags_out) *flags_out = MP_NODE_GEOM_GAP | MP_NODE_HARD_STOP; | ||
| 492 | return 0.0; | ||
| 493 | } | ||
| 494 | |||
| 495 | struct mp_vec2 t0 = mp_tangent_end (left); | ||
| 496 | struct mp_vec2 t1 = mp_tangent_start (right); | ||
| 497 | double dot = mp_clamp (mp_vec2_dot (t0, t1), -1.0, 1.0); | ||
| 498 | double cross = mp_vec2_cross (t0, t1); | ||
| 499 | double theta = fabs (atan2 (cross, dot)); | ||
| 500 | |||
| 501 | if (theta_out) | ||
| 502 | *theta_out = theta; | ||
| 503 | |||
| 504 | if (theta <= mp_straight_angle_tol (limits)) { | ||
| 505 | flags = MP_NODE_STRAIGHT; | ||
| 506 | if (flags_out) *flags_out = flags; | ||
| 507 | return cap; | ||
| 508 | } | ||
| 509 | |||
| 510 | if (theta >= mp_stop_angle (limits)) { | ||
| 511 | flags = MP_NODE_HARD_STOP | MP_NODE_CORNER_LIMIT; | ||
| 512 | if (flags_out) *flags_out = flags; | ||
| 513 | return 0; | ||
| 514 | } | ||
| 515 | |||
| 516 | if (!(limits->corner_tol > 0.0)) { | ||
| 517 | flags = MP_NODE_HARD_STOP | MP_NODE_CORNER_LIMIT; | ||
| 518 | if (flags_out) *flags_out = flags; | ||
| 519 | return 0; | ||
| 520 | } | ||
| 521 | |||
| 522 | double c = cos (theta/2); | ||
| 523 | double denom = 1 - c; | ||
| 524 | |||
| 525 | if (denom <= MP_EPS) { | ||
| 526 | flags = MP_NODE_STRAIGHT; | ||
| 527 | if (flags_out) *flags_out = flags; | ||
| 528 | return cap; | ||
| 529 | } | ||
| 530 | |||
| 531 | double r_virtual = limits->corner_tol*c/denom; | ||
| 532 | if (!(r_virtual > 0.0) || !isfinite (r_virtual)) { | ||
| 533 | flags = MP_NODE_HARD_STOP | MP_NODE_CORNER_LIMIT; | ||
| 534 | if (flags_out) *flags_out = flags; | ||
| 535 | return 0.0; | ||
| 536 | } | ||
| 537 | |||
| 538 | double vj = sqrt (limits->amax * r_virtual); | ||
| 539 | double db = mp_corner_deadband (limits); | ||
| 540 | |||
| 541 | if (vj >= cap*(1 - db)) { | ||
| 542 | flags = MP_NODE_STRAIGHT; | ||
| 543 | if (flags_out) *flags_out = flags; | ||
| 544 | return cap; | ||
| 545 | } | ||
| 546 | |||
| 547 | flags = MP_NODE_CORNER_LIMIT; | ||
| 548 | if (flags_out) *flags_out = flags; | ||
| 549 | return cap; | ||
| 550 | return fmin (cap, vj); | ||
| 551 | } | ||
| 552 | |||
| 553 | static int | ||
| 554 | mp_build_nodes (struct motion_plan *out, const struct mp_limits *limits) | ||
| 555 | { | ||
| 556 | uint32_t nseg = out->segment_count; | ||
| 557 | int rc = mp_reserve_nodes (out, nseg + 1u); | ||
| 558 | if (rc != MP_OK) | ||
| 559 | return rc; | ||
| 560 | |||
| 561 | out->node_count = nseg + 1u; | ||
| 562 | memset (out->nodes, 0, (size_t) out->node_count * sizeof out->nodes[0]); | ||
| 563 | |||
| 564 | out->nodes[0].s = 0.0; | ||
| 565 | out->nodes[0].v_cap = 0.0; | ||
| 566 | out->nodes[0].v = 0.0; | ||
| 567 | out->nodes[0].flags = MP_NODE_START | MP_NODE_HARD_STOP | MP_NODE_KNOT; | ||
| 568 | |||
| 569 | for (uint32_t i = 1; i < nseg; ++i) { | ||
| 570 | struct mp_node *node = &out->nodes[i]; | ||
| 571 | const struct mp_segment *left = &out->segments[i - 1u]; | ||
| 572 | const struct mp_segment *right = &out->segments[i]; | ||
| 573 | |||
| 574 | uint32_t flags = 0; | ||
| 575 | double theta = 0.0; | ||
| 576 | double vcap = mp_junction_speed (left, right, limits, &theta, &flags); | ||
| 577 | |||
| 578 | if (fabs (left->v_nominal - right->v_nominal) > 1e-8*fmax (1.0, fmax (left->v_nominal, right->v_nominal))) | ||
| 579 | flags |= MP_NODE_SPEED_CHANGE; | ||
| 580 | |||
| 581 | node->s = left->s_end; | ||
| 582 | node->v_cap = vcap; | ||
| 583 | node->v = vcap; | ||
| 584 | node->theta = theta; | ||
| 585 | node->flags = flags; | ||
| 586 | } | ||
| 587 | |||
| 588 | out->nodes[nseg].s = out->total_length; | ||
| 589 | out->nodes[nseg].v_cap = 0.0; | ||
| 590 | out->nodes[nseg].v = 0.0; | ||
| 591 | out->nodes[nseg].flags = MP_NODE_END | MP_NODE_HARD_STOP | MP_NODE_KNOT; | ||
| 592 | |||
| 593 | return MP_OK; | ||
| 594 | } | ||
| 595 | |||
| 596 | static double | ||
| 597 | mp_speed_change_distance_scurve (double v_from, | ||
| 598 | double v_to, | ||
| 599 | double amax, | ||
| 600 | double jmax) | ||
| 601 | { | ||
| 602 | if (v_to <= v_from + MP_EPS) | ||
| 603 | return 0.0; | ||
| 604 | |||
| 605 | double dv = v_to - v_from; | ||
| 606 | double dv_full = amax*amax/jmax; | ||
| 607 | double duration; | ||
| 608 | |||
| 609 | if (dv <= dv_full) { | ||
| 610 | double tj = sqrt (dv/jmax); | ||
| 611 | duration = 2.0*tj; | ||
| 612 | } else { | ||
| 613 | double tj = amax/jmax; | ||
| 614 | double tc = dv/amax - tj; | ||
| 615 | duration = 2.0*tj + tc; | ||
| 616 | } | ||
| 617 | |||
| 618 | return 0.5*(v_from + v_to)*duration; | ||
| 619 | } | ||
| 620 | |||
| 621 | static double | ||
| 622 | mp_reachable_speed (double v0, | ||
| 623 | double length, | ||
| 624 | const struct mp_limits *limits, | ||
| 625 | double vcap) | ||
| 626 | { | ||
| 627 | if (vcap <= v0) | ||
| 628 | return vcap; | ||
| 629 | |||
| 630 | if (mp_speed_change_distance_scurve (v0, vcap, limits->amax, limits->jmax) <= length) | ||
| 631 | return vcap; | ||
| 632 | |||
| 633 | double lo = v0; | ||
| 634 | double hi = vcap; | ||
| 635 | |||
| 636 | for (int k = 0; k < 80; ++k) { | ||
| 637 | double mid = 0.5*(lo + hi); | ||
| 638 | double s = mp_speed_change_distance_scurve (v0, mid, limits->amax, limits->jmax); | ||
| 639 | |||
| 640 | if (s <= length) | ||
| 641 | lo = mid; | ||
| 642 | else | ||
| 643 | hi = mid; | ||
| 644 | } | ||
| 645 | |||
| 646 | return lo; | ||
| 647 | } | ||
| 648 | |||
| 649 | static void | ||
| 650 | mp_apply_speed_lookahead (struct motion_plan *out, | ||
| 651 | const struct mp_limits *limits) | ||
| 652 | { | ||
| 653 | uint32_t nseg = out->segment_count; | ||
| 654 | |||
| 655 | for (uint32_t i = nseg; i-- > 0u;) { | ||
| 656 | double cap = out->segments[i].v_nominal; | ||
| 657 | double allowed = mp_reachable_speed (out->nodes[i + 1u].v, | ||
| 658 | out->segments[i].length, | ||
| 659 | limits, | ||
| 660 | cap); | ||
| 661 | if (out->nodes[i].v > allowed) | ||
| 662 | out->nodes[i].v = allowed; | ||
| 663 | } | ||
| 664 | |||
| 665 | for (uint32_t i = 0; i < nseg; ++i) { | ||
| 666 | double cap = out->segments[i].v_nominal; | ||
| 667 | double allowed = mp_reachable_speed (out->nodes[i].v, | ||
| 668 | out->segments[i].length, | ||
| 669 | limits, | ||
| 670 | cap); | ||
| 671 | if (out->nodes[i + 1u].v > allowed) | ||
| 672 | out->nodes[i + 1u].v = allowed; | ||
| 673 | } | ||
| 674 | } | ||
| 675 | |||
| 676 | static int | ||
| 677 | mp_node_should_be_knot (const struct motion_plan *p, | ||
| 678 | uint32_t node_index, | ||
| 679 | const struct mp_limits *limits) | ||
| 680 | { | ||
| 681 | if (node_index == 0u || node_index + 1u == p->node_count) | ||
| 682 | return 1; | ||
| 683 | |||
| 684 | const struct mp_node *node = &p->nodes[node_index]; | ||
| 685 | const struct mp_segment *left = &p->segments[node_index - 1u]; | ||
| 686 | const struct mp_segment *right = &p->segments[node_index]; | ||
| 687 | |||
| 688 | if (node->flags & (MP_NODE_GEOM_GAP | MP_NODE_HARD_STOP)) | ||
| 689 | return 1; | ||
| 690 | |||
| 691 | double cap = fmin (left->v_nominal, right->v_nominal); | ||
| 692 | double db = mp_corner_deadband (limits); | ||
| 693 | |||
| 694 | if (node->v_cap < cap * (1.0 - db)) | ||
| 695 | return 1; | ||
| 696 | |||
| 697 | return 0; | ||
| 698 | } | ||
| 699 | |||
| 700 | static void | ||
| 701 | mp_mark_knots (struct motion_plan *p, const struct mp_limits *limits) | ||
| 702 | { | ||
| 703 | for (uint32_t i = 0; i < p->node_count; ++i) { | ||
| 704 | if (mp_node_should_be_knot (p, i, limits)) | ||
| 705 | p->nodes[i].flags |= MP_NODE_KNOT; | ||
| 706 | else | ||
| 707 | p->nodes[i].flags &= ~((uint32_t) MP_NODE_KNOT); | ||
| 708 | } | ||
| 709 | } | ||
| 710 | |||
| 711 | static double | ||
| 712 | mp_interval_vcap (const struct motion_plan *p, | ||
| 713 | uint32_t node_begin, | ||
| 714 | uint32_t node_end) | ||
| 715 | { | ||
| 716 | double vcap = DBL_MAX; | ||
| 717 | |||
| 718 | for (uint32_t i = node_begin; i < node_end; ++i) | ||
| 719 | vcap = fmin (vcap, p->segments[i].v_nominal); | ||
| 720 | |||
| 721 | if (!(vcap < DBL_MAX)) | ||
| 722 | return 0.0; | ||
| 723 | |||
| 724 | return vcap; | ||
| 725 | } | ||
| 726 | |||
| 727 | static int | ||
| 728 | mp_append_phase (struct motion_plan *p, | ||
| 729 | double dt, | ||
| 730 | double a0, | ||
| 731 | double j, | ||
| 732 | double *s_cursor, | ||
| 733 | double *t_cursor, | ||
| 734 | double *v_cursor, | ||
| 735 | double *a_cursor) | ||
| 736 | { | ||
| 737 | if (dt <= 1e-12) | ||
| 738 | return MP_OK; | ||
| 739 | |||
| 740 | if (!isfinite (dt) || !isfinite (a0) || !isfinite (j)) | ||
| 741 | return MP_ERR_PROFILE; | ||
| 742 | |||
| 743 | int rc = mp_reserve_phases (p, p->phase_count + 1u); | ||
| 744 | if (rc != MP_OK) | ||
| 745 | return rc; | ||
| 746 | |||
| 747 | struct mp_phase *ph = &p->phases[p->phase_count++]; | ||
| 748 | |||
| 749 | ph->t_begin = *t_cursor; | ||
| 750 | ph->dt = dt; | ||
| 751 | ph->s_begin = *s_cursor; | ||
| 752 | ph->v0 = *v_cursor; | ||
| 753 | ph->a0 = a0; | ||
| 754 | ph->j = j; | ||
| 755 | |||
| 756 | double dt2 = dt*dt; | ||
| 757 | double dt3 = dt2*dt; | ||
| 758 | |||
| 759 | double s1 = *s_cursor + (*v_cursor)*dt + 0.5*a0*dt2 + (j*dt3)/6.0; | ||
| 760 | double v1 = *v_cursor + a0*dt + 0.5*j*dt2; | ||
| 761 | double a1 = a0 + j*dt; | ||
| 762 | |||
| 763 | ph->s_end = s1; | ||
| 764 | |||
| 765 | *s_cursor = s1; | ||
| 766 | *t_cursor += dt; | ||
| 767 | *v_cursor = v1; | ||
| 768 | *a_cursor = a1; | ||
| 769 | |||
| 770 | p->total_time = *t_cursor; | ||
| 771 | |||
| 772 | p->v_min = fmin (p->v_min, fmin (ph->v0, v1)); | ||
| 773 | p->v_max = fmax (p->v_max, fmax (ph->v0, v1)); | ||
| 774 | |||
| 775 | p->a_min = fmin (p->a_min, fmin (a0, a1)); | ||
| 776 | p->a_max = fmax (p->a_max, fmax (a0, a1)); | ||
| 777 | |||
| 778 | p->j_min = fmin (p->j_min, j); | ||
| 779 | p->j_max = fmax (p->j_max, j); | ||
| 780 | |||
| 781 | return MP_OK; | ||
| 782 | } | ||
| 783 | |||
| 784 | static int | ||
| 785 | mp_append_speed_change_scurve (struct motion_plan *p, | ||
| 786 | double v_from, | ||
| 787 | double v_to, | ||
| 788 | const struct mp_limits *limits, | ||
| 789 | double *s_cursor, | ||
| 790 | double *t_cursor, | ||
| 791 | double *v_cursor, | ||
| 792 | double *a_cursor) | ||
| 793 | { | ||
| 794 | double dv = fabs (v_to - v_from); | ||
| 795 | |||
| 796 | if (dv <= 1e-10) { | ||
| 797 | *v_cursor = v_to; | ||
| 798 | *a_cursor = 0.0; | ||
| 799 | return MP_OK; | ||
| 800 | } | ||
| 801 | |||
| 802 | double sign = v_to > v_from ? 1.0 : -1.0; | ||
| 803 | double dv_full = limits->amax*limits->amax/limits->jmax; | ||
| 804 | |||
| 805 | if (dv <= dv_full) { | ||
| 806 | double tj = sqrt (dv/limits->jmax); | ||
| 807 | double ap = limits->jmax*tj; | ||
| 808 | |||
| 809 | int rc = mp_append_phase (p, tj, 0.0, sign*limits->jmax, | ||
| 810 | s_cursor, t_cursor, v_cursor, a_cursor); | ||
| 811 | if (rc != MP_OK) return rc; | ||
| 812 | |||
| 813 | return mp_append_phase (p, tj, sign*ap, -sign*limits->jmax, | ||
| 814 | s_cursor, t_cursor, v_cursor, a_cursor); | ||
| 815 | } | ||
| 816 | |||
| 817 | double tj = limits->amax/limits->jmax; | ||
| 818 | double tc = dv/limits->amax - tj; | ||
| 819 | |||
| 820 | int rc = mp_append_phase (p, tj, 0.0, sign*limits->jmax, | ||
| 821 | s_cursor, t_cursor, v_cursor, a_cursor); | ||
| 822 | if (rc != MP_OK) return rc; | ||
| 823 | |||
| 824 | rc = mp_append_phase (p, tc, sign*limits->amax, 0.0, | ||
| 825 | s_cursor, t_cursor, v_cursor, a_cursor); | ||
| 826 | if (rc != MP_OK) return rc; | ||
| 827 | |||
| 828 | return mp_append_phase (p, tj, sign*limits->amax, -sign*limits->jmax, | ||
| 829 | s_cursor, t_cursor, v_cursor, a_cursor); | ||
| 830 | } | ||
| 831 | |||
| 832 | static int | ||
| 833 | mp_build_interval_scurve (struct motion_plan *p, | ||
| 834 | double length, | ||
| 835 | double v0, | ||
| 836 | double v1, | ||
| 837 | double vcap, | ||
| 838 | const struct mp_limits *limits, | ||
| 839 | double s_target, | ||
| 840 | double *s_cursor, | ||
| 841 | double *t_cursor, | ||
| 842 | double *v_cursor, | ||
| 843 | double *a_cursor) | ||
| 844 | { | ||
| 845 | if (!(length > 1e-12)) { | ||
| 846 | *s_cursor = s_target; | ||
| 847 | *v_cursor = v1; | ||
| 848 | *a_cursor = 0.0; | ||
| 849 | return MP_OK; | ||
| 850 | } | ||
| 851 | |||
| 852 | if (!(vcap > 0.0) || !isfinite (vcap)) | ||
| 853 | return MP_ERR_PROFILE; | ||
| 854 | |||
| 855 | if (v0 > vcap + 1e-7 || v1 > vcap + 1e-7) | ||
| 856 | return MP_ERR_PROFILE; | ||
| 857 | |||
| 858 | double vlo = fmax (v0, v1); | ||
| 859 | double vhi = fmax (vcap, vlo); | ||
| 860 | |||
| 861 | double s_at_vhi = | ||
| 862 | mp_speed_change_distance_scurve (v0, vhi, limits->amax, limits->jmax) + | ||
| 863 | mp_speed_change_distance_scurve (v1, vhi, limits->amax, limits->jmax); | ||
| 864 | |||
| 865 | double vp; | ||
| 866 | double cruise_len; | ||
| 867 | |||
| 868 | if (s_at_vhi <= length + 1e-8) { | ||
| 869 | vp = vhi; | ||
| 870 | cruise_len = fmax (0.0, length - s_at_vhi); | ||
| 871 | } else { | ||
| 872 | double s_at_vlo = | ||
| 873 | mp_speed_change_distance_scurve (v0, vlo, limits->amax, limits->jmax) + | ||
| 874 | mp_speed_change_distance_scurve (v1, vlo, limits->amax, limits->jmax); | ||
| 875 | |||
| 876 | if (s_at_vlo > length + 1e-6) | ||
| 877 | return MP_ERR_PROFILE; | ||
| 878 | |||
| 879 | double lo = vlo; | ||
| 880 | double hi = vhi; | ||
| 881 | |||
| 882 | for (int k = 0; k < 80; ++k) { | ||
| 883 | double mid = 0.5*(lo + hi); | ||
| 884 | double sm = | ||
| 885 | mp_speed_change_distance_scurve (v0, mid, limits->amax, limits->jmax) + | ||
| 886 | mp_speed_change_distance_scurve (v1, mid, limits->amax, limits->jmax); | ||
| 887 | |||
| 888 | if (sm <= length) | ||
| 889 | lo = mid; | ||
| 890 | else | ||
| 891 | hi = mid; | ||
| 892 | } | ||
| 893 | |||
| 894 | vp = lo; | ||
| 895 | cruise_len = 0.0; | ||
| 896 | } | ||
| 897 | |||
| 898 | *v_cursor = v0; | ||
| 899 | *a_cursor = 0.0; | ||
| 900 | |||
| 901 | int rc = mp_append_speed_change_scurve (p, v0, vp, limits, | ||
| 902 | s_cursor, t_cursor, v_cursor, a_cursor); | ||
| 903 | if (rc != MP_OK) | ||
| 904 | return rc; | ||
| 905 | |||
| 906 | if (cruise_len > 1e-10) { | ||
| 907 | if (!(vp > 1e-12)) | ||
| 908 | return MP_ERR_PROFILE; | ||
| 909 | |||
| 910 | rc = mp_append_phase (p, cruise_len/vp, 0.0, 0.0, | ||
| 911 | s_cursor, t_cursor, v_cursor, a_cursor); | ||
| 912 | if (rc != MP_OK) | ||
| 913 | return rc; | ||
| 914 | } | ||
| 915 | |||
| 916 | rc = mp_append_speed_change_scurve (p, vp, v1, limits, | ||
| 917 | s_cursor, t_cursor, v_cursor, a_cursor); | ||
| 918 | if (rc != MP_OK) | ||
| 919 | return rc; | ||
| 920 | |||
| 921 | *s_cursor = s_target; | ||
| 922 | *v_cursor = v1; | ||
| 923 | *a_cursor = 0.0; | ||
| 924 | |||
| 925 | if (p->phase_count > 0u) | ||
| 926 | p->phases[p->phase_count - 1u].s_end = s_target; | ||
| 927 | |||
| 928 | return MP_OK; | ||
| 929 | } | ||
| 930 | |||
| 931 | static int | ||
| 932 | mp_build_global_phases (struct motion_plan *p, | ||
| 933 | const struct mp_limits *limits) | ||
| 934 | { | ||
| 935 | p->phase_count = 0u; | ||
| 936 | p->total_time = 0.0; | ||
| 937 | |||
| 938 | p->v_min = DBL_MAX; | ||
| 939 | p->v_max = -DBL_MAX; | ||
| 940 | p->a_min = DBL_MAX; | ||
| 941 | p->a_max = -DBL_MAX; | ||
| 942 | p->j_min = DBL_MAX; | ||
| 943 | p->j_max = -DBL_MAX; | ||
| 944 | |||
| 945 | double s_cursor = 0.0; | ||
| 946 | double t_cursor = 0.0; | ||
| 947 | double v_cursor = 0.0; | ||
| 948 | double a_cursor = 0.0; | ||
| 949 | |||
| 950 | uint32_t knot_begin = 0u; | ||
| 951 | |||
| 952 | while (knot_begin + 1u < p->node_count) { | ||
| 953 | uint32_t knot_end = knot_begin + 1u; | ||
| 954 | |||
| 955 | while (knot_end + 1u < p->node_count && | ||
| 956 | !(p->nodes[knot_end].flags & MP_NODE_KNOT)) | ||
| 957 | ++knot_end; | ||
| 958 | |||
| 959 | double length = p->nodes[knot_end].s - p->nodes[knot_begin].s; | ||
| 960 | double v0 = p->nodes[knot_begin].v; | ||
| 961 | double v1 = p->nodes[knot_end].v; | ||
| 962 | double vcap = mp_interval_vcap (p, knot_begin, knot_end); | ||
| 963 | double s_target = p->nodes[knot_end].s; | ||
| 964 | |||
| 965 | int rc = mp_build_interval_scurve (p, length, v0, v1, vcap, limits, | ||
| 966 | s_target, | ||
| 967 | &s_cursor, &t_cursor, &v_cursor, &a_cursor); | ||
| 968 | if (rc != MP_OK) | ||
| 969 | return rc; | ||
| 970 | |||
| 971 | knot_begin = knot_end; | ||
| 972 | } | ||
| 973 | |||
| 974 | p->total_time = t_cursor; | ||
| 975 | |||
| 976 | if (p->phase_count == 0u) { | ||
| 977 | p->v_min = p->v_max = 0.0; | ||
| 978 | p->a_min = p->a_max = 0.0; | ||
| 979 | p->j_min = p->j_max = 0.0; | ||
| 980 | } | ||
| 981 | |||
| 982 | return MP_OK; | ||
| 983 | } | ||
| 984 | |||
| 985 | int | ||
| 986 | mp_plan_build (const struct path *path, | ||
| 987 | double initial_x, | ||
| 988 | double initial_y, | ||
| 989 | const struct mp_limits *limits, | ||
| 990 | struct motion_plan *out) | ||
| 991 | { | ||
| 992 | if (!path || !out || !mp_limits_valid (limits)) | ||
| 993 | return MP_ERR_INVALID_ARG; | ||
| 994 | |||
| 995 | mp_plan_free (out); | ||
| 996 | |||
| 997 | out->curvature_blend_len = limits->curvature_blend_len > 0.0 | ||
| 998 | ? limits->curvature_blend_len | ||
| 999 | : 0.0; | ||
| 1000 | |||
| 1001 | if (path->count == 0u) | ||
| 1002 | return MP_OK; | ||
| 1003 | |||
| 1004 | int rc = mp_build_segments (path, initial_x, initial_y, limits, out); | ||
| 1005 | if (rc != MP_OK) { | ||
| 1006 | mp_plan_free (out); | ||
| 1007 | return rc; | ||
| 1008 | } | ||
| 1009 | |||
| 1010 | if (out->segment_count == 0u) | ||
| 1011 | return MP_OK; | ||
| 1012 | |||
| 1013 | rc = mp_build_nodes (out, limits); | ||
| 1014 | if (rc != MP_OK) { | ||
| 1015 | mp_plan_free (out); | ||
| 1016 | return rc; | ||
| 1017 | } | ||
| 1018 | |||
| 1019 | mp_apply_speed_lookahead (out, limits); | ||
| 1020 | mp_mark_knots (out, limits); | ||
| 1021 | |||
| 1022 | rc = mp_build_global_phases (out, limits); | ||
| 1023 | if (rc != MP_OK) { | ||
| 1024 | mp_plan_free (out); | ||
| 1025 | return rc; | ||
| 1026 | } | ||
| 1027 | |||
| 1028 | return MP_OK; | ||
| 1029 | } | ||
| 1030 | |||
| 1031 | void | ||
| 1032 | mp_plan_eval_scalar (const struct motion_plan *plan, double t, | ||
| 1033 | double *s_out, double *v_out, | ||
| 1034 | double *a_out, double *j_out) | ||
| 1035 | { | ||
| 1036 | if (!plan || plan->phase_count == 0u) { | ||
| 1037 | if (s_out) *s_out = 0.0; | ||
| 1038 | if (v_out) *v_out = 0.0; | ||
| 1039 | if (a_out) *a_out = 0.0; | ||
| 1040 | if (j_out) *j_out = 0.0; | ||
| 1041 | return; | ||
| 1042 | } | ||
| 1043 | |||
| 1044 | if (t <= 0.0) { | ||
| 1045 | const struct mp_phase *ph = &plan->phases[0]; | ||
| 1046 | if (s_out) *s_out = ph->s_begin; | ||
| 1047 | if (v_out) *v_out = ph->v0; | ||
| 1048 | if (a_out) *a_out = ph->a0; | ||
| 1049 | if (j_out) *j_out = ph->j; | ||
| 1050 | return; | ||
| 1051 | } | ||
| 1052 | |||
| 1053 | if (t >= plan->total_time) { | ||
| 1054 | if (s_out) *s_out = plan->total_length; | ||
| 1055 | if (v_out) *v_out = 0.0; | ||
| 1056 | if (a_out) *a_out = 0.0; | ||
| 1057 | if (j_out) *j_out = 0.0; | ||
| 1058 | return; | ||
| 1059 | } | ||
| 1060 | |||
| 1061 | uint32_t lo = 0u; | ||
| 1062 | uint32_t hi = plan->phase_count; | ||
| 1063 | |||
| 1064 | while (lo + 1u < hi) { | ||
| 1065 | uint32_t mid = lo + (hi - lo)/2u; | ||
| 1066 | const struct mp_phase *ph = &plan->phases[mid]; | ||
| 1067 | |||
| 1068 | if (t < ph->t_begin + ph->dt) | ||
| 1069 | hi = mid; | ||
| 1070 | else | ||
| 1071 | lo = mid; | ||
| 1072 | } | ||
| 1073 | |||
| 1074 | uint32_t idx = lo; | ||
| 1075 | while (idx + 1u < plan->phase_count && | ||
| 1076 | t >= plan->phases[idx].t_begin + plan->phases[idx].dt) | ||
| 1077 | ++idx; | ||
| 1078 | |||
| 1079 | const struct mp_phase *ph = &plan->phases[idx]; | ||
| 1080 | double tau = t - ph->t_begin; | ||
| 1081 | tau = mp_clamp (tau, 0.0, ph->dt); | ||
| 1082 | |||
| 1083 | double s = ph->s_begin + ph->v0*tau + 0.5*ph->a0*tau*tau + (ph->j*tau*tau*tau)/6.0; | ||
| 1084 | double v = ph->v0 + ph->a0*tau + 0.5*ph->j*tau*tau; | ||
| 1085 | double a = ph->a0 + ph->j*tau; | ||
| 1086 | |||
| 1087 | if (s_out) *s_out = mp_clamp (s, 0.0, plan->total_length); | ||
| 1088 | if (v_out) *v_out = fmax (0.0, v); | ||
| 1089 | if (a_out) *a_out = a; | ||
| 1090 | if (j_out) *j_out = ph->j; | ||
| 1091 | } | ||
| 1092 | |||
| 1093 | static uint32_t | ||
| 1094 | mp_find_segment_by_s (const struct motion_plan *plan, double s) | ||
| 1095 | { | ||
| 1096 | if (plan->segment_count == 0u) | ||
| 1097 | return 0u; | ||
| 1098 | |||
| 1099 | if (s <= 0.0) | ||
| 1100 | return 0u; | ||
| 1101 | |||
| 1102 | if (s >= plan->total_length) | ||
| 1103 | return plan->segment_count - 1u; | ||
| 1104 | |||
| 1105 | uint32_t lo = 0u; | ||
| 1106 | uint32_t hi = plan->segment_count; | ||
| 1107 | |||
| 1108 | while (lo + 1u < hi) { | ||
| 1109 | uint32_t mid = lo + (hi - lo)/2u; | ||
| 1110 | |||
| 1111 | if (s < plan->segments[mid].s_end) | ||
| 1112 | hi = mid; | ||
| 1113 | else | ||
| 1114 | lo = mid; | ||
| 1115 | } | ||
| 1116 | |||
| 1117 | while (lo + 1u < plan->segment_count && s >= plan->segments[lo].s_end) | ||
| 1118 | ++lo; | ||
| 1119 | |||
| 1120 | return lo; | ||
| 1121 | } | ||
| 1122 | |||
| 1123 | void | ||
| 1124 | mp_plan_sample (const struct motion_plan *plan, double t, | ||
| 1125 | struct mp_sample *out) | ||
| 1126 | { | ||
| 1127 | if (!out) | ||
| 1128 | return; | ||
| 1129 | |||
| 1130 | memset (out, 0, sizeof *out); | ||
| 1131 | |||
| 1132 | if (!plan || plan->segment_count == 0u) { | ||
| 1133 | out->t = t; | ||
| 1134 | return; | ||
| 1135 | } | ||
| 1136 | |||
| 1137 | double s = 0.0; | ||
| 1138 | double v = 0.0; | ||
| 1139 | double a_t = 0.0; | ||
| 1140 | double j_t = 0.0; | ||
| 1141 | |||
| 1142 | mp_plan_eval_scalar (plan, t, &s, &v, &a_t, &j_t); | ||
| 1143 | |||
| 1144 | uint32_t si = mp_find_segment_by_s (plan, s); | ||
| 1145 | const struct mp_segment *g = &plan->segments[si]; | ||
| 1146 | double local_s = mp_clamp (s - g->s_begin, 0.0, g->length); | ||
| 1147 | |||
| 1148 | struct mp_vec2 p; | ||
| 1149 | struct mp_vec2 tangent; | ||
| 1150 | struct mp_vec2 normal; | ||
| 1151 | double kappa_geom; | ||
| 1152 | |||
| 1153 | mp_geom_eval_frame (g, local_s, &p, &tangent, &normal, &kappa_geom); | ||
| 1154 | |||
| 1155 | double kappa = mp_effective_kappa (plan, si, local_s, kappa_geom); | ||
| 1156 | double a_n = v*v*kappa; | ||
| 1157 | double a_abs = hypot (a_t, a_n); | ||
| 1158 | |||
| 1159 | struct mp_vec2 vel = mp_vec2_mul (tangent, v); | ||
| 1160 | struct mp_vec2 acc = mp_vec2_add (mp_vec2_mul (tangent, a_t), | ||
| 1161 | mp_vec2_mul (normal, a_n)); | ||
| 1162 | |||
| 1163 | double j_vec_t = j_t - v*v*v*kappa*kappa; | ||
| 1164 | double j_vec_n = 3.0*v*a_t*kappa; | ||
| 1165 | struct mp_vec2 jerk = mp_vec2_add (mp_vec2_mul (tangent, j_vec_t), | ||
| 1166 | mp_vec2_mul (normal, j_vec_n)); | ||
| 1167 | double j_abs = copysign (mp_vec2_len (jerk), j_t); | ||
| 1168 | |||
| 1169 | out->t = mp_clamp (t, 0.0, plan->total_time); | ||
| 1170 | out->s = s; | ||
| 1171 | out->p = p; | ||
| 1172 | out->tangent = tangent; | ||
| 1173 | out->normal = normal; | ||
| 1174 | out->kappa = kappa; | ||
| 1175 | out->kappa_geom = kappa_geom; | ||
| 1176 | out->v = v; | ||
| 1177 | out->a_t = a_t; | ||
| 1178 | out->j_t = j_t; | ||
| 1179 | out->a_n = a_n; | ||
| 1180 | out->a_abs = a_abs; | ||
| 1181 | out->j_abs = j_abs; | ||
| 1182 | out->vel = vel; | ||
| 1183 | out->acc = acc; | ||
| 1184 | out->jerk = jerk; | ||
| 1185 | out->segment_index = si; | ||
| 1186 | out->source_index = g->source_index; | ||
| 1187 | out->source_flags = g->flags; | ||
| 1188 | } | ||
| 1189 | |||
| 1190 | void | ||
| 1191 | mp_plan_write_csv (const struct motion_plan *plan, | ||
| 1192 | double dt, | ||
| 1193 | FILE *out, | ||
| 1194 | int write_header) | ||
| 1195 | { | ||
| 1196 | if (!plan || !out || !(dt > 0.0) || !isfinite (dt)) | ||
| 1197 | return; | ||
| 1198 | |||
| 1199 | if (write_header) { | ||
| 1200 | fputs ("t,s,x,y,v,a_t,j_t,kappa,a_n,a_abs,j_abs," | ||
| 1201 | "vx,vy,ax,ay,jx,jy,tx,ty,nx,ny,segment_index,source_index,source_flags\n", | ||
| 1202 | out); | ||
| 1203 | } | ||
| 1204 | |||
| 1205 | if (plan->segment_count == 0u) | ||
| 1206 | return; | ||
| 1207 | |||
| 1208 | double t = 0.0; | ||
| 1209 | |||
| 1210 | while (t < plan->total_time) { | ||
| 1211 | struct mp_sample smp; | ||
| 1212 | mp_plan_sample (plan, t, &smp); | ||
| 1213 | |||
| 1214 | fprintf (out, | ||
| 1215 | "%.9f,%.9f,%.9f,%.9f,%.9f,%.9f,%.9f,%.12f,%.9f,%.9f,%.9f," | ||
| 1216 | "%.9f,%.9f,%.9f,%.9f,%.9f,%.9f,%.9f,%.9f,%.9f,%.9f,%u,%u,%d\n", | ||
| 1217 | smp.t, smp.s, smp.p.x, smp.p.y, | ||
| 1218 | smp.v, smp.a_t, smp.j_t, smp.kappa, | ||
| 1219 | smp.a_n, smp.a_abs, smp.j_abs, | ||
| 1220 | smp.vel.x, smp.vel.y, | ||
| 1221 | smp.acc.x, smp.acc.y, | ||
| 1222 | smp.jerk.x, smp.jerk.y, | ||
| 1223 | smp.tangent.x, smp.tangent.y, | ||
| 1224 | smp.normal.x, smp.normal.y, | ||
| 1225 | smp.segment_index, smp.source_index, smp.source_flags); | ||
| 1226 | |||
| 1227 | t += dt; | ||
| 1228 | } | ||
| 1229 | |||
| 1230 | struct mp_sample last; | ||
| 1231 | mp_plan_sample (plan, plan->total_time, &last); | ||
| 1232 | |||
| 1233 | fprintf (out, | ||
| 1234 | "%.9f,%.9f,%.9f,%.9f,%.9f,%.9f,%.9f,%.12f,%.9f,%.9f,%.9f," | ||
| 1235 | "%.9f,%.9f,%.9f,%.9f,%.9f,%.9f,%.9f,%.9f,%.9f,%.9f,%u,%u,%d\n", | ||
| 1236 | last.t, last.s, last.p.x, last.p.y, | ||
| 1237 | last.v, last.a_t, last.j_t, last.kappa, | ||
| 1238 | last.a_n, last.a_abs, last.j_abs, | ||
| 1239 | last.vel.x, last.vel.y, | ||
| 1240 | last.acc.x, last.acc.y, | ||
| 1241 | last.jerk.x, last.jerk.y, | ||
| 1242 | last.tangent.x, last.tangent.y, | ||
| 1243 | last.normal.x, last.normal.y, | ||
| 1244 | last.segment_index, last.source_index, last.source_flags); | ||
| 1245 | } | ||
diff --git a/src/motion_planner.h b/src/motion_planner.h new file mode 100644 index 0000000..0073f79 --- /dev/null +++ b/src/motion_planner.h | |||
| @@ -0,0 +1,159 @@ | |||
| 1 | #ifndef INCLUDED_MOTION_PLANNER_H | ||
| 2 | #define INCLUDED_MOTION_PLANNER_H | ||
| 3 | |||
| 4 | #include <stdint.h> | ||
| 5 | #include <stdio.h> | ||
| 6 | #include "path.h" | ||
| 7 | |||
| 8 | #define MP_EPS 1e-9 | ||
| 9 | |||
| 10 | enum mp_status { | ||
| 11 | MP_OK = 0, | ||
| 12 | MP_ERR_INVALID_ARG = -1, | ||
| 13 | MP_ERR_LIMITS = -2, | ||
| 14 | MP_ERR_ALLOC = -3, | ||
| 15 | MP_ERR_GEOMETRY = -4, | ||
| 16 | MP_ERR_PROFILE = -5 | ||
| 17 | }; | ||
| 18 | |||
| 19 | enum mp_geom_type { | ||
| 20 | MP_GEOM_LINE = 1, | ||
| 21 | MP_GEOM_ARC = 2 | ||
| 22 | }; | ||
| 23 | |||
| 24 | enum mp_node_flags { | ||
| 25 | MP_NODE_START = 1u << 0, | ||
| 26 | MP_NODE_END = 1u << 1, | ||
| 27 | MP_NODE_GEOM_GAP = 1u << 2, | ||
| 28 | MP_NODE_STRAIGHT = 1u << 3, | ||
| 29 | MP_NODE_CORNER_LIMIT = 1u << 4, | ||
| 30 | MP_NODE_HARD_STOP = 1u << 5, | ||
| 31 | MP_NODE_SPEED_CHANGE = 1u << 6, | ||
| 32 | MP_NODE_KNOT = 1u << 7 | ||
| 33 | }; | ||
| 34 | |||
| 35 | struct mp_vec2 { | ||
| 36 | double x; | ||
| 37 | double y; | ||
| 38 | }; | ||
| 39 | |||
| 40 | struct mp_limits { | ||
| 41 | double vmax; // mm/s: предел для рабочих G1-перемещений | ||
| 42 | double rapid_vmax; // mm/s: предел для G0; если <= 0, используется vmax | ||
| 43 | double amax; // mm/s^2: скалярное тангенциальное ускорение | ||
| 44 | double jmax; // mm/s^3: скалярный jerk; должен быть > 0 | ||
| 45 | double corner_tol; // mm: виртуальный допуск скругления углов | ||
| 46 | double min_segment_len; // mm: сегменты короче порога игнорируются | ||
| 47 | double default_feed; // mm/s: feed для G1, если path_element.f <= 0 | ||
| 48 | |||
| 49 | double straight_angle_tol; // rad | ||
| 50 | double stop_angle; // rad | ||
| 51 | double corner_speed_deadband; // относительный deadband, например 0.02 | ||
| 52 | |||
| 53 | double curvature_blend_len; // mm | ||
| 54 | }; | ||
| 55 | |||
| 56 | struct mp_segment { | ||
| 57 | enum mp_geom_type type; | ||
| 58 | uint32_t source_index; | ||
| 59 | int flags; | ||
| 60 | |||
| 61 | struct mp_vec2 p0; | ||
| 62 | struct mp_vec2 p1; | ||
| 63 | |||
| 64 | struct mp_vec2 c; // центр дуги | ||
| 65 | double r; // радиус дуги | ||
| 66 | double a0; // начальный угол дуги | ||
| 67 | double sweep; // signed sweep, rad | ||
| 68 | |||
| 69 | double length; // mm | ||
| 70 | double s_begin; // global mm | ||
| 71 | double s_end; // global mm | ||
| 72 | |||
| 73 | double feed; // mm/s: командная скорость до ограничений | ||
| 74 | double v_nominal; // mm/s: скорость участка после ограничений | ||
| 75 | }; | ||
| 76 | |||
| 77 | struct mp_node { | ||
| 78 | double s; // global mm | ||
| 79 | double v_cap; // mm/s: геометрический/командный предел узла | ||
| 80 | double v; // mm/s: скорость после lookahead | ||
| 81 | double theta; // rad: угол между касательными | ||
| 82 | uint32_t flags; // enum mp_node_flags | ||
| 83 | }; | ||
| 84 | |||
| 85 | struct mp_phase { | ||
| 86 | double t_begin; // s | ||
| 87 | double dt; // s | ||
| 88 | |||
| 89 | double s_begin; // mm | ||
| 90 | double s_end; // mm | ||
| 91 | |||
| 92 | double v0; // mm/s | ||
| 93 | double a0; // mm/s^2 | ||
| 94 | double j; // mm/s^3 | ||
| 95 | }; | ||
| 96 | |||
| 97 | struct motion_plan { | ||
| 98 | struct mp_segment *segments; | ||
| 99 | uint32_t segment_count; | ||
| 100 | uint32_t segment_capacity; | ||
| 101 | |||
| 102 | struct mp_node *nodes; | ||
| 103 | uint32_t node_count; | ||
| 104 | uint32_t node_capacity; | ||
| 105 | |||
| 106 | struct mp_phase *phases; | ||
| 107 | uint32_t phase_count; | ||
| 108 | uint32_t phase_capacity; | ||
| 109 | |||
| 110 | double total_length; | ||
| 111 | double total_time; | ||
| 112 | |||
| 113 | double curvature_blend_len; // mm | ||
| 114 | |||
| 115 | double v_min; | ||
| 116 | double v_max; | ||
| 117 | double a_min; | ||
| 118 | double a_max; | ||
| 119 | double j_min; | ||
| 120 | double j_max; | ||
| 121 | }; | ||
| 122 | |||
| 123 | struct mp_sample { | ||
| 124 | double t; | ||
| 125 | double s; | ||
| 126 | |||
| 127 | struct mp_vec2 p; | ||
| 128 | struct mp_vec2 tangent; | ||
| 129 | struct mp_vec2 normal; | ||
| 130 | |||
| 131 | double kappa; | ||
| 132 | double kappa_geom; | ||
| 133 | |||
| 134 | double v; | ||
| 135 | double a_t; | ||
| 136 | double j_t; | ||
| 137 | |||
| 138 | double a_n; | ||
| 139 | double a_abs; | ||
| 140 | double j_abs; | ||
| 141 | |||
| 142 | struct mp_vec2 vel; | ||
| 143 | struct mp_vec2 acc; | ||
| 144 | struct mp_vec2 jerk; | ||
| 145 | |||
| 146 | uint32_t segment_index; | ||
| 147 | uint32_t source_index; | ||
| 148 | int source_flags; | ||
| 149 | }; | ||
| 150 | |||
| 151 | void mp_plan_init (struct motion_plan *plan); | ||
| 152 | void mp_plan_free (struct motion_plan *plan); | ||
| 153 | |||
| 154 | int mp_plan_build (const struct path *path, double initial_x, double initial_y, const struct mp_limits *limits, struct motion_plan *out); | ||
| 155 | void mp_plan_eval_scalar (const struct motion_plan *plan, double t, double *s_out, double *v_out, double *a_out, double *j_out); | ||
| 156 | void mp_plan_sample (const struct motion_plan *plan, double t, struct mp_sample *out); | ||
| 157 | void mp_plan_write_csv (const struct motion_plan *plan, double dt, FILE *out, int write_header); | ||
| 158 | |||
| 159 | #endif // INCLUDED_MOTION_PLANNER_H | ||
diff --git a/src/parse.c b/src/parse.c new file mode 100644 index 0000000..fb147be --- /dev/null +++ b/src/parse.c | |||
| @@ -0,0 +1,98 @@ | |||
| 1 | /// src/parse.h | ||
| 2 | // | ||
| 3 | // Copyright (C) 2026 by Martin Michalec <martin@michalec.dev> | ||
| 4 | // | ||
| 5 | // SPDX-License-Identifier: MIT | ||
| 6 | // | ||
| 7 | /// Commentary: | ||
| 8 | // | ||
| 9 | /// Code: | ||
| 10 | |||
| 11 | #include <stdlib.h> | ||
| 12 | #include <stdio.h> | ||
| 13 | #include <fcntl.h> | ||
| 14 | #include <unistd.h> | ||
| 15 | |||
| 16 | #include "utils.h" | ||
| 17 | #include "arena.h" | ||
| 18 | #include "sv.h" | ||
| 19 | #include "rs274ngc_lexer.h" | ||
| 20 | #include "rs274ngc_cst.h" | ||
| 21 | |||
| 22 | #define INDENTATION 2 | ||
| 23 | |||
| 24 | void | ||
| 25 | print_cst (struct arena *temp, struct rs274ngc_lexer *lexer, struct rs274ngc_cst_branch *root, size_t alignment) | ||
| 26 | { | ||
| 27 | void *bottom = ARENA_COPY (temp, root); | ||
| 28 | ARENA_COPY (temp, alignment); | ||
| 29 | while (temp->tail->free != bottom) { | ||
| 30 | alignment = *(size_t *) arena_pop (temp, sizeof (alignment)); | ||
| 31 | void *node = *(void **) arena_pop (temp, sizeof (node )); | ||
| 32 | ASSERT (node); | ||
| 33 | if (RS274NGC_CST_NODE_KIND (node) < RS274NGC_CST_TERMINAL_COUNT) { // leaf | ||
| 34 | struct rs274ngc_cst_leaf *leaf = &RS274NGC_CST_NODE_PTR (node)->leaf; | ||
| 35 | struct location location = find_location (lexer->sv, leaf->sv); | ||
| 36 | print_location (lexer->filename, location, alignment, "- leaf: %s", | ||
| 37 | rs274ngc_cst_node_kind_names[RS274NGC_CST_NODE_KIND (node)]); | ||
| 38 | } else { // branch | ||
| 39 | struct rs274ngc_cst_branch *branch = &RS274NGC_CST_NODE_PTR (node)->branch; | ||
| 40 | if (1 || RS274NGC_CST_NODE_KIND_EQ (node, LINE)) { | ||
| 41 | struct location location = find_location (lexer->sv, branch->sv); | ||
| 42 | print_location (lexer->filename, location, alignment, "- branch: %s", | ||
| 43 | rs274ngc_cst_node_kind_names[RS274NGC_CST_NODE_KIND (node)]); | ||
| 44 | } | ||
| 45 | alignment += INDENTATION; | ||
| 46 | for (size_t i = branch->count; i > 0; --i) { | ||
| 47 | ASSERT (branch->children[i - 1]); | ||
| 48 | ARENA_COPY (temp, branch->children[i - 1]); | ||
| 49 | ARENA_COPY (temp, alignment); | ||
| 50 | } | ||
| 51 | } | ||
| 52 | } | ||
| 53 | } | ||
| 54 | |||
| 55 | int | ||
| 56 | main (int argc, char *argv[]) | ||
| 57 | { | ||
| 58 | progname = argv[0]; | ||
| 59 | |||
| 60 | const char *filename; | ||
| 61 | int fd = 0; | ||
| 62 | if (argc == 1) { | ||
| 63 | filename = "-"; | ||
| 64 | } else if (argc == 2) { | ||
| 65 | filename = argv[1]; | ||
| 66 | fd = open (filename, O_RDONLY); | ||
| 67 | } else { | ||
| 68 | DIE ("too many arguments provided"); | ||
| 69 | } | ||
| 70 | |||
| 71 | struct arena a = {0}; | ||
| 72 | struct arena t = {0}; | ||
| 73 | |||
| 74 | struct sv rs274ngc = read_until_eof (&a, fd); | ||
| 75 | if (fd) close (fd); | ||
| 76 | |||
| 77 | int base_alignment = strlen (filename) + 15; | ||
| 78 | |||
| 79 | rs274ngc_lexer_compile_regexes (); | ||
| 80 | struct rs274ngc_lexer lexer = rs274ngc_lexer_from_sv (rs274ngc, filename); | ||
| 81 | |||
| 82 | struct rs274ngc_cst_parser parser = { | ||
| 83 | .lexer = &lexer, | ||
| 84 | .output = &a, | ||
| 85 | .temporary = &t, | ||
| 86 | }; | ||
| 87 | struct rs274ngc_cst_branch *program = &RS274NGC_CST_PARSE (parser, PROGRAM)->branch; | ||
| 88 | // ensure no memory leaked | ||
| 89 | ASSERT (t.head == t.tail ); | ||
| 90 | ASSERT (t.head->free == t.head->begin); | ||
| 91 | printf ("Memory used %lu\n", arena_used (parser.output)); | ||
| 92 | |||
| 93 | print_cst (&t, &lexer, program, base_alignment); | ||
| 94 | |||
| 95 | return EXIT_SUCCESS; | ||
| 96 | } | ||
| 97 | |||
| 98 | /// src/parse.h ends here | ||
diff --git a/src/path.c b/src/path.c new file mode 100644 index 0000000..7ded2d2 --- /dev/null +++ b/src/path.c | |||
| @@ -0,0 +1,145 @@ | |||
| 1 | /// src/path.c | ||
| 2 | // | ||
| 3 | // Copyright (C) 2026 by Martin Michalec <martin@michalec.dev> | ||
| 4 | // | ||
| 5 | // SPDX-License-Identifier: MIT | ||
| 6 | // | ||
| 7 | /// Commentary: | ||
| 8 | // | ||
| 9 | // Order of execution: | ||
| 10 | // 1. comment (includes message). | ||
| 11 | // 2. set feed rate mode (G93, G94 — inverse time or per minute). | ||
| 12 | // 3. set feed rate (F). | ||
| 13 | // 4. set spindle speed (S). | ||
| 14 | // 5. select tool (T). | ||
| 15 | // 6. change tool (M6). | ||
| 16 | // 7. spindle on or off (M3, M4, M5). | ||
| 17 | // 8. coolant on or off (M7, M8, M9). | ||
| 18 | // 9. enable or disable overrides (M48, M49). | ||
| 19 | // 10. dwell (G4). | ||
| 20 | // 11. set active plane (G17, G18, G19). | ||
| 21 | // 12. set length units (G20, G21). | ||
| 22 | // 13. cutter radius compensation on or off (G40, G41, G42) | ||
| 23 | // 14. cutter length compensation on or off (G43, G49) | ||
| 24 | // 15. coordinate system selection (G54, G55, G56, G57, G58, G59, | ||
| 25 | // G59.1, G59.2, G59.3). | ||
| 26 | // 16. set path control mode (G61, G61.1, G64) | ||
| 27 | // 17. set distance mode (G90, G91). | ||
| 28 | // 18. set retract mode (G98, G99). | ||
| 29 | // 19. home (G28, G30) or change coordinate system data (G10) or set | ||
| 30 | // axis offsets (G92, G92.1, G92.2, G94). | ||
| 31 | // 20. perform motion (G0 to G3, G80 to G89), as modified (possibly) by G53. | ||
| 32 | // 21. stop (M0, M1, M2, M30, M60). | ||
| 33 | // | ||
| 34 | /// Code: | ||
| 35 | |||
| 36 | #include <math.h> | ||
| 37 | #include "path.h" | ||
| 38 | #include "rs274ngc_state.h" | ||
| 39 | #include "da.h" | ||
| 40 | |||
| 41 | struct path | ||
| 42 | build_path (struct rs274ngc_cst_parser parser) | ||
| 43 | { | ||
| 44 | struct rs274ngc_state state = { | ||
| 45 | // optionally set defaults, but ZII seems to do the job | ||
| 46 | }; | ||
| 47 | |||
| 48 | struct path path = {0}; | ||
| 49 | double prev_x = 0; | ||
| 50 | double prev_y = 0; | ||
| 51 | |||
| 52 | while (rs274ngc_state_next (&state, parser)) { | ||
| 53 | // printf ("move %2d | %10.4lf | %10.4lf | %10.4lf | %.*s\n", state.current_motion_mode, state.x, state.y, state.f, SV_FMTA (state.line)); | ||
| 54 | if (state.words_set & (X_MASK | Y_MASK)) { | ||
| 55 | struct path_element pe = { .line = state.line }; | ||
| 56 | pe.line.end += 1; // HACK(cmmm): this should be fixed in parser | ||
| 57 | switch (state.distance_mode) { | ||
| 58 | case DISTANCE_MODE_ABSOLUTE: { | ||
| 59 | pe.x = state.x; | ||
| 60 | pe.y = state.y; | ||
| 61 | } break; | ||
| 62 | case DISTANCE_MODE_INCREMENTAL: { | ||
| 63 | pe.x = prev_x + state.x*((state.words_set & X_MASK) != 0); | ||
| 64 | pe.y = prev_y + state.y*((state.words_set & Y_MASK) != 0); | ||
| 65 | } break; | ||
| 66 | } | ||
| 67 | |||
| 68 | if (state.current_motion_mode == MOTION_RAPID_POSITIONING) { | ||
| 69 | pe.flags |= PEF_TRAVERSING; | ||
| 70 | pe.f = 100; // TODO(cmmm): take as arg | ||
| 71 | } | ||
| 72 | else | ||
| 73 | pe.f = state.f/60; | ||
| 74 | |||
| 75 | if (state.current_motion_mode == MOTION_CIRCULAR_INTERPOLATION_CW || | ||
| 76 | state.current_motion_mode == MOTION_CIRCULAR_INTERPOLATION_CCW) { | ||
| 77 | pe.flags |= PEF_ARC; | ||
| 78 | if (state.words_set & R_MASK) { | ||
| 79 | // NOTE(cmmm): maybe we can use just one sqrt | ||
| 80 | double x0 = prev_x; | ||
| 81 | double y0 = prev_y; | ||
| 82 | double x1 = state.x; | ||
| 83 | double y1 = state.y; | ||
| 84 | double r = state.r; | ||
| 85 | double hdx = (x1 - x0)/2; | ||
| 86 | double hdy = (y1 - y0)/2; | ||
| 87 | double d = sqrt (hdx*hdx + hdy*hdy); | ||
| 88 | double nx = -hdy/d; | ||
| 89 | double ny = hdx/d; | ||
| 90 | double h = sqrt (r*r - d*d); | ||
| 91 | if (r > 0 && state.current_motion_mode == MOTION_CIRCULAR_INTERPOLATION_CW || | ||
| 92 | r < 0 && state.current_motion_mode == MOTION_CIRCULAR_INTERPOLATION_CCW) { | ||
| 93 | h *= -1; // make center right | ||
| 94 | } | ||
| 95 | pe.i = prev_x + hdx + nx*h; | ||
| 96 | pe.j = prev_y + hdy + ny*h; | ||
| 97 | } else if (state.words_set & (I_MASK | J_MASK)) { | ||
| 98 | pe.i = prev_x + state.i; | ||
| 99 | pe.j = prev_y + state.j; | ||
| 100 | } | ||
| 101 | if (state.current_motion_mode == MOTION_CIRCULAR_INTERPOLATION_CCW) | ||
| 102 | pe.flags |= PEF_CCW; | ||
| 103 | |||
| 104 | // printf ("move %2d | %10.4lf | %10.4lf | %10.4lf | %10.4lf | %.*s\n", state.current_motion_mode, state.x, state.y, state.i, state.j, SV_FMTA (state.line)); | ||
| 105 | DA_APPEND (path, pe); | ||
| 106 | } else if (pe.x != prev_x || pe.y != prev_y) { | ||
| 107 | DA_APPEND (path, pe); | ||
| 108 | } | ||
| 109 | |||
| 110 | switch (state.distance_mode) { | ||
| 111 | case DISTANCE_MODE_ABSOLUTE: { | ||
| 112 | prev_x = state.x; | ||
| 113 | prev_y = state.y; | ||
| 114 | } break; | ||
| 115 | case DISTANCE_MODE_INCREMENTAL: { | ||
| 116 | prev_x += ((state.words_set & X_MASK) != 0)*state.x; | ||
| 117 | prev_y += ((state.words_set & Y_MASK) != 0)*state.y; | ||
| 118 | } break; | ||
| 119 | } | ||
| 120 | } | ||
| 121 | |||
| 122 | if (state.stopping == STOPPING_END) | ||
| 123 | break; | ||
| 124 | } | ||
| 125 | |||
| 126 | return path; | ||
| 127 | } | ||
| 128 | |||
| 129 | struct vec2 | ||
| 130 | path_element_start (const struct path *path, const struct path_element *pe) | ||
| 131 | { | ||
| 132 | struct vec2 start; | ||
| 133 | |||
| 134 | if (pe == path->items) { | ||
| 135 | start.x = path->initial_x; | ||
| 136 | start.y = path->initial_y; | ||
| 137 | } else { | ||
| 138 | start.x = pe[-1].x; | ||
| 139 | start.y = pe[-1].y; | ||
| 140 | } | ||
| 141 | |||
| 142 | return start; | ||
| 143 | } | ||
| 144 | |||
| 145 | /// src/path.c ends here | ||
diff --git a/src/path.h b/src/path.h new file mode 100644 index 0000000..2355021 --- /dev/null +++ b/src/path.h | |||
| @@ -0,0 +1,46 @@ | |||
| 1 | /// src/path.h | ||
| 2 | // | ||
| 3 | // Copyright (C) 2026 by Martin Michalec <martin@michalec.dev> | ||
| 4 | // | ||
| 5 | // SPDX-License-Identifier: MIT | ||
| 6 | // | ||
| 7 | /// Commentary: | ||
| 8 | // | ||
| 9 | /// Code: | ||
| 10 | |||
| 11 | #ifndef INCLUDED_PATH_H | ||
| 12 | #define INCLUDED_PATH_H | ||
| 13 | |||
| 14 | #include "utils.h" | ||
| 15 | #include "rs274ngc_cst.h" | ||
| 16 | #include "vec2.h" | ||
| 17 | |||
| 18 | #define PEF_TRAVERSING (1 << 0) // 0 means technological | ||
| 19 | #define PEF_ARC (1 << 1) // 0 means line | ||
| 20 | #define PEF_CCW (1 << 2) // 0 means CW | ||
| 21 | #define PEF_RELATIVE (1 << 3) // 0 means absolute | ||
| 22 | #define PEF_INCH (1 << 4) // 0 means mm | ||
| 23 | // ... | ||
| 24 | |||
| 25 | struct path_element { | ||
| 26 | struct sv line; | ||
| 27 | double x, y; // end coords (abs mm) | ||
| 28 | double f; // feed rate (mm/s) | ||
| 29 | double i, j; // centers for arcs (abs mm) | ||
| 30 | int flags; | ||
| 31 | }; | ||
| 32 | |||
| 33 | struct path { | ||
| 34 | struct path_element *items; | ||
| 35 | uint32_t count; | ||
| 36 | uint32_t capacity; | ||
| 37 | double initial_x; | ||
| 38 | double initial_y; | ||
| 39 | }; | ||
| 40 | |||
| 41 | struct path build_path (struct rs274ngc_cst_parser parser); | ||
| 42 | struct vec2 path_element_start (const struct path *, const struct path_element *); | ||
| 43 | |||
| 44 | #endif // INCLUDED_PATH_H | ||
| 45 | |||
| 46 | /// src/path.h ends here | ||
diff --git a/src/rate.c b/src/rate.c new file mode 100644 index 0000000..33def16 --- /dev/null +++ b/src/rate.c | |||
| @@ -0,0 +1,134 @@ | |||
| 1 | #include "rate.h" | ||
| 2 | #include <math.h> | ||
| 3 | #include <float.h> | ||
| 4 | #include <string.h> | ||
| 5 | |||
| 6 | static int | ||
| 7 | work_motion_is_working_pe (const struct path_element *pe) | ||
| 8 | { | ||
| 9 | if (!pe) | ||
| 10 | return 0; | ||
| 11 | |||
| 12 | return ~pe->flags & PEF_TRAVERSING; | ||
| 13 | } | ||
| 14 | |||
| 15 | static double | ||
| 16 | work_motion_clamp (double x, double lo, double hi) | ||
| 17 | { | ||
| 18 | return x < lo ? lo : (x > hi ? hi : x); | ||
| 19 | } | ||
| 20 | |||
| 21 | /* | ||
| 22 | * Находит время t, в которое глобальная координата траектории равна s. | ||
| 23 | * Нужно, чтобы интегрировать строго по рабочим segment.s_begin..segment.s_end, | ||
| 24 | * а не смешивать рабочие и холостые участки одним временным шагом. | ||
| 25 | */ | ||
| 26 | static double | ||
| 27 | work_motion_time_at_s (const struct motion_plan *plan, double s) | ||
| 28 | { | ||
| 29 | if (!plan || !(plan->total_time > 0.0)) | ||
| 30 | return 0.0; | ||
| 31 | |||
| 32 | if (s <= 0.0) | ||
| 33 | return 0.0; | ||
| 34 | |||
| 35 | if (s >= plan->total_length) | ||
| 36 | return plan->total_time; | ||
| 37 | |||
| 38 | double lo = 0.0; | ||
| 39 | double hi = plan->total_time; | ||
| 40 | |||
| 41 | for (int i = 0; i < 80; ++i) { | ||
| 42 | double mid = 0.5*(lo + hi); | ||
| 43 | double smid = 0.0; | ||
| 44 | |||
| 45 | mp_plan_eval_scalar (plan, mid, &smid, NULL, NULL, NULL); | ||
| 46 | |||
| 47 | if (smid < s) | ||
| 48 | lo = mid; | ||
| 49 | else | ||
| 50 | hi = mid; | ||
| 51 | } | ||
| 52 | |||
| 53 | return 0.5*(lo + hi); | ||
| 54 | } | ||
| 55 | |||
| 56 | /* | ||
| 57 | * dt -- шаг численного интегрирования в секундах. | ||
| 58 | * Для текущей визуализации можно использовать 0.001. | ||
| 59 | */ | ||
| 60 | struct work_motion_stats | ||
| 61 | measure_work_motion_stats (const struct path *path, | ||
| 62 | const struct motion_plan *plan, | ||
| 63 | double dt) | ||
| 64 | { | ||
| 65 | ASSERT (path); | ||
| 66 | ASSERT (plan); | ||
| 67 | ASSERT (plan->segment_count > 0); | ||
| 68 | ASSERT (plan->total_time > 0); | ||
| 69 | ASSERT (dt > 0); | ||
| 70 | ASSERT (isfinite (dt)); | ||
| 71 | |||
| 72 | struct work_motion_stats out = {0}; | ||
| 73 | out.dt = dt; | ||
| 74 | |||
| 75 | for (uint32_t si = 0; si < plan->segment_count; ++si) { | ||
| 76 | const struct mp_segment *seg = &plan->segments[si]; | ||
| 77 | |||
| 78 | ASSERT (seg->source_index < path->count); | ||
| 79 | |||
| 80 | const struct path_element *pe = &path->items[seg->source_index]; | ||
| 81 | |||
| 82 | if (!work_motion_is_working_pe (pe)) | ||
| 83 | continue; | ||
| 84 | |||
| 85 | double t0 = work_motion_time_at_s (plan, seg->s_begin); | ||
| 86 | double t1 = work_motion_time_at_s (plan, seg->s_end); | ||
| 87 | |||
| 88 | t0 = work_motion_clamp (t0, 0, plan->total_time); | ||
| 89 | t1 = work_motion_clamp (t1, 0, plan->total_time); | ||
| 90 | |||
| 91 | if (!(t1 > t0)) | ||
| 92 | continue; | ||
| 93 | |||
| 94 | out.active_segment_count += 1; | ||
| 95 | out.active_length += seg->length; | ||
| 96 | |||
| 97 | for (double t = t0; t < t1;) { | ||
| 98 | double h = fmin (dt, t1 - t); | ||
| 99 | double tm = t + h/2; | ||
| 100 | |||
| 101 | struct mp_sample sample; | ||
| 102 | mp_plan_sample (plan, tm, &sample); | ||
| 103 | |||
| 104 | /* | ||
| 105 | * Берём v_nominal именно у текущего рабочего сегмента. | ||
| 106 | * Это устойчивее, чем брать sample.segment_index на границе сегментов. | ||
| 107 | */ | ||
| 108 | double v_ref = seg->v_nominal; | ||
| 109 | double e = sample.v - v_ref; | ||
| 110 | // double e = (sample.v - v_ref)/v_ref; | ||
| 111 | double e_abs = fabs (e); | ||
| 112 | |||
| 113 | out.speed_error_abs_integral += e_abs*h; | ||
| 114 | out.speed_error_sq_integral += e*e*h; | ||
| 115 | out.speed_error_max_abs = fmax (out.speed_error_max_abs, e_abs); | ||
| 116 | |||
| 117 | out.jerk_abs_integral += fabs (sample.j_abs)*h; | ||
| 118 | out.jerk_abs_max = fmax (out.jerk_abs_max, fabs (sample.j_abs)); | ||
| 119 | |||
| 120 | out.active_time += h; | ||
| 121 | out.sample_count += 1; | ||
| 122 | |||
| 123 | t += h; | ||
| 124 | } | ||
| 125 | } | ||
| 126 | |||
| 127 | if (out.active_time > 0) { | ||
| 128 | out.speed_error_mean_abs = out.speed_error_abs_integral/out.active_time; | ||
| 129 | out.speed_error_rms = sqrt (out.speed_error_sq_integral/out.active_time); | ||
| 130 | out.jerk_abs_mean = out.jerk_abs_integral/out.active_time; | ||
| 131 | } | ||
| 132 | |||
| 133 | return out; | ||
| 134 | } | ||
diff --git a/src/rate.h b/src/rate.h new file mode 100644 index 0000000..b75b064 --- /dev/null +++ b/src/rate.h | |||
| @@ -0,0 +1,40 @@ | |||
| 1 | #ifndef INCLUDED_RATE_H | ||
| 2 | #define INCLUDED_RATE_H | ||
| 3 | |||
| 4 | #include "motion_planner.h" | ||
| 5 | |||
| 6 | struct work_motion_stats { | ||
| 7 | double dt; | ||
| 8 | |||
| 9 | double active_time; /* s */ | ||
| 10 | double active_length; /* mm */ | ||
| 11 | uint32_t active_segment_count; | ||
| 12 | uint32_t sample_count; | ||
| 13 | |||
| 14 | /* | ||
| 15 | * Отклонение скорости на рабочих участках. | ||
| 16 | * | ||
| 17 | * Ошибка считается как: | ||
| 18 | * e(t) = sample.v - segment.v_nominal | ||
| 19 | */ | ||
| 20 | double speed_error_max_abs; /* mm/s */ | ||
| 21 | double speed_error_mean_abs; /* mm/s */ | ||
| 22 | double speed_error_rms; /* mm/s */ | ||
| 23 | |||
| 24 | double speed_error_abs_integral; /* mm, т.к. integral |e| dt */ | ||
| 25 | double speed_error_sq_integral; /* mm^2/s, т.к. integral e^2 dt */ | ||
| 26 | |||
| 27 | /* | ||
| 28 | * Общий рывок на рабочих участках. | ||
| 29 | * | ||
| 30 | * Используется sample.j_abs, то есть модуль полного векторного рывка, | ||
| 31 | * а не только тангенциальный j_t. | ||
| 32 | */ | ||
| 33 | double jerk_abs_integral; /* mm/s^2, т.к. integral |j| dt */ | ||
| 34 | double jerk_abs_mean; /* mm/s^3 */ | ||
| 35 | double jerk_abs_max; /* mm/s^3 */ | ||
| 36 | }; | ||
| 37 | |||
| 38 | struct work_motion_stats measure_work_motion_stats (const struct path *, const struct motion_plan *, double dt); | ||
| 39 | |||
| 40 | #endif // INCLUDED_RATE_H | ||
diff --git a/src/rs274ngc_cst.c b/src/rs274ngc_cst.c new file mode 100644 index 0000000..b2dd582 --- /dev/null +++ b/src/rs274ngc_cst.c | |||
| @@ -0,0 +1,279 @@ | |||
| 1 | /// src/rs274ngc_cst.c --- RS274NGC Concrete Syntax Tree | ||
| 2 | // | ||
| 3 | // Copyright (C) 2026 by Martin Michalec <martin@michalec.dev> | ||
| 4 | // | ||
| 5 | // SPDX-License-Identifier: MIT | ||
| 6 | // | ||
| 7 | /// Commentary: | ||
| 8 | // | ||
| 9 | /// Code: | ||
| 10 | |||
| 11 | #include <stdbool.h> | ||
| 12 | #include <stdarg.h> | ||
| 13 | #include <stdio.h> | ||
| 14 | #include "utils.h" | ||
| 15 | #include "rs274ngc_cst.h" | ||
| 16 | |||
| 17 | #ifndef ARENA_ASSERT | ||
| 18 | #include <assert.h> | ||
| 19 | #define ASSERT assert | ||
| 20 | #else | ||
| 21 | #define ASSERT ARENA_ASSERT | ||
| 22 | #endif | ||
| 23 | |||
| 24 | #define X(SYM, ...) [RS274NGC_CST_NODE_KIND_##SYM] = #SYM, | ||
| 25 | const char *rs274ngc_cst_node_kind_names[RS274NGC_CST_NODE_KIND_COUNT] = { | ||
| 26 | [RS274NGC_CST_NODE_KIND_INVALID ] = "INVALID", | ||
| 27 | [RS274NGC_CST_NODE_KIND_END_OF_LINE] = "END_OF_LINE", | ||
| 28 | [RS274NGC_CST_NODE_KIND_END_OF_FILE] = "END_OF_FILE", | ||
| 29 | RS274NGC_CST_NODE_KINDS () | ||
| 30 | }; | ||
| 31 | #undef X | ||
| 32 | |||
| 33 | static void | ||
| 34 | print_error (struct rs274ngc_lexer *lexer, const char *point, | ||
| 35 | const char *format, ...) | ||
| 36 | { | ||
| 37 | int row = 1; | ||
| 38 | int col = 1; | ||
| 39 | |||
| 40 | for (const char *head = lexer->sv.beg; head < point; ++head) { | ||
| 41 | col += 1; | ||
| 42 | if (*head == '\n') { | ||
| 43 | row += 1; | ||
| 44 | col = 1; | ||
| 45 | } | ||
| 46 | }; | ||
| 47 | |||
| 48 | fprintf (stderr, "%s:%d:%d: error: ", lexer->filename, row, col); | ||
| 49 | |||
| 50 | va_list ap; | ||
| 51 | va_start (ap, format); | ||
| 52 | vfprintf (stderr, format, ap); | ||
| 53 | va_end (ap); | ||
| 54 | |||
| 55 | putc ('\n', stderr); | ||
| 56 | } | ||
| 57 | |||
| 58 | #define PARSE_BRANCH_NODE(P, B, K) \ | ||
| 59 | parse_branch_node (P, B, RS274NGC_CST_NODE_KIND_##K) | ||
| 60 | #define PARSE_BRANCH_NODE_IF(P, B, K, L) \ | ||
| 61 | (((P).lexer->lexeme.kind == RS274NGC_LEXEME_KIND_##L) \ | ||
| 62 | ? parse_branch_node (P, B, RS274NGC_CST_NODE_KIND_##K) : false) | ||
| 63 | #define PARSE_BRANCH_NODE_IF_SELF(P, B, L) \ | ||
| 64 | (((P).lexer->lexeme.kind == RS274NGC_LEXEME_KIND_##L) \ | ||
| 65 | ? parse_branch_node (P, B, RS274NGC_CST_NODE_KIND_##L) : false) | ||
| 66 | static bool | ||
| 67 | parse_branch_node (struct rs274ngc_cst_parser parser, | ||
| 68 | struct rs274ngc_cst_branch *branch, | ||
| 69 | enum rs274ngc_cst_node_kind kind) | ||
| 70 | { | ||
| 71 | union rs274ngc_cst_node *node = rs274ngc_cst_parse_node (parser, kind); | ||
| 72 | |||
| 73 | if (node == NULL) | ||
| 74 | return false; | ||
| 75 | |||
| 76 | ARENA_COPY (parser.temporary, node); | ||
| 77 | branch->count += 1; | ||
| 78 | |||
| 79 | return true; | ||
| 80 | } | ||
| 81 | |||
| 82 | #define LEXEME_MATCHES(P, K) \ | ||
| 83 | ((P).lexer->lexeme.kind == RS274NGC_LEXEME_KIND_##K) | ||
| 84 | |||
| 85 | struct rs274ngc_cst_leaf * | ||
| 86 | rs274ngc_cst_parse_leaf (struct rs274ngc_cst_parser parser, | ||
| 87 | enum rs274ngc_cst_node_kind kind) | ||
| 88 | { | ||
| 89 | ASSERT (kind < RS274NGC_CST_TERMINAL_COUNT); | ||
| 90 | |||
| 91 | if (parser.lexer->lexeme.kind != (enum rs274ngc_lexeme_kind) kind) | ||
| 92 | return NULL; | ||
| 93 | |||
| 94 | struct rs274ngc_cst_leaf leaf = { .sv = parser.lexer->lexeme.sv }; | ||
| 95 | void *ptr = ARENA_COPY (parser.output, leaf); | ||
| 96 | rs274ngc_lexer_next_lexeme (parser.lexer); | ||
| 97 | |||
| 98 | return (struct rs274ngc_cst_leaf *) RS274NGC_CST_TAG_NODE (ptr, kind); | ||
| 99 | } | ||
| 100 | |||
| 101 | struct rs274ngc_cst_branch * | ||
| 102 | rs274ngc_cst_parse_branch (struct rs274ngc_cst_parser parser, | ||
| 103 | enum rs274ngc_cst_node_kind kind) | ||
| 104 | { | ||
| 105 | ASSERT (kind >= RS274NGC_CST_TERMINAL_COUNT); | ||
| 106 | ASSERT (kind < RS274NGC_CST_NODE_KIND_COUNT); | ||
| 107 | |||
| 108 | // printf ("Parsing: %s\n", rs274ngc_cst_node_kind_names[kind]); | ||
| 109 | |||
| 110 | struct rs274ngc_cst_branch branch = { | ||
| 111 | .sv.beg = parser.lexer->lexeme.sv.beg | ||
| 112 | }; | ||
| 113 | |||
| 114 | const char *cursor = parser.lexer->cursor; | ||
| 115 | struct arena_checkpoint children = | ||
| 116 | arena_checkpoint (parser.temporary, ALIGNOF (void *) - 1); | ||
| 117 | switch (kind) { | ||
| 118 | case RS274NGC_CST_NODE_KIND_PROGRAM: { | ||
| 119 | while (!LEXEME_MATCHES (parser, END_OF_FILE)) { | ||
| 120 | if (PARSE_BRANCH_NODE (parser, &branch, LINE)) | ||
| 121 | continue; | ||
| 122 | |||
| 123 | struct location location = | ||
| 124 | find_location (parser.lexer->sv, parser.lexer->lexeme.sv); | ||
| 125 | print_location (parser.lexer->filename, location, 0, "failed: " SV_FMT, | ||
| 126 | SV_FMTA (parser.lexer->lexeme.sv)); | ||
| 127 | for (;;) { | ||
| 128 | rs274ngc_lexer_next_lexeme (parser.lexer); | ||
| 129 | if (LEXEME_MATCHES (parser, END_OF_FILE)) break; | ||
| 130 | if (LEXEME_MATCHES (parser, END_OF_LINE)) { | ||
| 131 | rs274ngc_lexer_next_lexeme (parser.lexer); | ||
| 132 | break; | ||
| 133 | } | ||
| 134 | } | ||
| 135 | } | ||
| 136 | } break; | ||
| 137 | case RS274NGC_CST_NODE_KIND_LINE: { | ||
| 138 | PARSE_BRANCH_NODE_IF (parser, &branch, BLOCK_DELETE, SLASH); | ||
| 139 | PARSE_BRANCH_NODE_IF_SELF (parser, &branch, LINE_NUMBER); | ||
| 140 | while (!LEXEME_MATCHES (parser, END_OF_LINE) && | ||
| 141 | !LEXEME_MATCHES (parser, END_OF_FILE)) { | ||
| 142 | if (!PARSE_BRANCH_NODE (parser, &branch, SEGMENT)) goto fail; | ||
| 143 | } rs274ngc_lexer_next_lexeme (parser.lexer); // skip END_OF_LINE | ||
| 144 | } break; | ||
| 145 | case RS274NGC_CST_NODE_KIND_SEGMENT: { | ||
| 146 | if (PARSE_BRANCH_NODE_IF (parser, &branch, WORD, WORD_LETTER )) break; | ||
| 147 | if (PARSE_BRANCH_NODE_IF (parser, &branch, PARAMETER_SETTING, PARAMETER_SIGN)) break; | ||
| 148 | if (PARSE_BRANCH_NODE (parser, &branch, COMMENT )) break; | ||
| 149 | goto fail; | ||
| 150 | } break; | ||
| 151 | case RS274NGC_CST_NODE_KIND_WORD: { | ||
| 152 | if (!PARSE_BRANCH_NODE_IF_SELF (parser, &branch, WORD_LETTER)) goto fail; | ||
| 153 | if (!PARSE_BRANCH_NODE (parser, &branch, REAL_VALUE )) goto fail; | ||
| 154 | } break; | ||
| 155 | case RS274NGC_CST_NODE_KIND_PARAMETER_INDEX: { | ||
| 156 | if (PARSE_BRANCH_NODE (parser, &branch, REAL_VALUE)) break; | ||
| 157 | goto fail; | ||
| 158 | } break; | ||
| 159 | case RS274NGC_CST_NODE_KIND_REAL_VALUE: { | ||
| 160 | if (PARSE_BRANCH_NODE (parser, &branch, REAL_NUMBER )) break; | ||
| 161 | if (PARSE_BRANCH_NODE (parser, &branch, EXPRESSION )) break; | ||
| 162 | if (PARSE_BRANCH_NODE_IF (parser, &branch, PARAMETER_VALUE, PARAMETER_SIGN)) break; | ||
| 163 | if (PARSE_BRANCH_NODE (parser, &branch, UNARY_COMBO )) break; | ||
| 164 | goto fail; | ||
| 165 | } break; | ||
| 166 | case RS274NGC_CST_NODE_KIND_REAL_NUMBER: { | ||
| 167 | if (!PARSE_BRANCH_NODE_IF_SELF (parser, &branch, MINUS)) | ||
| 168 | PARSE_BRANCH_NODE_IF_SELF (parser, &branch, PLUS); | ||
| 169 | if (PARSE_BRANCH_NODE (parser, &branch, REAL_NUMBER_NO_SIGN)) break; | ||
| 170 | goto fail; | ||
| 171 | } break; | ||
| 172 | case RS274NGC_CST_NODE_KIND_EXPRESSION: { | ||
| 173 | if (!PARSE_BRANCH_NODE (parser, &branch, BRACKET_LEFT)) goto fail; | ||
| 174 | if (!PARSE_BRANCH_NODE (parser, &branch, REAL_VALUE )) goto fail; | ||
| 175 | while (!LEXEME_MATCHES (parser, BRACKET_RIGHT)) { | ||
| 176 | if (!PARSE_BRANCH_NODE (parser, &branch, BINARY_OPERATION)) goto fail; | ||
| 177 | if (!PARSE_BRANCH_NODE (parser, &branch, REAL_VALUE )) goto fail; | ||
| 178 | } | ||
| 179 | if (!PARSE_BRANCH_NODE (parser, &branch, BRACKET_RIGHT)) goto fail; | ||
| 180 | } break; | ||
| 181 | case RS274NGC_CST_NODE_KIND_COMMENT: { | ||
| 182 | if (PARSE_BRANCH_NODE (parser, &branch, ORDINARY_COMMENT)) break; | ||
| 183 | if (PARSE_BRANCH_NODE (parser, &branch, MESSAGE )) break; | ||
| 184 | goto fail; | ||
| 185 | } break; | ||
| 186 | case RS274NGC_CST_NODE_KIND_BINARY_OPERATION: { | ||
| 187 | if (PARSE_BRANCH_NODE_IF_SELF (parser, &branch, POWER )) break; | ||
| 188 | if (PARSE_BRANCH_NODE_IF_SELF (parser, &branch, TIMES )) break; | ||
| 189 | if (PARSE_BRANCH_NODE_IF (parser, &branch, DIVIDED_BY, SLASH)) break; | ||
| 190 | if (PARSE_BRANCH_NODE_IF_SELF (parser, &branch, MODULO )) break; | ||
| 191 | if (PARSE_BRANCH_NODE_IF_SELF (parser, &branch, PLUS )) break; | ||
| 192 | if (PARSE_BRANCH_NODE_IF_SELF (parser, &branch, MINUS )) break; | ||
| 193 | if (PARSE_BRANCH_NODE_IF_SELF (parser, &branch, EXCLUSIVE_OR )) break; | ||
| 194 | if (PARSE_BRANCH_NODE_IF_SELF (parser, &branch, NON_EXCLUSIVE_OR )) break; | ||
| 195 | if (PARSE_BRANCH_NODE_IF_SELF (parser, &branch, AND )) break; | ||
| 196 | goto fail; | ||
| 197 | } break; | ||
| 198 | case RS274NGC_CST_NODE_KIND_BLOCK_DELETE: | ||
| 199 | case RS274NGC_CST_NODE_KIND_DIVIDED_BY: { | ||
| 200 | if (PARSE_BRANCH_NODE (parser, &branch, SLASH)) break; | ||
| 201 | goto fail; | ||
| 202 | } break; | ||
| 203 | case RS274NGC_CST_NODE_KIND_PARAMETER_VALUE: { | ||
| 204 | if (!PARSE_BRANCH_NODE (parser, &branch, PARAMETER_SIGN)) goto fail; | ||
| 205 | if (!PARSE_BRANCH_NODE (parser, &branch, REAL_VALUE )) goto fail; | ||
| 206 | } break; | ||
| 207 | case RS274NGC_CST_NODE_KIND_UNARY_COMBO: { | ||
| 208 | if (PARSE_BRANCH_NODE (parser, &branch, ORDINARY_UNARY_COMBO)) break; | ||
| 209 | if (PARSE_BRANCH_NODE (parser, &branch, ARC_TANGENT_COMBO )) break; | ||
| 210 | goto fail; | ||
| 211 | } break; | ||
| 212 | case RS274NGC_CST_NODE_KIND_ORDINARY_UNARY_COMBO: { | ||
| 213 | do { | ||
| 214 | if (PARSE_BRANCH_NODE_IF_SELF (parser, &branch, ABSOLUTE_VALUE)) break; | ||
| 215 | if (PARSE_BRANCH_NODE_IF_SELF (parser, &branch, ARC_COSINE )) break; | ||
| 216 | if (PARSE_BRANCH_NODE_IF_SELF (parser, &branch, ARC_SINE )) break; | ||
| 217 | if (PARSE_BRANCH_NODE_IF_SELF (parser, &branch, COSINE )) break; | ||
| 218 | if (PARSE_BRANCH_NODE_IF_SELF (parser, &branch, SINE )) break; | ||
| 219 | if (PARSE_BRANCH_NODE_IF_SELF (parser, &branch, E_RAISED_TO )) break; | ||
| 220 | if (PARSE_BRANCH_NODE_IF_SELF (parser, &branch, NATURAL_LOG_OF)) break; | ||
| 221 | if (PARSE_BRANCH_NODE_IF_SELF (parser, &branch, FIX_DOWN )) break; | ||
| 222 | if (PARSE_BRANCH_NODE_IF_SELF (parser, &branch, FIX_UP )) break; | ||
| 223 | if (PARSE_BRANCH_NODE_IF_SELF (parser, &branch, ROUND )) break; | ||
| 224 | if (PARSE_BRANCH_NODE_IF_SELF (parser, &branch, SQUARE_ROOT )) break; | ||
| 225 | if (PARSE_BRANCH_NODE_IF_SELF (parser, &branch, TANGENT )) break; | ||
| 226 | } while (0); | ||
| 227 | if (!PARSE_BRANCH_NODE (parser, &branch, EXPRESSION)) | ||
| 228 | goto fail; | ||
| 229 | } break; | ||
| 230 | case RS274NGC_CST_NODE_KIND_ARC_TANGENT_COMBO: { | ||
| 231 | if (!PARSE_BRANCH_NODE_IF_SELF (parser, &branch, ARC_TANGENT )) goto fail; | ||
| 232 | if (!PARSE_BRANCH_NODE (parser, &branch, EXPRESSION )) goto fail; | ||
| 233 | if (!PARSE_BRANCH_NODE_IF (parser, &branch, DIVIDED_BY, SLASH)) goto fail; | ||
| 234 | if (!PARSE_BRANCH_NODE (parser, &branch, EXPRESSION )) goto fail; | ||
| 235 | } break; | ||
| 236 | case RS274NGC_CST_NODE_KIND_PARAMETER_SETTING: { | ||
| 237 | if (!PARSE_BRANCH_NODE_IF_SELF (parser, &branch, PARAMETER_SIGN )) goto fail; | ||
| 238 | if (!PARSE_BRANCH_NODE (parser, &branch, PARAMETER_INDEX)) goto fail; | ||
| 239 | if (!PARSE_BRANCH_NODE_IF_SELF (parser, &branch, EQUAL_SIGN )) goto fail; | ||
| 240 | if (!PARSE_BRANCH_NODE (parser, &branch, REAL_VALUE )) goto fail; | ||
| 241 | } break; | ||
| 242 | default: return NULL; | ||
| 243 | } | ||
| 244 | |||
| 245 | if (branch.count == 0) | ||
| 246 | return NULL; | ||
| 247 | size_t children_size = branch.count*sizeof (*branch.children); | ||
| 248 | struct rs274ngc_cst_branch *ptr = | ||
| 249 | arena_reserve (parser.output, sizeof (branch) + children_size, ALIGNOF (*ptr) - 1); | ||
| 250 | ASSERT (ptr != NULL); | ||
| 251 | ARENA_COPY_FAST (parser.output, branch); | ||
| 252 | void *other = arena_coalesce_from_into_fast (parser.temporary, children, | ||
| 253 | parser.output, children_size); | ||
| 254 | ptr->sv.end = RS274NGC_CST_NODE_PTR (ptr->children[ptr->count - 1])->sv.end; | ||
| 255 | |||
| 256 | // struct location location = find_location (parser.lexer->sv, ptr->sv); | ||
| 257 | // print_location (parser.lexer->filename, location, 0, "parsed: %s", | ||
| 258 | // rs274ngc_cst_node_kind_names[kind]); | ||
| 259 | |||
| 260 | return (void *) RS274NGC_CST_TAG_NODE (ptr, kind); | ||
| 261 | |||
| 262 | fail: | ||
| 263 | // printf ("Failed to parse: %s\n", rs274ngc_node_kind_names[kind]); | ||
| 264 | parser.lexer->cursor = cursor; | ||
| 265 | if (branch.count) | ||
| 266 | arena_rollback_to (parser.temporary, children); | ||
| 267 | return NULL; | ||
| 268 | } | ||
| 269 | |||
| 270 | union rs274ngc_cst_node * | ||
| 271 | rs274ngc_cst_parse_node (struct rs274ngc_cst_parser parser, | ||
| 272 | enum rs274ngc_cst_node_kind kind) | ||
| 273 | { | ||
| 274 | return (kind < RS274NGC_CST_TERMINAL_COUNT | ||
| 275 | ? (void *) rs274ngc_cst_parse_leaf (parser, kind) | ||
| 276 | : (void *) rs274ngc_cst_parse_branch (parser, kind)); | ||
| 277 | } | ||
| 278 | |||
| 279 | /// src/rs274ngc_cst.c ends here | ||
diff --git a/src/rs274ngc_cst.h b/src/rs274ngc_cst.h new file mode 100644 index 0000000..6e93c93 --- /dev/null +++ b/src/rs274ngc_cst.h | |||
| @@ -0,0 +1,93 @@ | |||
| 1 | /// src/rs274ngc_cst.h --- RS274NGC Concrete Syntax Tree | ||
| 2 | // | ||
| 3 | // Copyright (C) 2026 by Martin Michalec <martin@michalec.dev> | ||
| 4 | // | ||
| 5 | // SPDX-License-Identifier: MIT | ||
| 6 | // | ||
| 7 | /// Commentary: | ||
| 8 | // | ||
| 9 | /// Code: | ||
| 10 | |||
| 11 | #ifndef INCLUDED_RS274NGC_CST_H | ||
| 12 | #define INCLUDED_RS274NGC_CST_H | ||
| 13 | |||
| 14 | #define RS274NGC_CST_NODE_KINDS() \ | ||
| 15 | RS274NGC_LEXEME_KINDS() \ | ||
| 16 | X (PROGRAM ) \ | ||
| 17 | X (LINE ) \ | ||
| 18 | X (BLOCK_DELETE ) \ | ||
| 19 | X (SEGMENT ) \ | ||
| 20 | X (WORD ) \ | ||
| 21 | X (COMMENT ) \ | ||
| 22 | X (PARAMETER_SETTING ) \ | ||
| 23 | X (PARAMETER_INDEX ) \ | ||
| 24 | X (REAL_VALUE ) \ | ||
| 25 | X (REAL_NUMBER ) \ | ||
| 26 | X (EXPRESSION ) \ | ||
| 27 | X (PARAMETER_VALUE ) \ | ||
| 28 | X (UNARY_COMBO ) \ | ||
| 29 | X (ORDINARY_UNARY_COMBO) \ | ||
| 30 | X (ARC_TANGENT_COMBO ) \ | ||
| 31 | X (BINARY_OPERATION ) \ | ||
| 32 | X (DIVIDED_BY ) | ||
| 33 | |||
| 34 | #include "rs274ngc_lexer.h" | ||
| 35 | #include "arena.h" | ||
| 36 | |||
| 37 | #define RS274NGC_CST_TAG_NODE(PTR, TAG) ((union rs274ngc_cst_node *) ((uintptr_t) (TAG) << 48 | (uintptr_t) (PTR))) | ||
| 38 | #define RS274NGC_CST_NODE_KIND(PTR) ((enum rs274ngc_cst_node_kind) ((uintptr_t) (PTR) >> 48)) | ||
| 39 | #define RS274NGC_CST_NODE_PTR(PTR) ((union rs274ngc_cst_node *) ((uintptr_t) (PTR) & (((uintptr_t) 1 << 48) - 1))) | ||
| 40 | |||
| 41 | #define RS274NGC_CST_NODE_KIND_EQ(PTR, KIND) (RS274NGC_CST_NODE_KIND (PTR) == RS274NGC_CST_NODE_KIND_##KIND) | ||
| 42 | |||
| 43 | #define X(SYM, ...) RS274NGC_CST_NODE_KIND_##SYM, | ||
| 44 | enum rs274ngc_cst_node_kind { | ||
| 45 | RS274NGC_CST_NODE_KIND_INVALID, | ||
| 46 | RS274NGC_CST_NODE_KIND_END_OF_LINE, | ||
| 47 | RS274NGC_CST_NODE_KIND_END_OF_FILE, | ||
| 48 | RS274NGC_CST_NODE_KINDS () | ||
| 49 | RS274NGC_CST_NODE_KIND_COUNT, | ||
| 50 | }; | ||
| 51 | #undef X | ||
| 52 | |||
| 53 | #define RS274NGC_CST_TERMINAL_COUNT \ | ||
| 54 | ((enum rs274ngc_cst_node_kind) RS274NGC_LEXEME_KIND_COUNT) | ||
| 55 | |||
| 56 | extern const char *rs274ngc_cst_node_kind_names[ | ||
| 57 | RS274NGC_CST_NODE_KIND_COUNT]; | ||
| 58 | |||
| 59 | union rs274ngc_cst_node; | ||
| 60 | |||
| 61 | struct rs274ngc_cst_leaf { | ||
| 62 | struct sv sv; | ||
| 63 | }; | ||
| 64 | |||
| 65 | struct rs274ngc_cst_branch { | ||
| 66 | struct sv sv; | ||
| 67 | uint64_t count; | ||
| 68 | union rs274ngc_cst_node *children[]; | ||
| 69 | }; | ||
| 70 | |||
| 71 | union rs274ngc_cst_node { | ||
| 72 | struct sv sv; | ||
| 73 | struct rs274ngc_cst_leaf leaf; | ||
| 74 | struct rs274ngc_cst_branch branch; | ||
| 75 | }; | ||
| 76 | |||
| 77 | struct rs274ngc_cst_parser { | ||
| 78 | struct rs274ngc_lexer *lexer; | ||
| 79 | struct arena *output; | ||
| 80 | struct arena *temporary; | ||
| 81 | }; | ||
| 82 | |||
| 83 | #define RS274NGC_CST_PARSE(P, K) \ | ||
| 84 | (RS274NGC_CST_NODE_KIND_##K < RS274NGC_CST_TERMINAL_COUNT \ | ||
| 85 | ? (union rs274ngc_cst_node *) rs274ngc_cst_parse_leaf (P, RS274NGC_CST_NODE_KIND_##K) \ | ||
| 86 | : (union rs274ngc_cst_node *) rs274ngc_cst_parse_branch (P, RS274NGC_CST_NODE_KIND_##K)) | ||
| 87 | union rs274ngc_cst_node *rs274ngc_cst_parse_node (struct rs274ngc_cst_parser, enum rs274ngc_cst_node_kind); | ||
| 88 | struct rs274ngc_cst_leaf *rs274ngc_cst_parse_leaf (struct rs274ngc_cst_parser, enum rs274ngc_cst_node_kind); | ||
| 89 | struct rs274ngc_cst_branch *rs274ngc_cst_parse_branch (struct rs274ngc_cst_parser, enum rs274ngc_cst_node_kind); | ||
| 90 | |||
| 91 | #endif // INCLUDED_RS274NGC_CST_H | ||
| 92 | |||
| 93 | /// src/rs274ngc_cst.h ends here | ||
diff --git a/src/rs274ngc_lexeme.c b/src/rs274ngc_lexeme.c new file mode 100644 index 0000000..1b4bbad --- /dev/null +++ b/src/rs274ngc_lexeme.c | |||
| @@ -0,0 +1,22 @@ | |||
| 1 | /// src/rs274ngc_lexeme.c --- RS274NGC lexeme | ||
| 2 | // | ||
| 3 | // Copyright (C) 2026 by Martin Michalec <martin@michalec.dev> | ||
| 4 | // | ||
| 5 | // SPDX-License-Identifier: MIT | ||
| 6 | // | ||
| 7 | /// Commentary: | ||
| 8 | // | ||
| 9 | /// Code: | ||
| 10 | |||
| 11 | #include "rs274ngc_lexeme.h" | ||
| 12 | |||
| 13 | #define X(SYM, ...) [RS274NGC_LEXEME_KIND_##SYM] = #SYM, | ||
| 14 | const char *rs274ngc_lexeme_kind_names[RS274NGC_LEXEME_KIND_COUNT] = { | ||
| 15 | [RS274NGC_LEXEME_KIND_INVALID ] = "INVALID", | ||
| 16 | [RS274NGC_LEXEME_KIND_END_OF_LINE] = "END_OF_LINE", | ||
| 17 | [RS274NGC_LEXEME_KIND_END_OF_FILE] = "END_OF_FILE", | ||
| 18 | RS274NGC_LEXEME_KINDS () | ||
| 19 | }; | ||
| 20 | #undef X | ||
| 21 | |||
| 22 | /// src/rs274ngc_lexeme.c ends here | ||
diff --git a/src/rs274ngc_lexeme.h b/src/rs274ngc_lexeme.h new file mode 100644 index 0000000..337d244 --- /dev/null +++ b/src/rs274ngc_lexeme.h | |||
| @@ -0,0 +1,75 @@ | |||
| 1 | /// src/rs274ngc_lexeme.h --- RS274NGC lexeme | ||
| 2 | // | ||
| 3 | // Copyright (C) 2026 by Martin Michalec <martin@michalec.dev> | ||
| 4 | // | ||
| 5 | // SPDX-License-Identifier: MIT | ||
| 6 | // | ||
| 7 | /// Commentary: | ||
| 8 | // | ||
| 9 | /// Code: | ||
| 10 | |||
| 11 | #ifndef INCLUDED__RS274NGC__LEXEME__H | ||
| 12 | #define INCLUDED__RS274NGC__LEXEME__H | ||
| 13 | |||
| 14 | #include <stddef.h> | ||
| 15 | #include <stdint.h> | ||
| 16 | #include "sv.h" | ||
| 17 | |||
| 18 | #define RS274NGC_LEXEME_KINDS() \ | ||
| 19 | X (MESSAGE, "\\([ \t]*[Mm][ \t]*[Ss][ \t]*[Gg][ \t]*," \ | ||
| 20 | "[^()]*\\)" ) \ | ||
| 21 | X (ORDINARY_COMMENT, ";[^\n]*|\\([^()]*\\)" ) \ | ||
| 22 | X (MODULO, "[Mm][ \t]*[Oo][ \t]*[Dd]" ) \ | ||
| 23 | X (NATURAL_LOG_OF, "[Ll][ \t]*[Nn]" ) \ | ||
| 24 | X (NON_EXCLUSIVE_OR, "[Oo][ \t]*[Rr]" ) \ | ||
| 25 | X (ABSOLUTE_VALUE, "[Aa][ \t]*[Bb][ \t]*[Ss]" ) \ | ||
| 26 | X (AND, "[Aa][ \t]*[Nn][ \t]*[Dd]" ) \ | ||
| 27 | X (ARC_COSINE, "[Aa][ \t]*[Cc][ \t]*[Oo][ \t]*[Ss]" ) \ | ||
| 28 | X (ARC_SINE, "[Aa][ \t]*[Ss][ \t]*[Ii][ \t]*[Nn]" ) \ | ||
| 29 | X (ARC_TANGENT, "[Aa][ \t]*[Tt][ \t]*[Aa][ \t]*[Nn]" ) \ | ||
| 30 | X (COSINE, "[Cc][ \t]*[Oo][ \t]*[Ss]" ) \ | ||
| 31 | X (EXCLUSIVE_OR, "[Xx][ \t]*[Oo][ \t]*[Rr]" ) \ | ||
| 32 | X (E_RAISED_TO, "[Ee][ \t]*[Xx][ \t]*[Pp]" ) \ | ||
| 33 | X (FIX_DOWN, "[Ff][ \t]*[Ii][ \t]*[Xx]" ) \ | ||
| 34 | X (FIX_UP, "[Ff][ \t]*[Uu][ \t]*[Pp]" ) \ | ||
| 35 | X (ROUND, "[Rr][ \t]*[Oo][ \t]*[Uu][ \t]*[Nn][ \t]*[Dd]" ) \ | ||
| 36 | X (SINE, "[Ss][ \t]*[Ii][ \t]*[Nn]" ) \ | ||
| 37 | X (SQUARE_ROOT, "[Ss][ \t]*[Qq][ \t]*[Rr][ \t]*[Tt]" ) \ | ||
| 38 | X (TANGENT, "[Tt][ \t]*[Aa][ \t]*[Nn]" ) \ | ||
| 39 | X (WORD_LETTER, "[ABCDFGHIJKLMPQRSTXYZabcdfghijklmpqrstxyz]" ) \ | ||
| 40 | X (REAL_NUMBER_NO_SIGN, "[0-9 \t]*(\\.[0-9 \t]*)?" ) \ | ||
| 41 | X (LINE_NUMBER, "[Nn][0-9 \t]+" ) \ | ||
| 42 | X (PARAMETER_SIGN, "#" ) \ | ||
| 43 | X (BRACKET_RIGHT, "\\]" ) \ | ||
| 44 | X (BRACKET_LEFT, "\\[" ) \ | ||
| 45 | X (EQUAL_SIGN, "=" ) \ | ||
| 46 | X (MINUS, "-" ) \ | ||
| 47 | X (PLUS, "\\+" ) \ | ||
| 48 | X (POWER, "\\*\\*" ) \ | ||
| 49 | X (TIMES, "\\*" ) \ | ||
| 50 | X (SLASH, "/" ) \ | ||
| 51 | |||
| 52 | #define X(SYM, ...) RS274NGC_LEXEME_KIND_##SYM, | ||
| 53 | enum rs274ngc_lexeme_kind { | ||
| 54 | RS274NGC_LEXEME_KIND_INVALID, | ||
| 55 | RS274NGC_LEXEME_KIND_END_OF_LINE, | ||
| 56 | RS274NGC_LEXEME_KIND_END_OF_FILE, | ||
| 57 | RS274NGC_LEXEME_KINDS () | ||
| 58 | RS274NGC_LEXEME_KIND_COUNT, | ||
| 59 | }; | ||
| 60 | #undef X | ||
| 61 | |||
| 62 | extern const char *rs274ngc_lexeme_kind_names[RS274NGC_LEXEME_KIND_COUNT]; | ||
| 63 | |||
| 64 | #define RS274NGC_LEXEME_REGEX_OFFSET 3 | ||
| 65 | #define RS274NGC_LEXEME_REGEX_COUNT \ | ||
| 66 | (RS274NGC_LEXEME_KIND_COUNT - RS274NGC_LEXEME_REGEX_OFFSET) | ||
| 67 | |||
| 68 | struct rs274ngc_lexeme { | ||
| 69 | struct sv sv; | ||
| 70 | enum rs274ngc_lexeme_kind kind; | ||
| 71 | }; | ||
| 72 | |||
| 73 | #endif // INCLUDED_RS274NGC_LEXEME_H | ||
| 74 | |||
| 75 | /// src/rs274ngc_lexeme.h ends here | ||
diff --git a/src/rs274ngc_lexer.c b/src/rs274ngc_lexer.c new file mode 100644 index 0000000..cbc7ade --- /dev/null +++ b/src/rs274ngc_lexer.c | |||
| @@ -0,0 +1,147 @@ | |||
| 1 | /// src/rs274ngc_lexer.c --- RS274NGC lexer | ||
| 2 | // | ||
| 3 | // Copyright (C) 2026 by Martin Michalec <martin@michalec.dev> | ||
| 4 | // | ||
| 5 | // SPDX-License-Identifier: MIT | ||
| 6 | // | ||
| 7 | /// Commentary: | ||
| 8 | // | ||
| 9 | /// Code: | ||
| 10 | |||
| 11 | #include "rs274ngc_lexer.h" | ||
| 12 | #include <regex.h> | ||
| 13 | #include <assert.h> | ||
| 14 | #include <stdlib.h> | ||
| 15 | #include <stdio.h> | ||
| 16 | #include <stdbool.h> | ||
| 17 | #include <ctype.h> | ||
| 18 | |||
| 19 | #define X(SYM, REG, ...) \ | ||
| 20 | [RS274NGC_LEXEME_KIND_##SYM - RS274NGC_LEXEME_REGEX_OFFSET] = "^(" REG ")", | ||
| 21 | static const char *lexeme_regex_strings[RS274NGC_LEXEME_REGEX_COUNT] = { | ||
| 22 | RS274NGC_LEXEME_KINDS () | ||
| 23 | }; | ||
| 24 | #undef X | ||
| 25 | |||
| 26 | static regex_t lexeme_regexes[RS274NGC_LEXEME_REGEX_COUNT]; | ||
| 27 | |||
| 28 | static void | ||
| 29 | print_regex_error (const regex_t *comp, const char *regex, int errcode) | ||
| 30 | { | ||
| 31 | size_t length = regerror (errcode, comp, NULL, 0); | ||
| 32 | char *buffer = malloc (length); | ||
| 33 | regerror (errcode, comp, buffer, length); | ||
| 34 | fprintf (stderr, "error: regcomp (\"%s\"): %s\n", regex, buffer); | ||
| 35 | free (buffer); | ||
| 36 | } | ||
| 37 | |||
| 38 | void | ||
| 39 | rs274ngc_lexer_compile_regexes (void) | ||
| 40 | { | ||
| 41 | bool errored = false; | ||
| 42 | |||
| 43 | for (int i = 0; i < RS274NGC_LEXEME_REGEX_COUNT; ++i) { | ||
| 44 | regex_t *compiled = &lexeme_regexes[i]; | ||
| 45 | const char *pattern = lexeme_regex_strings[i]; | ||
| 46 | int errcode = regcomp (compiled, pattern, REG_EXTENDED); | ||
| 47 | if (errcode) { | ||
| 48 | print_regex_error (compiled, pattern, errcode); | ||
| 49 | errored = true; | ||
| 50 | } | ||
| 51 | } | ||
| 52 | |||
| 53 | if (errored) | ||
| 54 | exit (EXIT_FAILURE); | ||
| 55 | } | ||
| 56 | |||
| 57 | struct rs274ngc_lexer | ||
| 58 | rs274ngc_lexer_from_sv (struct sv sv, const char *filename) | ||
| 59 | { | ||
| 60 | struct rs274ngc_lexer lexer = { | ||
| 61 | .sv = sv, | ||
| 62 | .cursor = sv.beg, | ||
| 63 | .filename = filename, | ||
| 64 | }; | ||
| 65 | |||
| 66 | rs274ngc_lexer_next_lexeme (&lexer); | ||
| 67 | return lexer; | ||
| 68 | } | ||
| 69 | |||
| 70 | static void | ||
| 71 | skip_whitespace (struct rs274ngc_lexer *lexer) | ||
| 72 | { | ||
| 73 | while (lexer->cursor < lexer->sv.end && (*lexer->cursor == ' ' || | ||
| 74 | *lexer->cursor == '\t')) | ||
| 75 | lexer->cursor += 1; | ||
| 76 | } | ||
| 77 | |||
| 78 | void | ||
| 79 | rs274ngc_lexer_next_lexeme (struct rs274ngc_lexer *lexer) | ||
| 80 | { | ||
| 81 | skip_whitespace (lexer); | ||
| 82 | lexer->lexeme = (struct rs274ngc_lexeme) { .sv.beg = lexer->cursor }; | ||
| 83 | |||
| 84 | if (lexer->cursor >= lexer->sv.end) { | ||
| 85 | lexer->lexeme.kind = RS274NGC_LEXEME_KIND_END_OF_FILE; | ||
| 86 | lexer->lexeme.sv.end = lexer->sv.end; | ||
| 87 | return; | ||
| 88 | } | ||
| 89 | |||
| 90 | if (*lexer->cursor == '\r') { | ||
| 91 | lexer->cursor += 1; | ||
| 92 | if (*lexer->cursor == '\n') | ||
| 93 | lexer->cursor += 1; | ||
| 94 | |||
| 95 | lexer->lexeme.kind = RS274NGC_LEXEME_KIND_END_OF_LINE; | ||
| 96 | lexer->lexeme.sv.end = lexer->cursor; | ||
| 97 | return; | ||
| 98 | } | ||
| 99 | |||
| 100 | if (*lexer->cursor == '\n') { | ||
| 101 | lexer->cursor += 1; | ||
| 102 | lexer->lexeme.kind = RS274NGC_LEXEME_KIND_END_OF_LINE; | ||
| 103 | lexer->lexeme.sv.end = lexer->cursor; | ||
| 104 | return; | ||
| 105 | } | ||
| 106 | |||
| 107 | regmatch_t regmatch; | ||
| 108 | int longest_matching_regex = RS274NGC_LEXEME_REGEX_COUNT; | ||
| 109 | int longest_matching_regex_length = 0; | ||
| 110 | for (int i = 0; i < RS274NGC_LEXEME_REGEX_COUNT; ++i) { | ||
| 111 | if (regexec (&lexeme_regexes[i], lexer->cursor, 1, ®match, 0)) continue; | ||
| 112 | if (regmatch.rm_eo <= longest_matching_regex_length) continue; | ||
| 113 | |||
| 114 | longest_matching_regex_length = regmatch.rm_eo; | ||
| 115 | longest_matching_regex = i; | ||
| 116 | |||
| 117 | #ifdef RS274NGC_LEXER_FIRST_MATCH | ||
| 118 | break; | ||
| 119 | #endif | ||
| 120 | } | ||
| 121 | |||
| 122 | if (longest_matching_regex != RS274NGC_LEXEME_REGEX_COUNT) { | ||
| 123 | lexer->lexeme.kind = longest_matching_regex + RS274NGC_LEXEME_REGEX_OFFSET; | ||
| 124 | lexer->lexeme.sv.end = lexer->cursor += longest_matching_regex_length; | ||
| 125 | |||
| 126 | #ifdef RS274NGC_LEXER_TRIM | ||
| 127 | while (lexer->lexeme.sv.end > lexer->lexeme.sv.beg && | ||
| 128 | (lexer->lexeme.sv.end[-1] == ' ' || | ||
| 129 | lexer->lexeme.sv.end[-1] == '\t')) { | ||
| 130 | lexer->lexeme.sv.end -= 1; | ||
| 131 | } | ||
| 132 | #endif | ||
| 133 | |||
| 134 | switch (lexer->lexeme.kind) { | ||
| 135 | #ifdef RS274NGC_LEXER_FILTER_COMMENTS | ||
| 136 | case RS274NGC_LEXEME_KIND_COMMENT: | ||
| 137 | return rs274ngc_lexer_next_lexeme (lexer); | ||
| 138 | #endif | ||
| 139 | default: return; | ||
| 140 | } | ||
| 141 | } | ||
| 142 | |||
| 143 | // INVALID | ||
| 144 | lexer->lexeme.sv.end = ++lexer->cursor; | ||
| 145 | } | ||
| 146 | |||
| 147 | /// src/rs274ngc_lexer.c ends here | ||
diff --git a/src/rs274ngc_lexer.h b/src/rs274ngc_lexer.h new file mode 100644 index 0000000..e8ee9a4 --- /dev/null +++ b/src/rs274ngc_lexer.h | |||
| @@ -0,0 +1,35 @@ | |||
| 1 | /// src/rs274ngc_lexer.h --- RS274NGC lexer | ||
| 2 | // | ||
| 3 | // Copyright (C) 2026 by Martin Michalec <martin@michalec.dev> | ||
| 4 | // | ||
| 5 | // SPDX-License-Identifier: MIT | ||
| 6 | // | ||
| 7 | /// Commentary: | ||
| 8 | // | ||
| 9 | /// Code: | ||
| 10 | |||
| 11 | #ifndef INCLUDED_RS274NGC_LEXER_H | ||
| 12 | #define INCLUDED_RS274NGC_LEXER_H | ||
| 13 | |||
| 14 | #include <stddef.h> | ||
| 15 | #include "sv.h" | ||
| 16 | #include "rs274ngc_lexeme.h" | ||
| 17 | |||
| 18 | #define RS274NGC_LEXER_FIRST_MATCH | ||
| 19 | #define RS274NGC_LEXER_TRIM | ||
| 20 | // #define RS274NGC_LEXER_FILTER_COMMENTS | ||
| 21 | |||
| 22 | struct rs274ngc_lexer { | ||
| 23 | struct sv sv; | ||
| 24 | const char *cursor; | ||
| 25 | const char *filename; | ||
| 26 | struct rs274ngc_lexeme lexeme; | ||
| 27 | }; | ||
| 28 | |||
| 29 | void rs274ngc_lexer_compile_regexes (void); | ||
| 30 | struct rs274ngc_lexer rs274ngc_lexer_from_sv (struct sv, const char *filename); | ||
| 31 | void rs274ngc_lexer_next_lexeme (struct rs274ngc_lexer *); | ||
| 32 | |||
| 33 | #endif // INCLUDED_RS274NGC_LEXER_H | ||
| 34 | |||
| 35 | /// src/rs274ngc_lexer.h ends here | ||
diff --git a/src/rs274ngc_state.c b/src/rs274ngc_state.c new file mode 100644 index 0000000..5ab17c2 --- /dev/null +++ b/src/rs274ngc_state.c | |||
| @@ -0,0 +1,455 @@ | |||
| 1 | #include "rs274ngc_state.h" | ||
| 2 | |||
| 3 | #include <ctype.h> | ||
| 4 | #include <math.h> | ||
| 5 | |||
| 6 | #include "utils.h" | ||
| 7 | #include "da.h" | ||
| 8 | |||
| 9 | #define INDENTATION 2 | ||
| 10 | #define EPS 0.0001 | ||
| 11 | |||
| 12 | static void | ||
| 13 | print_cst (struct arena *temp, struct rs274ngc_lexer *lexer, | ||
| 14 | struct rs274ngc_cst_branch *root, size_t alignment) | ||
| 15 | { | ||
| 16 | void *bottom = ARENA_COPY (temp, root); | ||
| 17 | ARENA_COPY (temp, alignment); | ||
| 18 | while (temp->tail->free != bottom) { | ||
| 19 | alignment = *(size_t *) arena_pop (temp, sizeof (alignment)); | ||
| 20 | void *node = *(void **) arena_pop (temp, sizeof (node )); | ||
| 21 | ASSERT (node); | ||
| 22 | if (RS274NGC_CST_NODE_KIND (node) < RS274NGC_CST_TERMINAL_COUNT) { // leaf | ||
| 23 | struct rs274ngc_cst_leaf *leaf = &RS274NGC_CST_NODE_PTR (node)->leaf; | ||
| 24 | struct location location = find_location (lexer->sv, leaf->sv); | ||
| 25 | print_location (lexer->filename, location, alignment, "- leaf: %s", | ||
| 26 | rs274ngc_cst_node_kind_names[RS274NGC_CST_NODE_KIND (node)]); | ||
| 27 | } else { // branch | ||
| 28 | struct rs274ngc_cst_branch *branch = &RS274NGC_CST_NODE_PTR (node)->branch; | ||
| 29 | if (1 || RS274NGC_CST_NODE_KIND_EQ (node, LINE)) { | ||
| 30 | struct location location = find_location (lexer->sv, branch->sv); | ||
| 31 | print_location (lexer->filename, location, alignment, "- branch: %s", | ||
| 32 | rs274ngc_cst_node_kind_names[RS274NGC_CST_NODE_KIND (node)]); | ||
| 33 | } | ||
| 34 | alignment += INDENTATION; | ||
| 35 | for (size_t i = branch->count; i > 0; --i) { | ||
| 36 | ASSERT (branch->children[i - 1]); | ||
| 37 | ARENA_COPY (temp, branch->children[i - 1]); | ||
| 38 | ARENA_COPY (temp, alignment); | ||
| 39 | } | ||
| 40 | } | ||
| 41 | } | ||
| 42 | } | ||
| 43 | |||
| 44 | struct binding_power { | ||
| 45 | int left, right; | ||
| 46 | }; | ||
| 47 | |||
| 48 | static struct binding_power | ||
| 49 | kind_to_binding_power (enum rs274ngc_cst_node_kind kind) | ||
| 50 | { | ||
| 51 | switch (kind) { | ||
| 52 | case RS274NGC_CST_NODE_KIND_POWER: return (struct binding_power) { 3, 3 }; | ||
| 53 | case RS274NGC_CST_NODE_KIND_TIMES: return (struct binding_power) { 2, 2 }; | ||
| 54 | case RS274NGC_CST_NODE_KIND_DIVIDED_BY: return (struct binding_power) { 2, 2 }; | ||
| 55 | case RS274NGC_CST_NODE_KIND_MODULO: return (struct binding_power) { 2, 2 }; | ||
| 56 | case RS274NGC_CST_NODE_KIND_PLUS: return (struct binding_power) { 1, 1 }; | ||
| 57 | case RS274NGC_CST_NODE_KIND_MINUS: return (struct binding_power) { 1, 1 }; | ||
| 58 | case RS274NGC_CST_NODE_KIND_EXCLUSIVE_OR: return (struct binding_power) { 1, 1 }; | ||
| 59 | case RS274NGC_CST_NODE_KIND_NON_EXCLUSIVE_OR: return (struct binding_power) { 1, 1 }; | ||
| 60 | case RS274NGC_CST_NODE_KIND_AND: return (struct binding_power) { 1, 1 }; | ||
| 61 | default: DIE ("invalid binop"); | ||
| 62 | } | ||
| 63 | } | ||
| 64 | |||
| 65 | static double | ||
| 66 | apply_binop (enum rs274ngc_cst_node_kind kind, double lhs, double rhs) | ||
| 67 | { | ||
| 68 | switch (kind) { | ||
| 69 | case RS274NGC_CST_NODE_KIND_POWER: return pow (lhs, rhs); | ||
| 70 | case RS274NGC_CST_NODE_KIND_TIMES: return lhs * rhs; | ||
| 71 | case RS274NGC_CST_NODE_KIND_DIVIDED_BY: return lhs / rhs; | ||
| 72 | case RS274NGC_CST_NODE_KIND_MODULO: return fmod (lhs, rhs); | ||
| 73 | case RS274NGC_CST_NODE_KIND_PLUS: return lhs + rhs; | ||
| 74 | case RS274NGC_CST_NODE_KIND_MINUS: return lhs - rhs; | ||
| 75 | case RS274NGC_CST_NODE_KIND_EXCLUSIVE_OR: return (lhs != 0) ^ (rhs != 0); | ||
| 76 | case RS274NGC_CST_NODE_KIND_NON_EXCLUSIVE_OR: return (lhs != 0) || (rhs != 0); | ||
| 77 | case RS274NGC_CST_NODE_KIND_AND: return (lhs != 0) && (rhs != 0); | ||
| 78 | default: DIE ("invalid binop"); | ||
| 79 | } | ||
| 80 | } | ||
| 81 | |||
| 82 | double eval_real_value (struct rs274ngc_state *, struct rs274ngc_cst_branch *real_value); | ||
| 83 | |||
| 84 | double | ||
| 85 | eval_expression (struct rs274ngc_state *state, | ||
| 86 | struct rs274ngc_cst_branch *expression, | ||
| 87 | size_t *i, int min_bp) | ||
| 88 | { | ||
| 89 | struct rs274ngc_cst_branch *lhsn = &expression->children[(*i)++]->branch; | ||
| 90 | ASSERT (RS274NGC_CST_NODE_KIND_EQ (lhsn, REAL_VALUE)); | ||
| 91 | lhsn = &RS274NGC_CST_NODE_PTR (lhsn)->branch; | ||
| 92 | double lhs = eval_real_value (state, lhsn); | ||
| 93 | for (;;) { | ||
| 94 | struct rs274ngc_cst_branch *binop = &expression->children[*i]->branch; | ||
| 95 | if (RS274NGC_CST_NODE_KIND_EQ (binop, BRACKET_RIGHT)) | ||
| 96 | break; | ||
| 97 | ASSERT (RS274NGC_CST_NODE_KIND_EQ (binop, BINARY_OPERATION)); | ||
| 98 | binop = &RS274NGC_CST_NODE_PTR (binop)->branch; | ||
| 99 | enum rs274ngc_cst_node_kind kind = RS274NGC_CST_NODE_KIND (binop->children[0]); | ||
| 100 | struct binding_power bp = kind_to_binding_power (kind); | ||
| 101 | if (bp.left < min_bp) | ||
| 102 | break; | ||
| 103 | *i += 1; | ||
| 104 | double rhs = eval_expression (state, expression, i, bp.right); | ||
| 105 | // printf ("[%02lu] %lg %s %lg", *i, lhs, rs274ngc_cst_node_kind_names[kind], rhs); | ||
| 106 | lhs = apply_binop (kind, lhs, rhs); | ||
| 107 | // printf (" = %lg\n", lhs); | ||
| 108 | } | ||
| 109 | |||
| 110 | return lhs; | ||
| 111 | } | ||
| 112 | |||
| 113 | static double | ||
| 114 | apply_unary (enum rs274ngc_cst_node_kind kind, double arg) | ||
| 115 | { | ||
| 116 | switch (kind) { | ||
| 117 | case RS274NGC_CST_NODE_KIND_ABSOLUTE_VALUE: return fabs (arg); | ||
| 118 | case RS274NGC_CST_NODE_KIND_ARC_COSINE: return acos (arg)/M_PI*180; | ||
| 119 | case RS274NGC_CST_NODE_KIND_ARC_SINE: return asin (arg)/M_PI*180; | ||
| 120 | case RS274NGC_CST_NODE_KIND_ARC_TANGENT: return atan (arg)/M_PI*180; | ||
| 121 | case RS274NGC_CST_NODE_KIND_COSINE: return cos (arg/180*M_PI); | ||
| 122 | case RS274NGC_CST_NODE_KIND_SINE: return sin (arg/180*M_PI); | ||
| 123 | case RS274NGC_CST_NODE_KIND_TANGENT: return tan (arg/180*M_PI); | ||
| 124 | case RS274NGC_CST_NODE_KIND_E_RAISED_TO: return exp (arg); | ||
| 125 | case RS274NGC_CST_NODE_KIND_NATURAL_LOG_OF: return log (arg); | ||
| 126 | case RS274NGC_CST_NODE_KIND_FIX_DOWN: return floor (arg); | ||
| 127 | case RS274NGC_CST_NODE_KIND_FIX_UP: return ceil (arg); | ||
| 128 | case RS274NGC_CST_NODE_KIND_ROUND: return round (arg); | ||
| 129 | case RS274NGC_CST_NODE_KIND_SQUARE_ROOT: return sqrt (arg); | ||
| 130 | default: DIE ("invalid binop"); | ||
| 131 | } | ||
| 132 | } | ||
| 133 | |||
| 134 | static double | ||
| 135 | svtod (struct sv sv) | ||
| 136 | { | ||
| 137 | double v = 0; | ||
| 138 | |||
| 139 | while (sv.beg < sv.end && *sv.beg != '.') { | ||
| 140 | v *= 10; | ||
| 141 | v += *sv.beg - '0'; | ||
| 142 | sv.beg += 1; | ||
| 143 | } | ||
| 144 | |||
| 145 | sv.beg += 1; | ||
| 146 | double d = 10; | ||
| 147 | while (sv.beg < sv.end) { | ||
| 148 | v += (*sv.beg - '0')/d; | ||
| 149 | d *= 10; | ||
| 150 | sv.beg += 1; | ||
| 151 | } | ||
| 152 | |||
| 153 | return v; | ||
| 154 | } | ||
| 155 | |||
| 156 | double | ||
| 157 | eval_real_value (struct rs274ngc_state *state, struct rs274ngc_cst_branch *real_value) | ||
| 158 | { | ||
| 159 | double value; | ||
| 160 | |||
| 161 | ASSERT (real_value->count == 1); | ||
| 162 | switch (RS274NGC_CST_NODE_KIND (real_value->children[0])) { | ||
| 163 | case RS274NGC_CST_NODE_KIND_REAL_NUMBER: { | ||
| 164 | struct rs274ngc_cst_branch *real_number = | ||
| 165 | &RS274NGC_CST_NODE_PTR (real_value->children[0])->branch; | ||
| 166 | double sign = 1; | ||
| 167 | struct rs274ngc_cst_leaf *real_number_no_sign; | ||
| 168 | if (real_number->count == 2) { | ||
| 169 | real_number_no_sign = &RS274NGC_CST_NODE_PTR (real_number->children[1])->leaf; | ||
| 170 | if (RS274NGC_CST_NODE_KIND_EQ (real_number->children[0], MINUS)) | ||
| 171 | sign = -1; | ||
| 172 | } else { | ||
| 173 | real_number_no_sign = &RS274NGC_CST_NODE_PTR (real_number->children[0])->leaf; | ||
| 174 | } | ||
| 175 | |||
| 176 | char *tail = NULL; | ||
| 177 | // value = sign*strtod (real_number_no_sign->sv.beg, &tail); | ||
| 178 | value = sign*svtod (real_number_no_sign->sv); | ||
| 179 | } break; | ||
| 180 | case RS274NGC_CST_NODE_KIND_EXPRESSION: { | ||
| 181 | struct rs274ngc_cst_branch *expression = | ||
| 182 | &RS274NGC_CST_NODE_PTR (real_value->children[0])->branch; | ||
| 183 | ASSERT (RS274NGC_CST_NODE_KIND_EQ (expression->children[0], BRACKET_LEFT)); | ||
| 184 | size_t i = 1; | ||
| 185 | value = eval_expression (state, expression, &i, 0); | ||
| 186 | } break; | ||
| 187 | case RS274NGC_CST_NODE_KIND_PARAMETER_VALUE: { | ||
| 188 | struct rs274ngc_cst_branch *parameter_value = | ||
| 189 | &RS274NGC_CST_NODE_PTR (real_value->children[0])->branch; | ||
| 190 | struct rs274ngc_cst_branch *real_parameter_value = | ||
| 191 | &RS274NGC_CST_NODE_PTR (parameter_value->children[1])->branch; | ||
| 192 | double i = eval_real_value (state, real_parameter_value); | ||
| 193 | int nbi = nearbyint (i); | ||
| 194 | ASSERT (fabs (i - nbi) < EPS); | ||
| 195 | ASSERT (nbi <= (int) ARRAY_LENGTH (state->parameter_values)); | ||
| 196 | value = state->parameter_values[nbi - 1]; | ||
| 197 | } break; | ||
| 198 | case RS274NGC_CST_NODE_KIND_UNARY_COMBO: { | ||
| 199 | struct rs274ngc_cst_branch *unary_combo = | ||
| 200 | &RS274NGC_CST_NODE_PTR (real_value->children[0])->branch; | ||
| 201 | switch (RS274NGC_CST_NODE_KIND (unary_combo->children[0])) { | ||
| 202 | case RS274NGC_CST_NODE_KIND_ORDINARY_UNARY_COMBO: { | ||
| 203 | struct rs274ngc_cst_branch *ordinary_unary_combo = | ||
| 204 | &RS274NGC_CST_NODE_PTR (unary_combo->children[0])->branch; | ||
| 205 | enum rs274ngc_cst_node_kind uniop = RS274NGC_CST_NODE_KIND (ordinary_unary_combo->children[0]); | ||
| 206 | struct rs274ngc_cst_branch *expression = | ||
| 207 | &RS274NGC_CST_NODE_PTR (ordinary_unary_combo->children[1])->branch; | ||
| 208 | size_t i = 1; | ||
| 209 | double arg = eval_expression (state, expression, &i, 0); | ||
| 210 | value = apply_unary (uniop, arg); | ||
| 211 | } break; | ||
| 212 | case RS274NGC_CST_NODE_KIND_ARC_TANGENT_COMBO: { | ||
| 213 | struct rs274ngc_cst_branch *arc_tangent_combo = | ||
| 214 | &RS274NGC_CST_NODE_PTR (unary_combo->children[0])->branch; | ||
| 215 | struct rs274ngc_cst_branch *arg = &RS274NGC_CST_NODE_PTR (arc_tangent_combo->children[1])->branch; | ||
| 216 | struct rs274ngc_cst_branch *div = &RS274NGC_CST_NODE_PTR (arc_tangent_combo->children[3])->branch; | ||
| 217 | size_t i = 1; | ||
| 218 | double argv = eval_expression (state, arg, &i, 0); | ||
| 219 | i = 1; | ||
| 220 | double divv = eval_expression (state, div, &i, 0); | ||
| 221 | value = atan (argv)/M_PI*180/divv; | ||
| 222 | } break; | ||
| 223 | default: DIE ("invalid unary combo"); | ||
| 224 | } | ||
| 225 | } break; | ||
| 226 | default: DIE ("invalid real value"); | ||
| 227 | } | ||
| 228 | |||
| 229 | return value; | ||
| 230 | } | ||
| 231 | |||
| 232 | static void | ||
| 233 | eval_word (struct rs274ngc_state *state, struct rs274ngc_cst_branch *word) | ||
| 234 | { | ||
| 235 | ASSERT (word->count == 2); | ||
| 236 | struct rs274ngc_cst_leaf *word_letter = &word->children[0]->leaf; | ||
| 237 | struct rs274ngc_cst_branch *real_value = &word->children[1]->branch; | ||
| 238 | ASSERT (RS274NGC_CST_NODE_KIND_EQ (word_letter, WORD_LETTER)); | ||
| 239 | ASSERT (RS274NGC_CST_NODE_KIND_EQ (real_value, REAL_VALUE )); | ||
| 240 | word_letter = &RS274NGC_CST_NODE_PTR (word_letter)->leaf; | ||
| 241 | ASSERT (SV_LENGTH (word_letter->sv) == 1); | ||
| 242 | char word_letter_char = toupper (word_letter->sv.beg[0]); | ||
| 243 | |||
| 244 | // print_cst (parser.temporary, parser.lexer, real_value, 80); | ||
| 245 | real_value = &RS274NGC_CST_NODE_PTR (real_value)->branch; | ||
| 246 | double value = eval_real_value (state, real_value); | ||
| 247 | // printf ("%c%g\n", word_letter_char, value); | ||
| 248 | |||
| 249 | switch (word_letter_char) { | ||
| 250 | case 'A': state->a = value; state->words_set |= A_MASK; break; | ||
| 251 | case 'B': state->b = value; state->words_set |= B_MASK; break; | ||
| 252 | case 'C': state->c = value; state->words_set |= C_MASK; break; | ||
| 253 | case 'D': state->d = value; state->words_set |= D_MASK; break; | ||
| 254 | case 'H': state->h = value; state->words_set |= H_MASK; break; | ||
| 255 | case 'I': state->i = value; state->words_set |= I_MASK; break; | ||
| 256 | case 'J': state->j = value; state->words_set |= J_MASK; break; | ||
| 257 | case 'K': state->k = value; state->words_set |= K_MASK; break; | ||
| 258 | case 'L': state->l = value; state->words_set |= L_MASK; break; | ||
| 259 | case 'N': state->n = value; state->words_set |= N_MASK; break; | ||
| 260 | case 'P': state->p = value; state->words_set |= P_MASK; break; | ||
| 261 | case 'Q': state->q = value; state->words_set |= Q_MASK; break; | ||
| 262 | case 'R': state->r = value; state->words_set |= R_MASK; break; | ||
| 263 | case 'F': state->f = value; state->words_set |= F_MASK; break; | ||
| 264 | case 'S': state->s = value; state->words_set |= S_MASK; break; | ||
| 265 | case 'T': state->t = value; state->words_set |= T_MASK; break; | ||
| 266 | case 'X': state->x = value; state->words_set |= X_MASK; break; | ||
| 267 | case 'Y': state->y = value; state->words_set |= Y_MASK; break; | ||
| 268 | case 'Z': state->z = value; state->words_set |= Z_MASK; break; | ||
| 269 | case 'G': { | ||
| 270 | switch ((int) nearbyint (10*value)) { | ||
| 271 | case 40: state->non_modal = NON_MODAL_DWELL; break; | ||
| 272 | case 100: state->non_modal = NON_MODAL_SET_COORDINATE_SYSTEM_DATA; break; | ||
| 273 | case 280: state->non_modal = NON_MODAL_RETURN_TO_HOME; break; | ||
| 274 | case 300: state->non_modal = NON_MODAL_RETURN_TO_SECONDARY_HOME; break; | ||
| 275 | case 530: state->non_modal = NON_MODAL_MOTION_IN_MACHINE_COORDINATE_SYSTEM; break; | ||
| 276 | case 920: state->non_modal = NON_MODAL_OFFSET_COORDINATE_SYSTEMS_AND_SET_PARAMETERS; break; | ||
| 277 | case 921: state->non_modal = NON_MODAL_CANCEL_OFFSET_COORDINATE_SYSTEMS_AND_SET_PARAMETERS_TO_ZERO; break; | ||
| 278 | case 922: state->non_modal = NON_MODAL_CANCEL_OFFSET_COORDINATE_SYSTEMS_BUT_DO_NOT_RESET_PARAMETERS; break; | ||
| 279 | case 923: state->non_modal = NON_MODAL_APPLY_PARAMETERS_TO_OFFSET_COORDINATE_SYSTEMS; break; | ||
| 280 | |||
| 281 | case 0: state->current_motion_mode = MOTION_RAPID_POSITIONING; break; | ||
| 282 | case 10: state->current_motion_mode = MOTION_LINEAR_INTERPOLATION; break; | ||
| 283 | case 20: state->current_motion_mode = MOTION_CIRCULAR_INTERPOLATION_CW; break; | ||
| 284 | case 30: state->current_motion_mode = MOTION_CIRCULAR_INTERPOLATION_CCW; break; | ||
| 285 | case 382: state->current_motion_mode = MOTION_STRAIGHT_PROBE; break; | ||
| 286 | case 800: state->current_motion_mode = MOTION_CANCEL_MOTION_MODE; break; | ||
| 287 | case 810: state->current_motion_mode = MOTION_CANNED_CYCLE_DRILLING; break; | ||
| 288 | case 820: state->current_motion_mode = MOTION_CANNED_CYCLE_DRILLING_WITH_DWELL; break; | ||
| 289 | case 830: state->current_motion_mode = MOTION_CANNED_CYCLE_PECK_DRILLING; break; | ||
| 290 | case 840: state->current_motion_mode = MOTION_CANNED_CYCLE_RIGHT_HAND_TAPPING; break; | ||
| 291 | case 850: state->current_motion_mode = MOTION_CANNED_CYCLE_BORING_NO_DWELL_FEED_OUT; break; | ||
| 292 | case 860: state->current_motion_mode = MOTION_CANNED_CYCLE_BORING_SPINDLE_STOP_RAPID_OUT; break; | ||
| 293 | case 870: state->current_motion_mode = MOTION_CANNED_CYCLE_BACK_BORING; break; | ||
| 294 | case 880: state->current_motion_mode = MOTION_CANNED_CYCLE_BORING_SPINDLE_STOP_MANUAL_OUT; break; | ||
| 295 | case 890: state->current_motion_mode = MOTION_CANNED_CYCLE_BORING_DWELL_FEED_OUT; break; | ||
| 296 | |||
| 297 | case 170: state->plane_selection = PLANE_SELECTION_XY; break; | ||
| 298 | case 180: state->plane_selection = PLANE_SELECTION_XZ; break; | ||
| 299 | case 190: state->plane_selection = PLANE_SELECTION_YZ; break; | ||
| 300 | |||
| 301 | case 900: state->distance_mode = DISTANCE_MODE_ABSOLUTE; break; | ||
| 302 | case 910: state->distance_mode = DISTANCE_MODE_INCREMENTAL; break; | ||
| 303 | |||
| 304 | case 930: state->feed_rate_mode = FEED_RATE_MODE_INVERSE_TIME; break; | ||
| 305 | case 940: state->feed_rate_mode = FEED_RATE_MODE_UNITS_PER_MINUTE; break; | ||
| 306 | |||
| 307 | case 200: state->units = UNITS_INCH; break; | ||
| 308 | case 210: state->units = UNITS_MM; break; | ||
| 309 | |||
| 310 | case 400: state->cutter_radius_compensation = CUTTER_RADIUS_COMPENSATION_CANCEL; break; | ||
| 311 | case 410: state->cutter_radius_compensation = CUTTER_RADIUS_COMPENSATION_START_LEFT; break; | ||
| 312 | case 420: state->cutter_radius_compensation = CUTTER_RADIUS_COMPENSATION_START_RIGHT; break; | ||
| 313 | |||
| 314 | case 430: state->tool_length_offset = TOOL_LENGTH_OFFSET_PLUS; break; | ||
| 315 | case 490: state->tool_length_offset = TOOL_LENGTH_OFFSET_CANCEL; break; | ||
| 316 | |||
| 317 | case 980: state->return_mode_in_canned_cycles = RETURN_MODE_IN_CANNED_CYCLES_INITIAL; break; | ||
| 318 | case 990: state->return_mode_in_canned_cycles = RETURN_MODE_IN_CANNED_CYCLES_R_POINT; break; | ||
| 319 | |||
| 320 | case 540: state->coordinate_system = COORDINATE_SYSTEM_PRESET_WORK_1; break; | ||
| 321 | case 550: state->coordinate_system = COORDINATE_SYSTEM_PRESET_WORK_2; break; | ||
| 322 | case 560: state->coordinate_system = COORDINATE_SYSTEM_PRESET_WORK_3; break; | ||
| 323 | case 570: state->coordinate_system = COORDINATE_SYSTEM_PRESET_WORK_4; break; | ||
| 324 | case 580: state->coordinate_system = COORDINATE_SYSTEM_PRESET_WORK_5; break; | ||
| 325 | case 590: state->coordinate_system = COORDINATE_SYSTEM_PRESET_WORK_6; break; | ||
| 326 | case 591: state->coordinate_system = COORDINATE_SYSTEM_PRESET_WORK_7; break; | ||
| 327 | case 592: state->coordinate_system = COORDINATE_SYSTEM_PRESET_WORK_8; break; | ||
| 328 | case 593: state->coordinate_system = COORDINATE_SYSTEM_PRESET_WORK_9; break; | ||
| 329 | |||
| 330 | case 610: state->path_control_mode = PATH_CONTROL_MODE_EXACT_PATH; break; | ||
| 331 | case 611: state->path_control_mode = PATH_CONTROL_MODE_EXACT_STOP; break; | ||
| 332 | case 640: state->path_control_mode = PATH_CONTROL_MODE_CONTINUOS; break; | ||
| 333 | |||
| 334 | default: DIE ("invalid G-command: " SV_FMT, SV_FMTA (word->sv)); | ||
| 335 | }; | ||
| 336 | } break; | ||
| 337 | case 'M': { | ||
| 338 | switch ((int) value) { | ||
| 339 | case 0: state->stopping = STOPPING_STOP; break; | ||
| 340 | case 1: state->stopping = STOPPING_STOP_OPTIONAL; break; | ||
| 341 | case 2: state->stopping = STOPPING_END; break; | ||
| 342 | case 30: state->stopping = STOPPING_EXCHANGE_PALLETE_SHUTES_AND_END; break; | ||
| 343 | case 60: state->stopping = STOPPING_EXCHANGE_PALLETE_SHUTES_AND_STOP; break; | ||
| 344 | |||
| 345 | case 6: state->tool_change = TOOL_CHANGE; break; | ||
| 346 | |||
| 347 | case 3: state->spindle_turning = SPINDLE_TURNING_START_CW; break; | ||
| 348 | case 4: state->spindle_turning = SPINDLE_TURNING_START_CCW; break; | ||
| 349 | case 5: state->spindle_turning = SPINDLE_TURNING_STOP; break; | ||
| 350 | |||
| 351 | case 7: state->coolant = state->coolant == COOLANT_ON_FLOOD ? COOLANT_ON_BOTH : COOLANT_ON_MIST; break; | ||
| 352 | case 8: state->coolant = state->coolant == COOLANT_ON_MIST ? COOLANT_ON_BOTH : COOLANT_ON_FLOOD; break; | ||
| 353 | case 9: state->coolant = COOLANT_OFF; break; | ||
| 354 | |||
| 355 | case 48: state->override_switches = OVERRIDE_SWITCHES_ENABLE; break; | ||
| 356 | case 49: state->override_switches = OVERRIDE_SWITCHES_DISABLE; break; | ||
| 357 | default: DIE ("invalid M-command: " SV_FMT, SV_FMTA (word->sv)); | ||
| 358 | }; | ||
| 359 | } break; | ||
| 360 | } | ||
| 361 | // puts (""); | ||
| 362 | } | ||
| 363 | |||
| 364 | struct parameter_spec { | ||
| 365 | int index; | ||
| 366 | double value; | ||
| 367 | }; | ||
| 368 | |||
| 369 | static struct parameter_spec | ||
| 370 | eval_parameter_setting (struct rs274ngc_state *state, | ||
| 371 | struct rs274ngc_cst_branch *parameter_setting) | ||
| 372 | { | ||
| 373 | // print_cst (parser.temporary, parser.lexer, &(*segment)->branch, 52); | ||
| 374 | struct rs274ngc_cst_branch *index = &RS274NGC_CST_NODE_PTR (parameter_setting->children[1])->branch; | ||
| 375 | struct rs274ngc_cst_branch *index_value = &RS274NGC_CST_NODE_PTR ( index->children[0])->branch; | ||
| 376 | struct rs274ngc_cst_branch *value = &RS274NGC_CST_NODE_PTR (parameter_setting->children[3])->branch; | ||
| 377 | double i = eval_real_value (state, index_value); | ||
| 378 | double v = eval_real_value (state, value); | ||
| 379 | int nbi = nearbyint (i); | ||
| 380 | ASSERT (fabs (i - nbi) < EPS); | ||
| 381 | ASSERT (nbi <= (int) ARRAY_LENGTH (state->parameter_values)); | ||
| 382 | // printf ("%d = %g\n", nbi, v); | ||
| 383 | return (struct parameter_spec) { nbi - 1, v }; | ||
| 384 | } | ||
| 385 | |||
| 386 | int | ||
| 387 | rs274ngc_state_next (struct rs274ngc_state *state, | ||
| 388 | struct rs274ngc_cst_parser parser) | ||
| 389 | { | ||
| 390 | // NOTE(cmmm): we might want to free this buffer at some point | ||
| 391 | static struct parameter_buffer { | ||
| 392 | struct parameter_spec *items; | ||
| 393 | uint32_t count; | ||
| 394 | uint32_t capacity; | ||
| 395 | } pb = {0}; | ||
| 396 | |||
| 397 | // NOTE(cmmm): alignment should be passed to coalesce, not checkpoint | ||
| 398 | struct arena_checkpoint cp = arena_checkpoint (parser.output, 1); | ||
| 399 | while (parser.lexer->lexeme.kind != RS274NGC_LEXEME_KIND_END_OF_FILE) { | ||
| 400 | arena_rollback_to (parser.output, cp); | ||
| 401 | |||
| 402 | struct rs274ngc_cst_branch *line = | ||
| 403 | &RS274NGC_CST_NODE_PTR (RS274NGC_CST_PARSE (parser, LINE))->branch; | ||
| 404 | if (!line) | ||
| 405 | continue; | ||
| 406 | union rs274ngc_cst_node **child = &line->children[0]; | ||
| 407 | union rs274ngc_cst_node **child_end = &line->children[line->count]; | ||
| 408 | // printf (SV_FMT "\n", SV_FMTA (line->sv)); | ||
| 409 | |||
| 410 | if (RS274NGC_CST_NODE_KIND_EQ (*child, BLOCK_DELETE)) | ||
| 411 | continue; | ||
| 412 | |||
| 413 | if (RS274NGC_CST_NODE_KIND_EQ (*child, LINE_NUMBER)) | ||
| 414 | child += 1; | ||
| 415 | |||
| 416 | DA_RESET (pb); | ||
| 417 | state->non_modal = NON_MODAL_NIL; | ||
| 418 | state->words_set = 0; | ||
| 419 | state->i = 0; | ||
| 420 | state->j = 0; | ||
| 421 | state->k = 0; | ||
| 422 | |||
| 423 | state->line = line->sv; | ||
| 424 | |||
| 425 | for (; child < child_end; ++child) { | ||
| 426 | ASSERT (RS274NGC_CST_NODE_KIND_EQ (*child, SEGMENT)); | ||
| 427 | struct rs274ngc_cst_branch *child_ptr = &RS274NGC_CST_NODE_PTR (*child)->branch; | ||
| 428 | union rs274ngc_cst_node **segment = &child_ptr->children[0]; | ||
| 429 | union rs274ngc_cst_node **segment_end = &child_ptr->children[child_ptr->count]; | ||
| 430 | for (; segment < segment_end; ++segment) { | ||
| 431 | struct rs274ngc_cst_branch *segment_ptr = | ||
| 432 | &RS274NGC_CST_NODE_PTR (*segment)->branch; | ||
| 433 | switch (RS274NGC_CST_NODE_KIND (*segment)) { | ||
| 434 | case RS274NGC_CST_NODE_KIND_WORD: | ||
| 435 | eval_word (state, segment_ptr); | ||
| 436 | break; | ||
| 437 | case RS274NGC_CST_NODE_KIND_PARAMETER_SETTING: | ||
| 438 | DA_APPEND (pb, eval_parameter_setting (state, segment_ptr)); | ||
| 439 | break; | ||
| 440 | case RS274NGC_CST_NODE_KIND_COMMENT: | ||
| 441 | break; | ||
| 442 | default: | ||
| 443 | DIE ("malformed segment"); | ||
| 444 | } | ||
| 445 | } | ||
| 446 | } | ||
| 447 | |||
| 448 | DA_FOR_EACH (spec, pb) | ||
| 449 | state->parameter_values[spec->index] = spec->value; | ||
| 450 | |||
| 451 | return 1; | ||
| 452 | } | ||
| 453 | |||
| 454 | return 0; | ||
| 455 | } | ||
diff --git a/src/rs274ngc_state.h b/src/rs274ngc_state.h new file mode 100644 index 0000000..477c207 --- /dev/null +++ b/src/rs274ngc_state.h | |||
| @@ -0,0 +1,204 @@ | |||
| 1 | /// src/rs274ngc_state.h | ||
| 2 | // | ||
| 3 | // Copyright (C) 2026 by Martin Michalec <martin@michalec.dev> | ||
| 4 | // | ||
| 5 | // SPDX-License-Identifier: MIT | ||
| 6 | // | ||
| 7 | /// Commentary: | ||
| 8 | // | ||
| 9 | /// Code: | ||
| 10 | |||
| 11 | #ifndef INCLUDED_RS274NGC_STATE_H | ||
| 12 | #define INCLUDED_RS274NGC_STATE_H | ||
| 13 | |||
| 14 | #include "rs274ngc_cst.h" | ||
| 15 | |||
| 16 | #define A_MASK (1 << 0) | ||
| 17 | #define B_MASK (1 << 1) | ||
| 18 | #define C_MASK (1 << 2) | ||
| 19 | #define D_MASK (1 << 3) | ||
| 20 | #define H_MASK (1 << 4) | ||
| 21 | #define I_MASK (1 << 5) | ||
| 22 | #define J_MASK (1 << 6) | ||
| 23 | #define K_MASK (1 << 7) | ||
| 24 | #define L_MASK (1 << 8) | ||
| 25 | #define N_MASK (1 << 9) | ||
| 26 | #define P_MASK (1 << 10) | ||
| 27 | #define Q_MASK (1 << 11) | ||
| 28 | #define R_MASK (1 << 12) | ||
| 29 | #define F_MASK (1 << 13) | ||
| 30 | #define S_MASK (1 << 14) | ||
| 31 | #define T_MASK (1 << 15) | ||
| 32 | #define X_MASK (1 << 16) | ||
| 33 | #define Y_MASK (1 << 17) | ||
| 34 | #define Z_MASK (1 << 18) | ||
| 35 | |||
| 36 | #define AXIS_MASK (A_MASK | B_MASK | C_MASK | X_MASK | Y_MASK | Z_MASK) | ||
| 37 | |||
| 38 | struct rs274ngc_state { | ||
| 39 | struct sv line; | ||
| 40 | |||
| 41 | enum non_modal { // group 0 | ||
| 42 | NON_MODAL_NIL, | ||
| 43 | NON_MODAL_DWELL, // G4 | ||
| 44 | NON_MODAL_SET_COORDINATE_SYSTEM_DATA, // G10 | ||
| 45 | NON_MODAL_RETURN_TO_HOME, // G28 | ||
| 46 | NON_MODAL_RETURN_TO_SECONDARY_HOME, // G30 | ||
| 47 | NON_MODAL_MOTION_IN_MACHINE_COORDINATE_SYSTEM, // G53 | ||
| 48 | NON_MODAL_OFFSET_COORDINATE_SYSTEMS_AND_SET_PARAMETERS, // G92 | ||
| 49 | NON_MODAL_CANCEL_OFFSET_COORDINATE_SYSTEMS_AND_SET_PARAMETERS_TO_ZERO, // G92.1 | ||
| 50 | NON_MODAL_CANCEL_OFFSET_COORDINATE_SYSTEMS_BUT_DO_NOT_RESET_PARAMETERS, // G92.2 | ||
| 51 | NON_MODAL_APPLY_PARAMETERS_TO_OFFSET_COORDINATE_SYSTEMS, // G92.3 | ||
| 52 | } non_modal; | ||
| 53 | |||
| 54 | enum motion { // group 1 | ||
| 55 | MOTION_RAPID_POSITIONING, // G0 | ||
| 56 | MOTION_LINEAR_INTERPOLATION, // G1 | ||
| 57 | MOTION_CIRCULAR_INTERPOLATION_CW, // G2 | ||
| 58 | MOTION_CIRCULAR_INTERPOLATION_CCW, // G3 | ||
| 59 | MOTION_STRAIGHT_PROBE, // G38.2 | ||
| 60 | MOTION_CANCEL_MOTION_MODE, // G80 (including any canned cycle) | ||
| 61 | MOTION_CANNED_CYCLE_DRILLING, // G81 | ||
| 62 | MOTION_CANNED_CYCLE_DRILLING_WITH_DWELL, // G82 | ||
| 63 | MOTION_CANNED_CYCLE_PECK_DRILLING, // G83 | ||
| 64 | MOTION_CANNED_CYCLE_RIGHT_HAND_TAPPING, // G84 | ||
| 65 | MOTION_CANNED_CYCLE_BORING_NO_DWELL_FEED_OUT, // G85 | ||
| 66 | MOTION_CANNED_CYCLE_BORING_SPINDLE_STOP_RAPID_OUT, // G86 | ||
| 67 | MOTION_CANNED_CYCLE_BACK_BORING, // G87 | ||
| 68 | MOTION_CANNED_CYCLE_BORING_SPINDLE_STOP_MANUAL_OUT, // G88 | ||
| 69 | MOTION_CANNED_CYCLE_BORING_DWELL_FEED_OUT, // G89 | ||
| 70 | } current_motion_mode; | ||
| 71 | |||
| 72 | enum plane_selection { // group 2 | ||
| 73 | PLANE_SELECTION_XY, // G17 | ||
| 74 | PLANE_SELECTION_XZ, // G18 | ||
| 75 | PLANE_SELECTION_YZ, // G19 | ||
| 76 | } plane_selection; | ||
| 77 | |||
| 78 | enum distance_mode { // group 3 | ||
| 79 | DISTANCE_MODE_ABSOLUTE, // G90 | ||
| 80 | DISTANCE_MODE_INCREMENTAL, // G91 | ||
| 81 | } distance_mode; | ||
| 82 | |||
| 83 | enum feed_rate_mode { // group 5 | ||
| 84 | FEED_RATE_MODE_INVERSE_TIME, // G93 | ||
| 85 | FEED_RATE_MODE_UNITS_PER_MINUTE, // G94 | ||
| 86 | } feed_rate_mode; | ||
| 87 | |||
| 88 | enum units { // group 6 | ||
| 89 | UNITS_INCH, // G20 | ||
| 90 | UNITS_MM, // G21 | ||
| 91 | } units; | ||
| 92 | |||
| 93 | enum cutter_radius_compensation { // group 7 | ||
| 94 | CUTTER_RADIUS_COMPENSATION_CANCEL, // G40 | ||
| 95 | CUTTER_RADIUS_COMPENSATION_START_LEFT, // G41 | ||
| 96 | CUTTER_RADIUS_COMPENSATION_START_RIGHT, // G42 | ||
| 97 | } cutter_radius_compensation; | ||
| 98 | |||
| 99 | enum tool_length_offset { // group 8 | ||
| 100 | TOOL_LENGTH_OFFSET_PLUS, // G43 | ||
| 101 | TOOL_LENGTH_OFFSET_CANCEL, // G49 | ||
| 102 | } tool_length_offset; | ||
| 103 | |||
| 104 | enum return_mode_in_canned_cycles { // group 10 | ||
| 105 | RETURN_MODE_IN_CANNED_CYCLES_INITIAL, // G98 | ||
| 106 | RETURN_MODE_IN_CANNED_CYCLES_R_POINT, // G99 | ||
| 107 | } return_mode_in_canned_cycles; | ||
| 108 | |||
| 109 | enum coordinate_system { // group 12 | ||
| 110 | COORDINATE_SYSTEM_PRESET_WORK_1, // G54 | ||
| 111 | COORDINATE_SYSTEM_PRESET_WORK_2, // G55 | ||
| 112 | COORDINATE_SYSTEM_PRESET_WORK_3, // G56 | ||
| 113 | COORDINATE_SYSTEM_PRESET_WORK_4, // G57 | ||
| 114 | COORDINATE_SYSTEM_PRESET_WORK_5, // G58 | ||
| 115 | COORDINATE_SYSTEM_PRESET_WORK_6, // G59 | ||
| 116 | COORDINATE_SYSTEM_PRESET_WORK_7, // G59.1 | ||
| 117 | COORDINATE_SYSTEM_PRESET_WORK_8, // G59.2 | ||
| 118 | COORDINATE_SYSTEM_PRESET_WORK_9, // G59.3 | ||
| 119 | } coordinate_system; | ||
| 120 | |||
| 121 | enum path_control_mode { // group 13 | ||
| 122 | PATH_CONTROL_MODE_EXACT_PATH, // G61 | ||
| 123 | PATH_CONTROL_MODE_EXACT_STOP, // G61.1 | ||
| 124 | PATH_CONTROL_MODE_CONTINUOS, // G64 | ||
| 125 | } path_control_mode; | ||
| 126 | |||
| 127 | enum stopping { // group 4 | ||
| 128 | STOPPING_NIL, | ||
| 129 | STOPPING_STOP, // M0 | ||
| 130 | STOPPING_STOP_OPTIONAL, // M1 | ||
| 131 | STOPPING_END, // M2 | ||
| 132 | STOPPING_EXCHANGE_PALLETE_SHUTES_AND_END, // M30 | ||
| 133 | STOPPING_EXCHANGE_PALLETE_SHUTES_AND_STOP, // M60 | ||
| 134 | } stopping; | ||
| 135 | |||
| 136 | enum tool_change { // group 6 | ||
| 137 | TOOL_CHANGE_NIL, | ||
| 138 | TOOL_CHANGE, // M6 | ||
| 139 | } tool_change; | ||
| 140 | |||
| 141 | enum spindle_turning { // group 7 | ||
| 142 | SPINDLE_TURNING_NIL, | ||
| 143 | SPINDLE_TURNING_START_CW, // M3 | ||
| 144 | SPINDLE_TURNING_START_CCW, // M4 | ||
| 145 | SPINDLE_TURNING_STOP, // M5 | ||
| 146 | } spindle_turning; | ||
| 147 | |||
| 148 | // NOTE(cmmm):special case: M7 and M8 may be active at the same time | ||
| 149 | enum coolant { // group 8 | ||
| 150 | COOLANT_OFF, // M9 | ||
| 151 | COOLANT_ON_MIST, // M7 | ||
| 152 | COOLANT_ON_FLOOD, // M8 | ||
| 153 | COOLANT_ON_BOTH, | ||
| 154 | } coolant; | ||
| 155 | |||
| 156 | enum override_switches { // group 9 | ||
| 157 | OVERRIDE_SWITCHES_DISABLE, // M49 | ||
| 158 | OVERRIDE_SWITCHES_ENABLE, // M48 | ||
| 159 | } override_switches; | ||
| 160 | |||
| 161 | int words_set; | ||
| 162 | |||
| 163 | double a; // A-axis of machine | ||
| 164 | double b; // B-axis of machine | ||
| 165 | double c; // C-axis of machine | ||
| 166 | |||
| 167 | double d; // tool radius compensation number | ||
| 168 | double h; // tool length offset index | ||
| 169 | |||
| 170 | double i; // X-axis offset for arcs / X offset in G87 canned cycle | ||
| 171 | double j; // Y-axis offset for arcs / Y offset in G87 canned cycle | ||
| 172 | double k; // Z-axis offset for arcs / Z offset in G87 canned cycle | ||
| 173 | |||
| 174 | double l; // number of repetitions in canned cycles, key used with G10 | ||
| 175 | |||
| 176 | double n; // line number | ||
| 177 | |||
| 178 | double p; // dwell time in canned cycles, dwell time with G4, key used with G10 | ||
| 179 | |||
| 180 | double q; // feed increment in G83 canned cycle | ||
| 181 | |||
| 182 | double r; // arc radius, canned cycle plane | ||
| 183 | |||
| 184 | double f; // feed rate | ||
| 185 | double s; // spindle speed | ||
| 186 | double t; // tool selection | ||
| 187 | |||
| 188 | double x; // X-axis of machine | ||
| 189 | double y; // Y-axis of machine | ||
| 190 | double z; // Z-axis of machine | ||
| 191 | |||
| 192 | struct coordinate_system_data { | ||
| 193 | double x, y, z; | ||
| 194 | double a, b, c; | ||
| 195 | } coordinate_system_data[9]; | ||
| 196 | |||
| 197 | double parameter_values[5400]; | ||
| 198 | }; | ||
| 199 | |||
| 200 | int rs274ngc_state_next (struct rs274ngc_state *, struct rs274ngc_cst_parser); | ||
| 201 | |||
| 202 | #endif // INCLUDED_RS274NGC_STATE_H | ||
| 203 | |||
| 204 | /// src/rs274ngc_state.h ends here | ||
diff --git a/src/simulate.c b/src/simulate.c new file mode 100644 index 0000000..e053599 --- /dev/null +++ b/src/simulate.c | |||
| @@ -0,0 +1,646 @@ | |||
| 1 | /// src/simulate.h | ||
| 2 | // | ||
| 3 | // Copyright (C) 2026 by Martin Michalec <martin@michalec.dev> | ||
| 4 | // | ||
| 5 | // SPDX-License-Identifier: MIT | ||
| 6 | // | ||
| 7 | /// Commentary: | ||
| 8 | // | ||
| 9 | /// Code: | ||
| 10 | |||
| 11 | #include <stdlib.h> | ||
| 12 | #include <stdio.h> | ||
| 13 | #include <fcntl.h> | ||
| 14 | #include <unistd.h> | ||
| 15 | |||
| 16 | #include <raylib.h> | ||
| 17 | #include <raymath.h> | ||
| 18 | #include <rlgl.h> | ||
| 19 | |||
| 20 | #include "utils.h" | ||
| 21 | #include "da.h" | ||
| 22 | #include "rs274ngc_lexer.h" | ||
| 23 | #include "rs274ngc_cst.h" | ||
| 24 | #include "path.h" | ||
| 25 | #include "motion_planner.h" | ||
| 26 | #include "critical_points.h" | ||
| 27 | #include "compensations.h" | ||
| 28 | #include "rate.h" | ||
| 29 | |||
| 30 | #define LINE_THICKNESS 4 | ||
| 31 | #define TITLE "RS274NGC Simulator" | ||
| 32 | |||
| 33 | #define DPU 8 // dots per unit | ||
| 34 | |||
| 35 | struct point { | ||
| 36 | Vector2 c; | ||
| 37 | Vector2 n; | ||
| 38 | }; | ||
| 39 | |||
| 40 | struct points { | ||
| 41 | struct point *items; | ||
| 42 | uint32_t count; | ||
| 43 | uint32_t capacity; | ||
| 44 | } points = {0}; | ||
| 45 | |||
| 46 | struct rgb32 { | ||
| 47 | uint8_t r, g, b, a; | ||
| 48 | }; | ||
| 49 | |||
| 50 | struct overlay { | ||
| 51 | const char *name; | ||
| 52 | struct rgb32 *items; | ||
| 53 | uint32_t count; | ||
| 54 | uint32_t capacity; | ||
| 55 | }; | ||
| 56 | |||
| 57 | struct overlays { | ||
| 58 | struct overlay *items; | ||
| 59 | uint32_t count; | ||
| 60 | uint32_t capacity; | ||
| 61 | } overlays = {0}; | ||
| 62 | |||
| 63 | struct path path = {0}; | ||
| 64 | struct critical_points cps = {0}; | ||
| 65 | struct compensations comps = {0}; | ||
| 66 | |||
| 67 | struct rgb32 | ||
| 68 | lerp_rgb32 (struct rgb32 a, struct rgb32 b, float t) | ||
| 69 | { | ||
| 70 | struct rgb32 c; | ||
| 71 | c.r = (uint8_t) (a.r + (b.r - a.r)*t); | ||
| 72 | c.g = (uint8_t) (a.g + (b.g - a.g)*t); | ||
| 73 | c.b = (uint8_t) (a.b + (b.b - a.b)*t); | ||
| 74 | c.a = (uint8_t) (a.a + (b.a - a.a)*t); | ||
| 75 | return c; | ||
| 76 | } | ||
| 77 | |||
| 78 | void | ||
| 79 | print_arena (const struct arena *a) | ||
| 80 | { | ||
| 81 | for (struct arena_chunk *ch = a->head; ch; ch = ch->next) | ||
| 82 | printf ("%p %lu\n", ch, (void *) ch - ch->begin); | ||
| 83 | } | ||
| 84 | |||
| 85 | void | ||
| 86 | print_path (struct path path) | ||
| 87 | { | ||
| 88 | DA_FOR_EACH (pe, path) { | ||
| 89 | printf ("%04b | %10.4lf | %10.4lf | %10.4lf | %10.4lf | %10.4lf | %.*s\n", | ||
| 90 | pe->flags, pe->x, pe->y, pe->f, pe->i, pe->j, SV_FMTA (pe->line)); | ||
| 91 | } | ||
| 92 | } | ||
| 93 | |||
| 94 | void | ||
| 95 | draw_path (struct path path) | ||
| 96 | { | ||
| 97 | SetConfigFlags (FLAG_MSAA_4X_HINT | FLAG_VSYNC_HINT); | ||
| 98 | InitWindow (700, 700, TITLE); | ||
| 99 | Camera2D camera = { | ||
| 100 | .zoom = 8, | ||
| 101 | }; | ||
| 102 | |||
| 103 | int first = 1; | ||
| 104 | while (!WindowShouldClose ()) { | ||
| 105 | float line_thickness = LINE_THICKNESS/camera.zoom; | ||
| 106 | |||
| 107 | Vector2 cursor = Vector2Zero (); | ||
| 108 | if (IsMouseButtonDown (MOUSE_BUTTON_LEFT) || | ||
| 109 | IsMouseButtonDown (MOUSE_BUTTON_RIGHT)) { | ||
| 110 | camera.target = Vector2Add (camera.target, Vector2Scale (GetMouseDelta (), -1/camera.zoom)); | ||
| 111 | } | ||
| 112 | |||
| 113 | float wheel_move = -GetMouseWheelMove (); | ||
| 114 | if (wheel_move) { | ||
| 115 | Vector2 offset = GetMousePosition (); | ||
| 116 | camera.target = GetScreenToWorld2D (offset, camera); | ||
| 117 | camera.offset = offset; | ||
| 118 | camera.zoom = Clamp (expf (logf (camera.zoom) + .2*wheel_move), 4, 128); | ||
| 119 | } | ||
| 120 | |||
| 121 | BeginDrawing (); | ||
| 122 | ClearBackground (WHITE); | ||
| 123 | BeginMode2D (camera); | ||
| 124 | |||
| 125 | // DrawLine (-1000, 0, +1000, 0, GRAY); | ||
| 126 | // DrawLine (0, -1000, 0, +1000, GRAY); | ||
| 127 | rlPushMatrix (); | ||
| 128 | rlTranslatef (100, 0, 0); | ||
| 129 | rlRotatef (90, 1, 0, 0); | ||
| 130 | DrawGrid (200, 1); | ||
| 131 | rlPopMatrix(); | ||
| 132 | |||
| 133 | DA_FOR_EACH (pe, path) { | ||
| 134 | Vector2 from = cursor; | ||
| 135 | cursor = (Vector2) { pe->x, -pe->y }; | ||
| 136 | if (pe->flags & PEF_ARC) { | ||
| 137 | Vector2 center = { pe->i, -pe->j }; | ||
| 138 | float r = Vector2Distance (from, center); | ||
| 139 | |||
| 140 | Vector2 v0 = Vector2Subtract (from, center); | ||
| 141 | Vector2 v1 = Vector2Subtract (cursor, center); | ||
| 142 | float angle_beg = Vector2Angle ((Vector2) { 1, 0 }, v0)/PI*180; | ||
| 143 | float angle_end = Vector2Angle ((Vector2) { 1, 0 }, v1)/PI*180; | ||
| 144 | if (first) printf ("< %f %f | " SV_FMT "\n", angle_beg, angle_end, SV_FMTA (pe->line)); | ||
| 145 | if (pe->flags & PEF_CCW) { | ||
| 146 | float tmp = angle_beg; | ||
| 147 | angle_beg = angle_end; | ||
| 148 | angle_end = tmp; | ||
| 149 | } | ||
| 150 | if (angle_beg > angle_end) | ||
| 151 | angle_end += 360; | ||
| 152 | if (Vector2Equals (from, cursor)) { | ||
| 153 | angle_beg = 0; | ||
| 154 | angle_end = 360; | ||
| 155 | } | ||
| 156 | if (first) printf ("< %f %f\n\n", angle_beg, angle_end); | ||
| 157 | |||
| 158 | DrawCircleV (center, line_thickness/2, GREEN); | ||
| 159 | DrawRing (center, r - line_thickness/2, r + line_thickness/2, | ||
| 160 | angle_beg, angle_end, 32, BLUE); | ||
| 161 | } else { | ||
| 162 | if (pe->flags & PEF_TRAVERSING) { | ||
| 163 | // DrawLineV (from, cursor, ORANGE); | ||
| 164 | DrawCircleV (from, line_thickness/4, ORANGE); | ||
| 165 | DrawLineEx (from, cursor, line_thickness/2, ORANGE); | ||
| 166 | DrawCircleV (cursor, line_thickness/4, ORANGE); | ||
| 167 | } else { | ||
| 168 | // DrawLineV (from, cursor, BLUE); | ||
| 169 | DrawCircleV (from, line_thickness/2, BLUE); | ||
| 170 | DrawLineEx (from, cursor, line_thickness, BLUE); | ||
| 171 | DrawCircleV (cursor, line_thickness/2, BLUE); | ||
| 172 | } | ||
| 173 | } | ||
| 174 | } | ||
| 175 | EndMode2D (); | ||
| 176 | EndDrawing (); | ||
| 177 | first = 0; | ||
| 178 | } | ||
| 179 | |||
| 180 | CloseWindow (); | ||
| 181 | } | ||
| 182 | |||
| 183 | void | ||
| 184 | draw_grid (Rectangle bb, float step) | ||
| 185 | { | ||
| 186 | rlBegin (RL_LINES); | ||
| 187 | int i = 0; | ||
| 188 | for (float y = bb.y; y <= bb.y + bb.height; y += step) { | ||
| 189 | if (i % 10 == 0) { | ||
| 190 | rlColor3f (.25, .25, .25); | ||
| 191 | rlColor3f (.25, .25, .25); | ||
| 192 | } else { | ||
| 193 | rlColor3f (.5, .5, .5); | ||
| 194 | rlColor3f (.5, .5, .5); | ||
| 195 | } i += 1; | ||
| 196 | |||
| 197 | rlVertex3f (bb.x, -y, 0); | ||
| 198 | rlVertex3f (bb.x + bb.width, -y, 0); | ||
| 199 | } | ||
| 200 | i = 0; | ||
| 201 | for (float x = bb.x; x <= bb.x + bb.width; x += step) { | ||
| 202 | if (i % 10 == 0) { | ||
| 203 | rlColor3f (.25, .25, .25); | ||
| 204 | rlColor3f (.25, .25, .25); | ||
| 205 | } else { | ||
| 206 | rlColor3f (.5, .5, .5); | ||
| 207 | rlColor3f (.5, .5, .5); | ||
| 208 | } i += 1; | ||
| 209 | |||
| 210 | rlVertex3f (x, -bb.y, 0); | ||
| 211 | rlVertex3f (x, -bb.y - bb.height, 0); | ||
| 212 | } | ||
| 213 | rlEnd (); | ||
| 214 | } | ||
| 215 | |||
| 216 | #define ARROW_LENGTH .5 | ||
| 217 | #define ARROW_ANGLE 10 | ||
| 218 | |||
| 219 | void | ||
| 220 | draw_arrow (Vector2 beg, Vector2 end, float thick, Color c) | ||
| 221 | { | ||
| 222 | Vector2 off = Vector2Scale (Vector2Normalize (Vector2Subtract (end, beg)), | ||
| 223 | ARROW_LENGTH); | ||
| 224 | Vector2 ahl = Vector2Add (end, Vector2Rotate (off, +ARROW_ANGLE)); | ||
| 225 | Vector2 ahr = Vector2Add (end, Vector2Rotate (off, -ARROW_ANGLE)); | ||
| 226 | |||
| 227 | DrawLineEx (beg, end, thick, c); | ||
| 228 | DrawLineEx (end, ahl, thick, c); | ||
| 229 | DrawLineEx (end, ahr, thick, c); | ||
| 230 | |||
| 231 | DrawCircleV (beg, thick/2., c); | ||
| 232 | DrawCircleV (end, thick/2., c); | ||
| 233 | DrawCircleV (ahl, thick/2., c); | ||
| 234 | DrawCircleV (ahr, thick/2., c); | ||
| 235 | } | ||
| 236 | |||
| 237 | void | ||
| 238 | visualize (void) | ||
| 239 | { | ||
| 240 | uint32_t active_overlay = 0; | ||
| 241 | |||
| 242 | SetConfigFlags (FLAG_MSAA_4X_HINT | | ||
| 243 | FLAG_VSYNC_HINT | | ||
| 244 | FLAG_WINDOW_UNDECORATED | | ||
| 245 | FLAG_BORDERLESS_WINDOWED_MODE | | ||
| 246 | FLAG_WINDOW_RESIZABLE | | ||
| 247 | 0); | ||
| 248 | float s = 1.25; | ||
| 249 | // InitWindow (700*s, 700, TextFormat (TITLE " - %s", overlays.items[active_overlay].name)); | ||
| 250 | InitWindow (750, 650, TextFormat (TITLE " - %s", overlays.items[active_overlay].name)); | ||
| 251 | SetTargetFPS (60); | ||
| 252 | rlDisableBackfaceCulling (); | ||
| 253 | |||
| 254 | Camera2D camera = { | ||
| 255 | // .zoom = 16, | ||
| 256 | .zoom = 7*s, | ||
| 257 | .offset = { | ||
| 258 | .x = 0, | ||
| 259 | .y = GetScreenHeight (), | ||
| 260 | }, | ||
| 261 | .target = { | ||
| 262 | .x = 25.85, | ||
| 263 | .y = -33.6, | ||
| 264 | }, | ||
| 265 | }; | ||
| 266 | |||
| 267 | int draw_grid_flag = 1; | ||
| 268 | int draw_fps_flag = 0; | ||
| 269 | int draw_cps_flag = 0; | ||
| 270 | int draw_comps_flag = 0; | ||
| 271 | // uint32_t from = 37120; | ||
| 272 | // uint32_t upto = 48080; | ||
| 273 | // uint32_t from = 17800; | ||
| 274 | // uint32_t upto = 24000; | ||
| 275 | uint32_t from = 0; | ||
| 276 | uint32_t upto = points.count; | ||
| 277 | while (!WindowShouldClose ()) { | ||
| 278 | if (IsKeyPressed (KEY_UP)) { | ||
| 279 | active_overlay = (active_overlay + 1) % overlays.count; | ||
| 280 | SetWindowTitle (TextFormat (TITLE " - %s", overlays.items[active_overlay].name)); | ||
| 281 | } | ||
| 282 | if (IsKeyPressed (KEY_DOWN)) { | ||
| 283 | active_overlay = overlays.count - 1 - (overlays.count - active_overlay) % overlays.count; | ||
| 284 | SetWindowTitle (TextFormat (TITLE " - %s", overlays.items[active_overlay].name)); | ||
| 285 | } | ||
| 286 | |||
| 287 | uint32_t speed = (300 + 700*IsKeyDown (KEY_LEFT_SHIFT))*GetFrameTime (); | ||
| 288 | // speed = 1; | ||
| 289 | if (IsKeyUp (KEY_LEFT_CONTROL)) { | ||
| 290 | if (IsKeyDown (KEY_RIGHT)) | ||
| 291 | upto = (upto + speed) % (points.count + 1); | ||
| 292 | if (IsKeyDown (KEY_LEFT)) | ||
| 293 | upto = upto <= speed ? from : upto - speed; | ||
| 294 | } else { | ||
| 295 | if (IsKeyDown (KEY_RIGHT)) | ||
| 296 | from = (from + speed) % (upto + 1); | ||
| 297 | if (IsKeyDown (KEY_LEFT)) | ||
| 298 | from = from <= speed ? points.count : from - speed; | ||
| 299 | } | ||
| 300 | |||
| 301 | if (IsKeyPressed (KEY_G)) | ||
| 302 | draw_grid_flag = !draw_grid_flag; | ||
| 303 | if (IsKeyPressed (KEY_F)) | ||
| 304 | draw_fps_flag = !draw_fps_flag; | ||
| 305 | if (IsKeyPressed (KEY_P)) | ||
| 306 | draw_cps_flag = !draw_cps_flag; | ||
| 307 | if (IsKeyPressed (KEY_C)) | ||
| 308 | draw_comps_flag = !draw_comps_flag; | ||
| 309 | |||
| 310 | float line_thickness = LINE_THICKNESS/camera.zoom; | ||
| 311 | |||
| 312 | Vector2 cursor = Vector2Zero (); | ||
| 313 | if (IsMouseButtonDown (MOUSE_BUTTON_LEFT) || | ||
| 314 | IsMouseButtonDown (MOUSE_BUTTON_RIGHT)) { | ||
| 315 | camera.target = | ||
| 316 | Vector2Add (camera.target, | ||
| 317 | Vector2Scale (GetMouseDelta (), -1/camera.zoom)); | ||
| 318 | } | ||
| 319 | |||
| 320 | float wheel_move = -GetMouseWheelMove (); | ||
| 321 | if (wheel_move) { | ||
| 322 | Vector2 offset = GetMousePosition (); | ||
| 323 | camera.target = GetScreenToWorld2D (offset, camera); | ||
| 324 | camera.offset = offset; | ||
| 325 | camera.zoom = Clamp (expf (logf (camera.zoom) + .2*wheel_move), 4, 128); | ||
| 326 | } | ||
| 327 | |||
| 328 | Rectangle screen = { | ||
| 329 | .width = GetScreenWidth (), | ||
| 330 | .height = GetScreenHeight (), | ||
| 331 | }; | ||
| 332 | |||
| 333 | BeginDrawing (); | ||
| 334 | ClearBackground (WHITE); | ||
| 335 | BeginMode2D (camera); | ||
| 336 | |||
| 337 | float grid_size = 200; | ||
| 338 | if (draw_grid_flag) { | ||
| 339 | // rlPushMatrix (); | ||
| 340 | // rlTranslatef (grid_size/2, 0, 0); | ||
| 341 | // rlRotatef (90, 1, 0, 0); | ||
| 342 | // DrawGrid (grid_size, 1); | ||
| 343 | // rlPopMatrix(); | ||
| 344 | draw_grid ((Rectangle) { 0, 0, 100, 80 }, 10); | ||
| 345 | } | ||
| 346 | |||
| 347 | struct overlay *overlay = &overlays.items[active_overlay]; | ||
| 348 | |||
| 349 | uint32_t i = from; | ||
| 350 | struct rgb32 pc = overlay->items[i]; | ||
| 351 | |||
| 352 | Vector2 c = points.items[i].c; | ||
| 353 | Vector2 n = Vector2Scale (points.items[i].n, LINE_THICKNESS/2/camera.zoom); | ||
| 354 | Vector2 pl = Vector2Add (c, n); | ||
| 355 | Vector2 pr = Vector2Subtract (c, n); | ||
| 356 | |||
| 357 | rlBegin (RL_TRIANGLES); | ||
| 358 | for (i = from + 1; i < upto; i += logf (128)/logf (camera.zoom)) { | ||
| 359 | Vector2 c = points.items[i].c; | ||
| 360 | Vector2 n = Vector2Scale (points.items[i].n, LINE_THICKNESS/2/camera.zoom); | ||
| 361 | Vector2 cl = Vector2Add (c, n); | ||
| 362 | Vector2 cr = Vector2Subtract (c, n); | ||
| 363 | |||
| 364 | struct rgb32 cc = overlay->items[i]; | ||
| 365 | |||
| 366 | rlColor4ub (pc.r, pc.g, pc.b, pc.a); rlVertex2f (pl.x, pl.y); | ||
| 367 | rlColor4ub (cc.r, cc.g, cc.b, cc.a); rlVertex2f (cl.x, cl.y); | ||
| 368 | rlColor4ub (pc.r, pc.g, pc.b, pc.a); rlVertex2f (pr.x, pr.y); | ||
| 369 | |||
| 370 | rlColor4ub (pc.r, pc.g, pc.b, pc.a); rlVertex2f (pr.x, pr.y); | ||
| 371 | rlColor4ub (cc.r, cc.g, cc.b, cc.a); rlVertex2f (cl.x, cl.y); | ||
| 372 | rlColor4ub (cc.r, cc.g, cc.b, cc.a); rlVertex2f (cr.x, cr.y); | ||
| 373 | |||
| 374 | pl = cl; | ||
| 375 | pr = cr; | ||
| 376 | pc = cc; | ||
| 377 | } | ||
| 378 | rlEnd (); | ||
| 379 | |||
| 380 | if (draw_comps_flag) { | ||
| 381 | for (uint32_t i = 0; i < comps.count; ++i) { | ||
| 382 | const struct compensation *c = &comps.items[i]; | ||
| 383 | const struct polyline *pl = &c->polyline; | ||
| 384 | Vector2 from = { c->initial_position.x, -c->initial_position.y }; | ||
| 385 | for (uint32_t j = 0; j < pl->count; ++j) { | ||
| 386 | struct vec2 tov = pl->items[j]; | ||
| 387 | Vector2 to = { tov.x, -tov.y }; | ||
| 388 | DrawLineEx (from, to, line_thickness/2, GREEN); | ||
| 389 | from = to; | ||
| 390 | } | ||
| 391 | } | ||
| 392 | } | ||
| 393 | |||
| 394 | if (draw_cps_flag) { | ||
| 395 | for (uint32_t i = 0; i < cps.count; ++i) { | ||
| 396 | const struct critical_point *cp = &cps.items[i]; | ||
| 397 | Vector2 c = { cp->r.x, -cp->r.y }; | ||
| 398 | Vector2 in = { 1.5*cp->t_left .x, -1.5*cp->t_left .y }; | ||
| 399 | Vector2 out = { 1.5*cp->t_right.x, -1.5*cp->t_right.y }; | ||
| 400 | |||
| 401 | struct Color colors[] = { | ||
| 402 | [CPT_IN ] = RED, | ||
| 403 | [CPT_OUT ] = GREEN, | ||
| 404 | [CPT_LOOP] = BLACK, | ||
| 405 | [CPT_BEG ] = RED, | ||
| 406 | [CPT_END ] = GREEN, | ||
| 407 | }; | ||
| 408 | DrawCircleV (c, line_thickness, colors[cp->type]); | ||
| 409 | // DrawCircleV (c, 2*line_thickness, BLACK); | ||
| 410 | |||
| 411 | draw_arrow (c, Vector2Add (c, in ), line_thickness, GREEN); | ||
| 412 | draw_arrow (c, Vector2Add (c, out), line_thickness, RED); | ||
| 413 | } | ||
| 414 | } | ||
| 415 | |||
| 416 | EndMode2D (); | ||
| 417 | if (draw_fps_flag) | ||
| 418 | DrawFPS (2, 0); | ||
| 419 | // DrawText (TextFormat ("FROM: %u", from), 2, 0, 20, BLACK); | ||
| 420 | // DrawText (TextFormat ("UPTO: %u", upto), 2, 20, 20, BLACK); | ||
| 421 | // DrawText (TextFormat ("WIDTH: %d", GetScreenWidth ()), 2, 0*20, 20, BLACK); | ||
| 422 | // DrawText (TextFormat ("HEIGHT: %d", GetScreenHeight ()), 2, 1*20, 20, BLACK); | ||
| 423 | // DrawText (TextFormat ("ZOOM: %f", camera.zoom ), 2, 2*20, 20, BLACK); | ||
| 424 | // DrawText (TextFormat ("XOFF: %f", camera.offset.x ), 2, 3*20, 20, BLACK); | ||
| 425 | // DrawText (TextFormat ("YOFF: %f", camera.offset.y ), 2, 4*20, 20, BLACK); | ||
| 426 | // DrawText (TextFormat ("YTAR: %f", camera.target.x ), 2, 5*20, 20, BLACK); | ||
| 427 | // DrawText (TextFormat ("YTAR: %f", camera.target.y ), 2, 6*20, 20, BLACK); | ||
| 428 | EndDrawing (); | ||
| 429 | } | ||
| 430 | |||
| 431 | CloseWindow (); | ||
| 432 | } | ||
| 433 | |||
| 434 | struct overlay line_overlay = { .name = "line" }; | ||
| 435 | struct overlay type_overlay = { .name = "type" }; | ||
| 436 | struct overlay velocity_overlay = { .name = "velocity" }; | ||
| 437 | struct overlay velocity_error_overlay = { .name = "velocity error" }; | ||
| 438 | struct overlay velocity_error_alpha_overlay = { .name = "velocity error (alpha)" }; | ||
| 439 | struct overlay acceleration_overlay = { .name = "acceleration" }; | ||
| 440 | struct overlay acceleration_t_overlay = { .name = "tangential acceleration" }; | ||
| 441 | struct overlay acceleration_n_overlay = { .name = "normal acceleration" }; | ||
| 442 | struct overlay jerk_overlay = { .name = "jerk" }; | ||
| 443 | struct overlay jerk_alpha_overlay = { .name = "jerk (alpha)" }; | ||
| 444 | |||
| 445 | void | ||
| 446 | add_sample (const struct motion_plan *plan, | ||
| 447 | const struct mp_sample *sample) | ||
| 448 | { | ||
| 449 | struct point point = { | ||
| 450 | .c = { sample->p.x, -sample->p.y }, | ||
| 451 | .n = { sample->normal.x, -sample->normal.y }, | ||
| 452 | }; | ||
| 453 | if (sample->source_flags & PEF_TRAVERSING) { | ||
| 454 | point.n.x /= 2; | ||
| 455 | point.n.y /= 2; | ||
| 456 | } | ||
| 457 | DA_APPEND (points, point); | ||
| 458 | struct rgb32 red = { 0xff, 0x00, 0x00, 0xff }; | ||
| 459 | struct rgb32 blue = { 0x00, 0x00, 0xff, 0xff }; | ||
| 460 | struct rgb32 green = { 0x00, 0xff, 0x00, 0xff }; | ||
| 461 | struct rgb32 orange = { 0xff, 0x7f, 0x00, 0xff }; | ||
| 462 | struct rgb32 blank = { 0x00, 0x00, 0x00, 0x00 }; | ||
| 463 | if (sample->source_flags & PEF_TRAVERSING) { | ||
| 464 | DA_APPEND ( velocity_overlay, orange); | ||
| 465 | DA_APPEND (velocity_error_overlay, orange); | ||
| 466 | DA_APPEND (velocity_error_alpha_overlay, blank); | ||
| 467 | DA_APPEND (jerk_alpha_overlay, blank); | ||
| 468 | DA_APPEND ( acceleration_t_overlay, orange); | ||
| 469 | DA_APPEND ( acceleration_n_overlay, orange); | ||
| 470 | DA_APPEND ( jerk_overlay, orange); | ||
| 471 | } | ||
| 472 | else { | ||
| 473 | struct rgb32 black_red = { 0xff, 0x00, 0x00, 0x00 }; | ||
| 474 | double v_nominal = plan->segments[sample->segment_index].v_nominal; | ||
| 475 | double error = fabs (sample->v - v_nominal); | ||
| 476 | float t = Normalize (error, plan->v_min, v_nominal); | ||
| 477 | DA_APPEND (velocity_error_overlay, lerp_rgb32 (green, red, t)); | ||
| 478 | DA_APPEND (velocity_error_alpha_overlay, lerp_rgb32 (black_red, red, t)); | ||
| 479 | struct rgb32 jc = lerp_rgb32 (red, blue, Normalize (sample->j_abs, plan->j_min, plan->j_max)); | ||
| 480 | jc.a = 0xff*Clamp (Normalize (sample->j_abs, 0, sample->j_abs > 0 ? plan->j_max : plan->j_min), 0, 1); | ||
| 481 | DA_APPEND (jerk_alpha_overlay, jc); | ||
| 482 | } | ||
| 483 | |||
| 484 | DA_APPEND ( velocity_overlay, lerp_rgb32 (red, blue, Normalize (sample->v, plan->v_min, plan->v_max))); | ||
| 485 | DA_APPEND (acceleration_t_overlay, lerp_rgb32 (red, blue, Normalize (sample->a_t, plan->a_min, plan->a_max))); | ||
| 486 | DA_APPEND (acceleration_n_overlay, lerp_rgb32 (red, blue, Normalize (sample->a_n, plan->a_min, plan->a_max))); | ||
| 487 | DA_APPEND ( jerk_overlay, lerp_rgb32 (red, blue, Normalize (sample->j_abs, plan->j_min, plan->j_max))); | ||
| 488 | |||
| 489 | struct rgb32 colors[] = { | ||
| 490 | { 0xff, 0x00, 0x00, 0xff }, | ||
| 491 | { 0x00, 0xff, 0xff, 0xff }, | ||
| 492 | { 0x00, 0xff, 0x00, 0xff }, | ||
| 493 | { 0xff, 0x00, 0xff, 0xff }, | ||
| 494 | { 0x00, 0x00, 0xff, 0xff }, | ||
| 495 | { 0xff, 0xff, 0x00, 0xff }, | ||
| 496 | }; | ||
| 497 | DA_APPEND (line_overlay, colors[sample->source_index % ARRAY_LENGTH (colors)]); | ||
| 498 | |||
| 499 | if (sample->source_flags & PEF_ARC) { | ||
| 500 | if (sample->source_flags & PEF_CCW) | ||
| 501 | DA_APPEND (type_overlay, red); | ||
| 502 | else | ||
| 503 | DA_APPEND (type_overlay, green); | ||
| 504 | } else { | ||
| 505 | if (sample->source_flags & PEF_TRAVERSING) | ||
| 506 | DA_APPEND (type_overlay, orange); | ||
| 507 | else | ||
| 508 | DA_APPEND (type_overlay, blue); | ||
| 509 | } | ||
| 510 | } | ||
| 511 | |||
| 512 | void | ||
| 513 | build_overlays (const struct motion_plan *plan) | ||
| 514 | { | ||
| 515 | double dt = .001; | ||
| 516 | |||
| 517 | struct mp_sample smp; | ||
| 518 | for (double t = 0; t < plan->total_time; t += dt) { | ||
| 519 | mp_plan_sample (plan, t, &smp); | ||
| 520 | add_sample (plan, &smp); | ||
| 521 | } mp_plan_sample (plan, plan->total_time, &smp); | ||
| 522 | add_sample (plan, &smp); | ||
| 523 | |||
| 524 | DA_APPEND (overlays, line_overlay); | ||
| 525 | DA_APPEND (overlays, type_overlay); | ||
| 526 | DA_APPEND (overlays, velocity_overlay); | ||
| 527 | DA_APPEND (overlays, velocity_error_overlay); | ||
| 528 | DA_APPEND (overlays, velocity_error_alpha_overlay); | ||
| 529 | DA_APPEND (overlays, acceleration_t_overlay); | ||
| 530 | DA_APPEND (overlays, acceleration_n_overlay); | ||
| 531 | DA_APPEND (overlays, jerk_overlay); | ||
| 532 | DA_APPEND (overlays, jerk_alpha_overlay); | ||
| 533 | } | ||
| 534 | |||
| 535 | int | ||
| 536 | main (int argc, char *argv[]) | ||
| 537 | { | ||
| 538 | progname = argv[0]; | ||
| 539 | |||
| 540 | const char *filename; | ||
| 541 | int fd = 0; | ||
| 542 | if (argc == 1) { | ||
| 543 | filename = "-"; | ||
| 544 | } else if (argc == 2) { | ||
| 545 | filename = argv[1]; | ||
| 546 | fd = open (filename, O_RDONLY); | ||
| 547 | } else { | ||
| 548 | DIE ("too many arguments provided"); | ||
| 549 | } | ||
| 550 | |||
| 551 | struct arena a = {0}; | ||
| 552 | struct arena t = {0}; | ||
| 553 | |||
| 554 | struct sv rs274ngc = read_until_eof (&a, fd); | ||
| 555 | if (fd) close (fd); | ||
| 556 | |||
| 557 | rs274ngc_lexer_compile_regexes (); | ||
| 558 | struct rs274ngc_lexer lexer = rs274ngc_lexer_from_sv (rs274ngc, filename); | ||
| 559 | |||
| 560 | struct rs274ngc_cst_parser parser = { | ||
| 561 | .lexer = &lexer, | ||
| 562 | .output = &a, | ||
| 563 | .temporary = &t, | ||
| 564 | }; | ||
| 565 | |||
| 566 | path = build_path (parser); | ||
| 567 | ASSERT (path.count > 0); | ||
| 568 | // print_path (path); | ||
| 569 | // draw_path (path); | ||
| 570 | // return 0; | ||
| 571 | |||
| 572 | double initial_x = 0; | ||
| 573 | double initial_y = 0; | ||
| 574 | |||
| 575 | struct mp_limits limits = { | ||
| 576 | .vmax = 80, | ||
| 577 | .rapid_vmax = 100, | ||
| 578 | .amax = 800, | ||
| 579 | .jmax = 16000, | ||
| 580 | .corner_tol = .05, | ||
| 581 | // .corner_tol = 1, | ||
| 582 | .min_segment_len = 1e-6, | ||
| 583 | .default_feed = 50, | ||
| 584 | |||
| 585 | .straight_angle_tol = 0.02, | ||
| 586 | .stop_angle = M_PI/8, | ||
| 587 | .corner_speed_deadband = .002, | ||
| 588 | |||
| 589 | .curvature_blend_len = 0.05, | ||
| 590 | }; | ||
| 591 | |||
| 592 | cps = find_critical_points (&path); | ||
| 593 | uint32_t cpcs[5] = {0}; | ||
| 594 | for (uint32_t i = 0; i < cps.count; ++i) { | ||
| 595 | const struct critical_point *cp = &cps.items[i]; | ||
| 596 | cpcs[cp->type] += 1; | ||
| 597 | } | ||
| 598 | printf ("CPT_IN: %u\n", cpcs[CPT_IN]), | ||
| 599 | printf ("CPT_OUT: %u\n", cpcs[CPT_OUT]), | ||
| 600 | printf ("CPT_LOOP: %u\n", cpcs[CPT_LOOP]), | ||
| 601 | printf ("CPT_BEG: %u\n", cpcs[CPT_BEG]), | ||
| 602 | printf ("CPT_END: %u\n", cpcs[CPT_END]), | ||
| 603 | printf ("CPT_TOTAL: %u\n", cpcs[0] + cpcs[1] + cpcs[2] + cpcs[3] + cpcs[4]), | ||
| 604 | |||
| 605 | comps = synthesize_compensations (&cps); | ||
| 606 | |||
| 607 | struct motion_plan plan = {0}; | ||
| 608 | |||
| 609 | ASSERT (path.count > 0); | ||
| 610 | int rc = mp_plan_build (&path, initial_x, initial_y, &limits, &plan); | ||
| 611 | if (rc) { | ||
| 612 | printf ("%d\n", rc); | ||
| 613 | return 1; | ||
| 614 | } | ||
| 615 | // FILE *csv = fopen ("motion-plan.csv", "w"); | ||
| 616 | // mp_plan_write_csv (&plan, 0.001, csv, 1); | ||
| 617 | // fclose (csv); | ||
| 618 | // mp_plan_free(&plan); | ||
| 619 | |||
| 620 | printf ("total_length: %lg\n", plan.total_length); | ||
| 621 | printf ("total_time: %lg\n", plan.total_time); | ||
| 622 | printf ("v_min: %lg\n", plan.v_min); | ||
| 623 | printf ("v_max: %lg\n", plan.v_max); | ||
| 624 | printf ("a_min: %lg\n", plan.a_min); | ||
| 625 | printf ("a_max: %lg\n", plan.a_max); | ||
| 626 | printf ("j_min: %lg\n", plan.j_min); | ||
| 627 | printf ("j_max: %lg\n", plan.j_max); | ||
| 628 | |||
| 629 | struct work_motion_stats stats = measure_work_motion_stats (&path, &plan, 0.001); | ||
| 630 | |||
| 631 | printf ("work_active_time: %lg s\n", stats.active_time); | ||
| 632 | printf ("work_active_length: %lg mm\n", stats.active_length); | ||
| 633 | printf ("work_speed_error_max_abs: %lg mm/s\n", stats.speed_error_max_abs); | ||
| 634 | printf ("work_speed_error_mean_abs: %lg mm/s\n", stats.speed_error_mean_abs); | ||
| 635 | printf ("work_speed_error_rms: %lg mm/s\n", stats.speed_error_rms); | ||
| 636 | printf ("work_jerk_abs_integral: %lg mm/s^2\n", stats.jerk_abs_integral); | ||
| 637 | printf ("work_jerk_abs_mean: %lg mm/s^3\n", stats.jerk_abs_mean); | ||
| 638 | printf ("work_jerk_abs_max: %lg mm/s^3\n", stats.jerk_abs_max); | ||
| 639 | |||
| 640 | build_overlays (&plan); | ||
| 641 | visualize (); | ||
| 642 | |||
| 643 | return EXIT_SUCCESS; | ||
| 644 | } | ||
| 645 | |||
| 646 | /// src/simulate.h ends here | ||
diff --git a/src/skywrite.c b/src/skywrite.c new file mode 100644 index 0000000..196ac78 --- /dev/null +++ b/src/skywrite.c | |||
| @@ -0,0 +1,81 @@ | |||
| 1 | /// src/skywrite.h | ||
| 2 | // | ||
| 3 | // Copyright (C) 2026 by Martin Michalec <martin@michalec.dev> | ||
| 4 | // | ||
| 5 | // SPDX-License-Identifier: MIT | ||
| 6 | // | ||
| 7 | /// Commentary: | ||
| 8 | // | ||
| 9 | /// Code: | ||
| 10 | |||
| 11 | #include <stdlib.h> | ||
| 12 | #include <stdio.h> | ||
| 13 | #include <fcntl.h> | ||
| 14 | #include <unistd.h> | ||
| 15 | |||
| 16 | #include "utils.h" | ||
| 17 | #include "da.h" | ||
| 18 | #include "rs274ngc_lexer.h" | ||
| 19 | #include "rs274ngc_cst.h" | ||
| 20 | #include "path.h" | ||
| 21 | #include "critical_points.h" | ||
| 22 | #include "compensations.h" | ||
| 23 | #include "generator.h" | ||
| 24 | |||
| 25 | void | ||
| 26 | print_arena (const struct arena *a) | ||
| 27 | { | ||
| 28 | for (struct arena_chunk *ch = a->head; ch; ch = ch->next) | ||
| 29 | printf ("%p %lu\n", ch, (void *) ch - ch->begin); | ||
| 30 | } | ||
| 31 | |||
| 32 | void | ||
| 33 | print_path (struct path path) | ||
| 34 | { | ||
| 35 | DA_FOR_EACH (pe, path) { | ||
| 36 | printf ("%04b | %10.4lf | %10.4lf | %10.4lf | %10.4lf | %10.4lf | %.*s\n", | ||
| 37 | pe->flags, pe->x, pe->y, pe->f, pe->i, pe->j, SV_FMTA (pe->line)); | ||
| 38 | } | ||
| 39 | } | ||
| 40 | |||
| 41 | int | ||
| 42 | main (int argc, char *argv[]) | ||
| 43 | { | ||
| 44 | progname = argv[0]; | ||
| 45 | |||
| 46 | const char *filename; | ||
| 47 | int fd = 0; | ||
| 48 | if (argc == 1) { | ||
| 49 | filename = "-"; | ||
| 50 | } else if (argc == 2) { | ||
| 51 | filename = argv[1]; | ||
| 52 | fd = open (filename, O_RDONLY); | ||
| 53 | } else { | ||
| 54 | DIE ("too many arguments provided"); | ||
| 55 | } | ||
| 56 | |||
| 57 | struct arena a = {0}; | ||
| 58 | struct arena t = {0}; | ||
| 59 | |||
| 60 | struct sv rs274ngc = read_until_eof (&a, fd); | ||
| 61 | if (fd) close (fd); | ||
| 62 | |||
| 63 | rs274ngc_lexer_compile_regexes (); | ||
| 64 | struct rs274ngc_lexer lexer = rs274ngc_lexer_from_sv (rs274ngc, filename); | ||
| 65 | |||
| 66 | struct rs274ngc_cst_parser parser = { | ||
| 67 | .lexer = &lexer, | ||
| 68 | .output = &a, | ||
| 69 | .temporary = &t, | ||
| 70 | }; | ||
| 71 | |||
| 72 | struct path path = build_path (parser); | ||
| 73 | struct critical_points cps = find_critical_points (&path); | ||
| 74 | struct compensations comps = synthesize_compensations (&cps); | ||
| 75 | struct replacements reps = generate_replacements (&a, &comps); | ||
| 76 | write_code_with_replacements (0, rs274ngc, &reps); | ||
| 77 | |||
| 78 | return EXIT_SUCCESS; | ||
| 79 | } | ||
| 80 | |||
| 81 | /// src/skywrite.h ends here | ||
diff --git a/src/sv.h b/src/sv.h new file mode 100644 index 0000000..c01b0d1 --- /dev/null +++ b/src/sv.h | |||
| @@ -0,0 +1,26 @@ | |||
| 1 | /// src/sv.h --- simple String View library | ||
| 2 | // | ||
| 3 | // Copyright (C) 2026 by Martin Michalec <martin@michalec.dev> | ||
| 4 | // | ||
| 5 | // SPDX-License-Identifier: MIT | ||
| 6 | // | ||
| 7 | /// Commentary: | ||
| 8 | // | ||
| 9 | /// Code: | ||
| 10 | |||
| 11 | #ifndef INCLUDED_SV_H | ||
| 12 | #define INCLUDED_SV_H | ||
| 13 | |||
| 14 | #define SV_LENGTH(SV) ((SV).end - (SV).beg) | ||
| 15 | |||
| 16 | #define SV_FMT "%.*s" | ||
| 17 | #define SV_FMTA(SV) (int) SV_LENGTH (SV), (SV).beg | ||
| 18 | |||
| 19 | struct sv { | ||
| 20 | const char *beg; | ||
| 21 | const char *end; | ||
| 22 | }; | ||
| 23 | |||
| 24 | #endif // INCLUDED_SV_H | ||
| 25 | |||
| 26 | /// src/sv.h ends here | ||
diff --git a/src/transition.c b/src/transition.c new file mode 100644 index 0000000..9910b27 --- /dev/null +++ b/src/transition.c | |||
| @@ -0,0 +1,777 @@ | |||
| 1 | #include "transition.h" | ||
| 2 | |||
| 3 | #include <float.h> | ||
| 4 | #include <math.h> | ||
| 5 | #include <string.h> | ||
| 6 | |||
| 7 | #define TR_EPS 1e-10 | ||
| 8 | #define TR_TIME_EPS 1e-9 | ||
| 9 | #define TR_SOL_EPS 1e-8 | ||
| 10 | #define TR_MAX_SCAN 2048 | ||
| 11 | #define TR_MAX_BISECT 96 | ||
| 12 | #define TR_INF 1e100 | ||
| 13 | |||
| 14 | static double | ||
| 15 | tr_abs (double x) | ||
| 16 | { | ||
| 17 | return x < 0.0 ? -x : x; | ||
| 18 | } | ||
| 19 | |||
| 20 | static int | ||
| 21 | tr_finite_pos (double x) | ||
| 22 | { | ||
| 23 | return isfinite (x) && x > 0.0; | ||
| 24 | } | ||
| 25 | |||
| 26 | static double | ||
| 27 | tr_clamp (double x, double lo, double hi) | ||
| 28 | { | ||
| 29 | return x < lo ? lo : (x > hi ? hi : x); | ||
| 30 | } | ||
| 31 | |||
| 32 | static int | ||
| 33 | tr_limits_valid (double vmax, double amax, double jmax) | ||
| 34 | { | ||
| 35 | return tr_finite_pos (vmax) && tr_finite_pos (amax) && tr_finite_pos (jmax); | ||
| 36 | } | ||
| 37 | |||
| 38 | struct tr_axis_limits { | ||
| 39 | double vmax; | ||
| 40 | double amax; | ||
| 41 | double jmax; | ||
| 42 | }; | ||
| 43 | |||
| 44 | struct tr_change { | ||
| 45 | double dt; | ||
| 46 | double ds; | ||
| 47 | }; | ||
| 48 | |||
| 49 | static struct tr_change | ||
| 50 | tr_speed_change (double v0, double v1, const struct tr_axis_limits *l) | ||
| 51 | { | ||
| 52 | struct tr_change c = {0}; | ||
| 53 | double dv = tr_abs (v1 - v0); | ||
| 54 | |||
| 55 | if (dv <= TR_EPS) | ||
| 56 | return c; | ||
| 57 | |||
| 58 | double dv_tri = l->amax*l->amax/l->jmax; | ||
| 59 | |||
| 60 | if (dv <= dv_tri) { | ||
| 61 | double tj = sqrt (dv/l->jmax); | ||
| 62 | c.dt = 2.0*tj; | ||
| 63 | } else { | ||
| 64 | double tj = l->amax/l->jmax; | ||
| 65 | double ta = dv/l->amax - tj; | ||
| 66 | c.dt = 2.0*tj + ta; | ||
| 67 | } | ||
| 68 | |||
| 69 | c.ds = 0.5*(v0 + v1)*c.dt; | ||
| 70 | return c; | ||
| 71 | } | ||
| 72 | |||
| 73 | static double | ||
| 74 | tr_axis_fixed_f (double vm, | ||
| 75 | double q0, | ||
| 76 | double q1, | ||
| 77 | double v0, | ||
| 78 | double v1, | ||
| 79 | double T, | ||
| 80 | const struct tr_axis_limits *l, | ||
| 81 | int *admissible_out) | ||
| 82 | { | ||
| 83 | struct tr_change c0 = tr_speed_change (v0, vm, l); | ||
| 84 | struct tr_change c1 = tr_speed_change (vm, v1, l); | ||
| 85 | double tc = T - c0.dt - c1.dt; | ||
| 86 | |||
| 87 | if (admissible_out) | ||
| 88 | *admissible_out = tc >= -1e-8; | ||
| 89 | |||
| 90 | return c0.ds + c1.ds + vm*tc - (q1 - q0); | ||
| 91 | } | ||
| 92 | |||
| 93 | static int | ||
| 94 | tr_fixed_vm_candidate (double vm, | ||
| 95 | double q0, | ||
| 96 | double q1, | ||
| 97 | double v0, | ||
| 98 | double v1, | ||
| 99 | double T, | ||
| 100 | const struct tr_axis_limits *l, | ||
| 101 | double *err_out, | ||
| 102 | double *tc_out) | ||
| 103 | { | ||
| 104 | if (vm < -l->vmax - 1e-9 || vm > l->vmax + 1e-9) | ||
| 105 | return 0; | ||
| 106 | |||
| 107 | struct tr_change c0 = tr_speed_change (v0, vm, l); | ||
| 108 | struct tr_change c1 = tr_speed_change (vm, v1, l); | ||
| 109 | double tc = T - c0.dt - c1.dt; | ||
| 110 | if (tc < -1e-8) | ||
| 111 | return 0; | ||
| 112 | |||
| 113 | double q = c0.ds + c1.ds + vm*tc; | ||
| 114 | double err = q - (q1 - q0); | ||
| 115 | |||
| 116 | if (err_out) *err_out = err; | ||
| 117 | if (tc_out) *tc_out = tc > 0.0 ? tc : 0.0; | ||
| 118 | return 1; | ||
| 119 | } | ||
| 120 | |||
| 121 | static int | ||
| 122 | tr_find_fixed_vm (double q0, | ||
| 123 | double q1, | ||
| 124 | double v0, | ||
| 125 | double v1, | ||
| 126 | double T, | ||
| 127 | const struct tr_axis_limits *l, | ||
| 128 | double *vm_out, | ||
| 129 | double *tc_out) | ||
| 130 | { | ||
| 131 | double best_vm = 0.0; | ||
| 132 | double best_tc = 0.0; | ||
| 133 | double best_abs = TR_INF; | ||
| 134 | int found_exact = 0; | ||
| 135 | |||
| 136 | double prev_vm = 0.0; | ||
| 137 | double prev_f = 0.0; | ||
| 138 | int prev_ok = 0; | ||
| 139 | |||
| 140 | for (int i = 0; i <= TR_MAX_SCAN; ++i) { | ||
| 141 | double u = (double) i / (double) TR_MAX_SCAN; | ||
| 142 | double vm = -l->vmax + 2.0*l->vmax*u; | ||
| 143 | double f = 0.0; | ||
| 144 | double tc = 0.0; | ||
| 145 | int ok = tr_fixed_vm_candidate (vm, q0, q1, v0, v1, T, l, &f, &tc); | ||
| 146 | |||
| 147 | if (ok) { | ||
| 148 | double af = tr_abs (f); | ||
| 149 | if (af < best_abs) { | ||
| 150 | best_abs = af; | ||
| 151 | best_vm = vm; | ||
| 152 | best_tc = tc; | ||
| 153 | } | ||
| 154 | |||
| 155 | if (af <= TR_SOL_EPS*fmax (1.0, tr_abs (q1 - q0))) { | ||
| 156 | *vm_out = vm; | ||
| 157 | *tc_out = tc; | ||
| 158 | return 1; | ||
| 159 | } | ||
| 160 | |||
| 161 | if (prev_ok && ((prev_f <= 0.0 && f >= 0.0) || (prev_f >= 0.0 && f <= 0.0))) { | ||
| 162 | double lo = prev_vm; | ||
| 163 | double hi = vm; | ||
| 164 | double flo = prev_f; | ||
| 165 | double fhi = f; | ||
| 166 | |||
| 167 | for (int k = 0; k < TR_MAX_BISECT; ++k) { | ||
| 168 | double mid = 0.5*(lo + hi); | ||
| 169 | int adm = 0; | ||
| 170 | double fm = tr_axis_fixed_f (mid, q0, q1, v0, v1, T, l, &adm); | ||
| 171 | if (!adm) { | ||
| 172 | /* This should not normally happen inside an admissible bracket. */ | ||
| 173 | break; | ||
| 174 | } | ||
| 175 | |||
| 176 | if (tr_abs (fm) <= TR_SOL_EPS*fmax (1.0, tr_abs (q1 - q0))) { | ||
| 177 | double ignored_err = 0.0; | ||
| 178 | tr_fixed_vm_candidate (mid, q0, q1, v0, v1, T, l, &ignored_err, &tc); | ||
| 179 | *vm_out = mid; | ||
| 180 | *tc_out = tc; | ||
| 181 | return 1; | ||
| 182 | } | ||
| 183 | |||
| 184 | if ((flo <= 0.0 && fm >= 0.0) || (flo >= 0.0 && fm <= 0.0)) { | ||
| 185 | hi = mid; | ||
| 186 | fhi = fm; | ||
| 187 | } else { | ||
| 188 | lo = mid; | ||
| 189 | flo = fm; | ||
| 190 | } | ||
| 191 | (void) fhi; | ||
| 192 | } | ||
| 193 | |||
| 194 | double mid = 0.5*(lo + hi); | ||
| 195 | double ignored_err = 0.0; | ||
| 196 | tr_fixed_vm_candidate (mid, q0, q1, v0, v1, T, l, &ignored_err, &tc); | ||
| 197 | *vm_out = mid; | ||
| 198 | *tc_out = tc; | ||
| 199 | return 1; | ||
| 200 | } | ||
| 201 | } | ||
| 202 | |||
| 203 | prev_vm = vm; | ||
| 204 | prev_f = f; | ||
| 205 | prev_ok = ok; | ||
| 206 | } | ||
| 207 | |||
| 208 | if (best_abs <= 1e-6*fmax (1.0, tr_abs (q1 - q0))) { | ||
| 209 | *vm_out = best_vm; | ||
| 210 | *tc_out = best_tc; | ||
| 211 | found_exact = 1; | ||
| 212 | } | ||
| 213 | |||
| 214 | return found_exact; | ||
| 215 | } | ||
| 216 | |||
| 217 | static int | ||
| 218 | tr_axis_feasible_at (double q0, | ||
| 219 | double q1, | ||
| 220 | double v0, | ||
| 221 | double v1, | ||
| 222 | double T, | ||
| 223 | const struct tr_axis_limits *l) | ||
| 224 | { | ||
| 225 | double vm, tc; | ||
| 226 | return tr_find_fixed_vm (q0, q1, v0, v1, T, l, &vm, &tc); | ||
| 227 | } | ||
| 228 | |||
| 229 | static int | ||
| 230 | tr_axis_min_duration (double q0, | ||
| 231 | double q1, | ||
| 232 | double v0, | ||
| 233 | double v1, | ||
| 234 | const struct tr_axis_limits *l, | ||
| 235 | double *T_out) | ||
| 236 | { | ||
| 237 | if (tr_abs (v0) > l->vmax + 1e-8 || tr_abs (v1) > l->vmax + 1e-8) | ||
| 238 | return TR_ERR_INFEASIBLE; | ||
| 239 | |||
| 240 | double lo = 0.0; | ||
| 241 | double hi = 1e-9; | ||
| 242 | |||
| 243 | /* Lower bound must at least allow the velocity change through some vm. */ | ||
| 244 | struct tr_change direct = tr_speed_change (v0, v1, l); | ||
| 245 | lo = 0.0; | ||
| 246 | hi = fmax (direct.dt, 1e-6); | ||
| 247 | |||
| 248 | while (!tr_axis_feasible_at (q0, q1, v0, v1, hi, l)) { | ||
| 249 | hi *= 2.0; | ||
| 250 | if (!(hi < 1e9) || !isfinite (hi)) | ||
| 251 | return TR_ERR_NO_PROFILE; | ||
| 252 | } | ||
| 253 | |||
| 254 | for (int k = 0; k < TR_MAX_BISECT; ++k) { | ||
| 255 | double mid = 0.5*(lo + hi); | ||
| 256 | if (tr_axis_feasible_at (q0, q1, v0, v1, mid, l)) | ||
| 257 | hi = mid; | ||
| 258 | else | ||
| 259 | lo = mid; | ||
| 260 | } | ||
| 261 | |||
| 262 | *T_out = hi; | ||
| 263 | return TR_OK; | ||
| 264 | } | ||
| 265 | |||
| 266 | static int | ||
| 267 | tr_axis_push_phase (struct tr_axis_plan *p, | ||
| 268 | double dt, | ||
| 269 | double j, | ||
| 270 | double *q, | ||
| 271 | double *v, | ||
| 272 | double *a, | ||
| 273 | double *t) | ||
| 274 | { | ||
| 275 | if (dt <= 1e-10) | ||
| 276 | return TR_OK; | ||
| 277 | |||
| 278 | if (p->count >= (uint32_t) (sizeof p->phases / sizeof p->phases[0])) | ||
| 279 | return TR_ERR_NUMERIC; | ||
| 280 | |||
| 281 | struct tr_axis_phase *ph = &p->phases[p->count++]; | ||
| 282 | ph->t_begin = *t; | ||
| 283 | ph->dt = dt; | ||
| 284 | ph->q0 = *q; | ||
| 285 | ph->v0 = *v; | ||
| 286 | ph->a0 = *a; | ||
| 287 | ph->j = j; | ||
| 288 | |||
| 289 | double dt2 = dt*dt; | ||
| 290 | double dt3 = dt2*dt; | ||
| 291 | *q = *q + (*v)*dt + 0.5*(*a)*dt2 + (j*dt3)/6.0; | ||
| 292 | *v = *v + (*a)*dt + 0.5*j*dt2; | ||
| 293 | *a = *a + j*dt; | ||
| 294 | *t = *t + dt; | ||
| 295 | return TR_OK; | ||
| 296 | } | ||
| 297 | |||
| 298 | static int | ||
| 299 | tr_axis_append_speed_change (struct tr_axis_plan *p, | ||
| 300 | double v_to, | ||
| 301 | const struct tr_axis_limits *l, | ||
| 302 | double *q, | ||
| 303 | double *v, | ||
| 304 | double *a, | ||
| 305 | double *t) | ||
| 306 | { | ||
| 307 | double dv = v_to - *v; | ||
| 308 | double adv = tr_abs (dv); | ||
| 309 | if (adv <= 1e-10) { | ||
| 310 | *v = v_to; | ||
| 311 | *a = 0.0; | ||
| 312 | return TR_OK; | ||
| 313 | } | ||
| 314 | |||
| 315 | double sgn = dv >= 0.0 ? 1.0 : -1.0; | ||
| 316 | double dv_tri = l->amax*l->amax/l->jmax; | ||
| 317 | |||
| 318 | if (adv <= dv_tri) { | ||
| 319 | double tj = sqrt (adv/l->jmax); | ||
| 320 | int rc = tr_axis_push_phase (p, tj, sgn*l->jmax, q, v, a, t); | ||
| 321 | if (rc != TR_OK) return rc; | ||
| 322 | rc = tr_axis_push_phase (p, tj, -sgn*l->jmax, q, v, a, t); | ||
| 323 | if (rc != TR_OK) return rc; | ||
| 324 | } else { | ||
| 325 | double tj = l->amax/l->jmax; | ||
| 326 | double ta = adv/l->amax - tj; | ||
| 327 | int rc = tr_axis_push_phase (p, tj, sgn*l->jmax, q, v, a, t); | ||
| 328 | if (rc != TR_OK) return rc; | ||
| 329 | rc = tr_axis_push_phase (p, ta, 0.0, q, v, a, t); | ||
| 330 | if (rc != TR_OK) return rc; | ||
| 331 | rc = tr_axis_push_phase (p, tj, -sgn*l->jmax, q, v, a, t); | ||
| 332 | if (rc != TR_OK) return rc; | ||
| 333 | } | ||
| 334 | |||
| 335 | *v = v_to; | ||
| 336 | *a = 0.0; | ||
| 337 | return TR_OK; | ||
| 338 | } | ||
| 339 | |||
| 340 | static int | ||
| 341 | tr_axis_build_fixed (struct tr_axis_plan *out, | ||
| 342 | double q0, | ||
| 343 | double q1, | ||
| 344 | double v0, | ||
| 345 | double v1, | ||
| 346 | double T, | ||
| 347 | const struct tr_axis_limits *l) | ||
| 348 | { | ||
| 349 | if (tr_abs (v0) > l->vmax + 1e-8 || tr_abs (v1) > l->vmax + 1e-8) | ||
| 350 | return TR_ERR_INFEASIBLE; | ||
| 351 | |||
| 352 | double vm = 0.0; | ||
| 353 | double tc = 0.0; | ||
| 354 | if (!tr_find_fixed_vm (q0, q1, v0, v1, T, l, &vm, &tc)) | ||
| 355 | return TR_ERR_NO_PROFILE; | ||
| 356 | |||
| 357 | memset (out, 0, sizeof *out); | ||
| 358 | out->duration = T; | ||
| 359 | out->q0 = q0; | ||
| 360 | out->q1 = q1; | ||
| 361 | out->v0 = v0; | ||
| 362 | out->v1 = v1; | ||
| 363 | |||
| 364 | double q = q0; | ||
| 365 | double v = v0; | ||
| 366 | double a = 0.0; | ||
| 367 | double t = 0.0; | ||
| 368 | |||
| 369 | int rc = tr_axis_append_speed_change (out, vm, l, &q, &v, &a, &t); | ||
| 370 | if (rc != TR_OK) return rc; | ||
| 371 | |||
| 372 | rc = tr_axis_push_phase (out, tc, 0.0, &q, &v, &a, &t); | ||
| 373 | if (rc != TR_OK) return rc; | ||
| 374 | |||
| 375 | rc = tr_axis_append_speed_change (out, v1, l, &q, &v, &a, &t); | ||
| 376 | if (rc != TR_OK) return rc; | ||
| 377 | |||
| 378 | /* Clamp accumulated numerical error at the boundary. */ | ||
| 379 | if (out->count > 0u) { | ||
| 380 | out->duration = T; | ||
| 381 | } | ||
| 382 | |||
| 383 | if (tr_abs (t - T) > 2e-6*fmax (1.0, T)) | ||
| 384 | return TR_ERR_NUMERIC; | ||
| 385 | if (tr_abs (q - q1) > 2e-5*fmax (1.0, tr_abs (q1 - q0))) | ||
| 386 | return TR_ERR_NUMERIC; | ||
| 387 | if (tr_abs (v - v1) > 2e-6*fmax (1.0, tr_abs (v1))) | ||
| 388 | return TR_ERR_NUMERIC; | ||
| 389 | if (tr_abs (a) > 2e-6*fmax (1.0, l->amax)) | ||
| 390 | return TR_ERR_NUMERIC; | ||
| 391 | |||
| 392 | return TR_OK; | ||
| 393 | } | ||
| 394 | |||
| 395 | static void | ||
| 396 | tr_axis_eval (const struct tr_axis_plan *p, | ||
| 397 | double t, | ||
| 398 | double *q_out, | ||
| 399 | double *v_out, | ||
| 400 | double *a_out, | ||
| 401 | double *j_out) | ||
| 402 | { | ||
| 403 | if (!p || p->count == 0u) { | ||
| 404 | if (q_out) *q_out = p ? p->q0 : 0.0; | ||
| 405 | if (v_out) *v_out = p ? p->v0 : 0.0; | ||
| 406 | if (a_out) *a_out = 0.0; | ||
| 407 | if (j_out) *j_out = 0.0; | ||
| 408 | return; | ||
| 409 | } | ||
| 410 | |||
| 411 | if (t <= 0.0) { | ||
| 412 | if (q_out) *q_out = p->q0; | ||
| 413 | if (v_out) *v_out = p->v0; | ||
| 414 | if (a_out) *a_out = 0.0; | ||
| 415 | if (j_out) *j_out = 0.0; | ||
| 416 | return; | ||
| 417 | } | ||
| 418 | |||
| 419 | if (t >= p->duration) { | ||
| 420 | if (q_out) *q_out = p->q1; | ||
| 421 | if (v_out) *v_out = p->v1; | ||
| 422 | if (a_out) *a_out = 0.0; | ||
| 423 | if (j_out) *j_out = 0.0; | ||
| 424 | return; | ||
| 425 | } | ||
| 426 | |||
| 427 | const struct tr_axis_phase *ph = &p->phases[p->count - 1u]; | ||
| 428 | for (uint32_t i = 0; i < p->count; ++i) { | ||
| 429 | const struct tr_axis_phase *cand = &p->phases[i]; | ||
| 430 | if (t < cand->t_begin + cand->dt + 1e-12) { | ||
| 431 | ph = cand; | ||
| 432 | break; | ||
| 433 | } | ||
| 434 | } | ||
| 435 | |||
| 436 | double tau = tr_clamp (t - ph->t_begin, 0.0, ph->dt); | ||
| 437 | double tau2 = tau*tau; | ||
| 438 | double tau3 = tau2*tau; | ||
| 439 | |||
| 440 | if (q_out) *q_out = ph->q0 + ph->v0*tau + 0.5*ph->a0*tau2 + (ph->j*tau3)/6.0; | ||
| 441 | if (v_out) *v_out = ph->v0 + ph->a0*tau + 0.5*ph->j*tau2; | ||
| 442 | if (a_out) *a_out = ph->a0 + ph->j*tau; | ||
| 443 | if (j_out) *j_out = ph->j; | ||
| 444 | } | ||
| 445 | |||
| 446 | |||
| 447 | static double | ||
| 448 | tr_speed_at_time (const struct tr_transition *tr, double t) | ||
| 449 | { | ||
| 450 | double vx = 0.0; | ||
| 451 | double vy = 0.0; | ||
| 452 | |||
| 453 | tr_axis_eval (&tr->x, t, NULL, &vx, NULL, NULL); | ||
| 454 | tr_axis_eval (&tr->y, t, NULL, &vy, NULL, NULL); | ||
| 455 | |||
| 456 | return hypot (vx, vy); | ||
| 457 | } | ||
| 458 | |||
| 459 | static double | ||
| 460 | tr_integrate_speed (const struct tr_transition *tr, double t0, double t1) | ||
| 461 | { | ||
| 462 | if (!tr || !(t1 > t0)) | ||
| 463 | return 0.0; | ||
| 464 | |||
| 465 | /* 16-point Gauss-Legendre rule on [t0, t1]. On every joint phase interval | ||
| 466 | * vx(t) and vy(t) are quadratic polynomials, so the integrand is smooth. | ||
| 467 | */ | ||
| 468 | static const double x[8] = { | ||
| 469 | 0.095012509837637440185, | ||
| 470 | 0.281603550779258913230, | ||
| 471 | 0.458016777657227386342, | ||
| 472 | 0.617876244402643748447, | ||
| 473 | 0.755404408355003033895, | ||
| 474 | 0.865631202387831743880, | ||
| 475 | 0.944575023073232576078, | ||
| 476 | 0.989400934991649932596 | ||
| 477 | }; | ||
| 478 | static const double w[8] = { | ||
| 479 | 0.189450610455068496285, | ||
| 480 | 0.182603415044923588867, | ||
| 481 | 0.169156519395002538189, | ||
| 482 | 0.149595988816576732081, | ||
| 483 | 0.124628971255533872052, | ||
| 484 | 0.095158511682492784810, | ||
| 485 | 0.062253523938647892863, | ||
| 486 | 0.027152459411754094852 | ||
| 487 | }; | ||
| 488 | |||
| 489 | double c = 0.5*(t0 + t1); | ||
| 490 | double h = 0.5*(t1 - t0); | ||
| 491 | double sum = 0.0; | ||
| 492 | |||
| 493 | for (int i = 0; i < 8; ++i) { | ||
| 494 | double dx = h*x[i]; | ||
| 495 | sum += w[i] * (tr_speed_at_time (tr, c - dx) + | ||
| 496 | tr_speed_at_time (tr, c + dx)); | ||
| 497 | } | ||
| 498 | |||
| 499 | return h*sum; | ||
| 500 | } | ||
| 501 | |||
| 502 | static double | ||
| 503 | tr_lookup_time_in_dense_table (const double *ts, | ||
| 504 | const double *ss, | ||
| 505 | uint32_t n, | ||
| 506 | double s) | ||
| 507 | { | ||
| 508 | if (!ts || !ss || n == 0u) | ||
| 509 | return 0.0; | ||
| 510 | |||
| 511 | if (s <= ss[0]) | ||
| 512 | return ts[0]; | ||
| 513 | if (s >= ss[n - 1u]) | ||
| 514 | return ts[n - 1u]; | ||
| 515 | |||
| 516 | uint32_t lo = 0u; | ||
| 517 | uint32_t hi = n - 1u; | ||
| 518 | |||
| 519 | while (lo + 1u < hi) { | ||
| 520 | uint32_t mid = lo + (hi - lo)/2u; | ||
| 521 | if (ss[mid] <= s) | ||
| 522 | lo = mid; | ||
| 523 | else | ||
| 524 | hi = mid; | ||
| 525 | } | ||
| 526 | |||
| 527 | double s0 = ss[lo]; | ||
| 528 | double s1 = ss[hi]; | ||
| 529 | double t0 = ts[lo]; | ||
| 530 | double t1 = ts[hi]; | ||
| 531 | |||
| 532 | if (!(s1 > s0)) | ||
| 533 | return t0; | ||
| 534 | |||
| 535 | double u = (s - s0)/(s1 - s0); | ||
| 536 | return t0 + u*(t1 - t0); | ||
| 537 | } | ||
| 538 | |||
| 539 | static int | ||
| 540 | tr_build_s_table (struct tr_transition *tr) | ||
| 541 | { | ||
| 542 | if (!tr) | ||
| 543 | return TR_ERR_INVALID_ARG; | ||
| 544 | |||
| 545 | tr->length = 0.0; | ||
| 546 | tr->s_node_count = 0u; | ||
| 547 | tr->s_step = 0.0; | ||
| 548 | |||
| 549 | if (!(tr->duration > 0.0) || !isfinite (tr->duration)) { | ||
| 550 | tr->s_node_count = 1u; | ||
| 551 | tr->s_nodes[0].s = 0.0; | ||
| 552 | tr->s_nodes[0].t = 0.0; | ||
| 553 | return TR_OK; | ||
| 554 | } | ||
| 555 | |||
| 556 | /* First build a dense cumulative table in time. This is done once at build | ||
| 557 | * time. Runtime sampling by s does not integrate and does not bisect with | ||
| 558 | * quadrature anymore. | ||
| 559 | */ | ||
| 560 | double ts[TR_S_TABLE_CAP]; | ||
| 561 | double ss[TR_S_TABLE_CAP]; | ||
| 562 | const uint32_t n = TR_S_TABLE_CAP; | ||
| 563 | |||
| 564 | ts[0] = 0.0; | ||
| 565 | ss[0] = 0.0; | ||
| 566 | |||
| 567 | double s_acc = 0.0; | ||
| 568 | double t_prev = 0.0; | ||
| 569 | |||
| 570 | for (uint32_t i = 1u; i < n; ++i) { | ||
| 571 | double t = tr->duration * ((double) i / (double) (n - 1u)); | ||
| 572 | double ds = tr_integrate_speed (tr, t_prev, t); | ||
| 573 | |||
| 574 | if (!isfinite (ds) || ds < -1e-9) | ||
| 575 | return TR_ERR_NUMERIC; | ||
| 576 | |||
| 577 | if (ds < 0.0) | ||
| 578 | ds = 0.0; | ||
| 579 | |||
| 580 | s_acc += ds; | ||
| 581 | ts[i] = t; | ||
| 582 | ss[i] = s_acc; | ||
| 583 | t_prev = t; | ||
| 584 | } | ||
| 585 | |||
| 586 | tr->length = s_acc; | ||
| 587 | |||
| 588 | if (!(tr->length > 0.0) || !isfinite (tr->length)) { | ||
| 589 | tr->s_node_count = 1u; | ||
| 590 | tr->s_step = 0.0; | ||
| 591 | tr->s_nodes[0].s = 0.0; | ||
| 592 | tr->s_nodes[0].t = 0.0; | ||
| 593 | return TR_OK; | ||
| 594 | } | ||
| 595 | |||
| 596 | tr->s_node_count = n; | ||
| 597 | tr->s_step = tr->length / (double) (n - 1u); | ||
| 598 | |||
| 599 | for (uint32_t i = 0u; i < n; ++i) { | ||
| 600 | double s_target = tr->s_step * (double) i; | ||
| 601 | if (i + 1u == n) | ||
| 602 | s_target = tr->length; | ||
| 603 | |||
| 604 | tr->s_nodes[i].s = s_target; | ||
| 605 | tr->s_nodes[i].t = tr_lookup_time_in_dense_table (ts, ss, n, s_target); | ||
| 606 | } | ||
| 607 | |||
| 608 | tr->s_nodes[0].s = 0.0; | ||
| 609 | tr->s_nodes[0].t = 0.0; | ||
| 610 | tr->s_nodes[n - 1u].s = tr->length; | ||
| 611 | tr->s_nodes[n - 1u].t = tr->duration; | ||
| 612 | |||
| 613 | return TR_OK; | ||
| 614 | } | ||
| 615 | |||
| 616 | double | ||
| 617 | tr_length_at_time (const struct tr_transition *tr, double t) | ||
| 618 | { | ||
| 619 | if (!tr || tr->s_node_count == 0u) | ||
| 620 | return 0.0; | ||
| 621 | |||
| 622 | if (tr->length <= 0.0) | ||
| 623 | return 0.0; | ||
| 624 | |||
| 625 | t = tr_clamp (t, 0.0, tr->duration); | ||
| 626 | |||
| 627 | if (t <= 0.0) | ||
| 628 | return 0.0; | ||
| 629 | if (t >= tr->duration) | ||
| 630 | return tr->length; | ||
| 631 | |||
| 632 | uint32_t lo = 0u; | ||
| 633 | uint32_t hi = tr->s_node_count - 1u; | ||
| 634 | |||
| 635 | while (lo + 1u < hi) { | ||
| 636 | uint32_t mid = lo + (hi - lo)/2u; | ||
| 637 | if (tr->s_nodes[mid].t <= t) | ||
| 638 | lo = mid; | ||
| 639 | else | ||
| 640 | hi = mid; | ||
| 641 | } | ||
| 642 | |||
| 643 | const struct tr_s_node *a = &tr->s_nodes[lo]; | ||
| 644 | const struct tr_s_node *b = &tr->s_nodes[hi]; | ||
| 645 | |||
| 646 | if (!(b->t > a->t)) | ||
| 647 | return a->s; | ||
| 648 | |||
| 649 | double u = (t - a->t)/(b->t - a->t); | ||
| 650 | return tr_clamp (a->s + u*(b->s - a->s), 0.0, tr->length); | ||
| 651 | } | ||
| 652 | |||
| 653 | double | ||
| 654 | tr_time_at_length (const struct tr_transition *tr, double s) | ||
| 655 | { | ||
| 656 | if (!tr || tr->s_node_count == 0u) | ||
| 657 | return 0.0; | ||
| 658 | |||
| 659 | if (tr->length <= 0.0) | ||
| 660 | return 0.0; | ||
| 661 | |||
| 662 | s = tr_clamp (s, 0.0, tr->length); | ||
| 663 | |||
| 664 | if (s <= 0.0) | ||
| 665 | return 0.0; | ||
| 666 | if (s >= tr->length) | ||
| 667 | return tr->duration; | ||
| 668 | |||
| 669 | /* The table is uniform by arclength, so the common path is O(1). */ | ||
| 670 | double u = s / tr->s_step; | ||
| 671 | uint32_t i = (uint32_t) floor (u); | ||
| 672 | |||
| 673 | if (i + 1u >= tr->s_node_count) | ||
| 674 | return tr->duration; | ||
| 675 | |||
| 676 | double f = u - (double) i; | ||
| 677 | const struct tr_s_node *a = &tr->s_nodes[i]; | ||
| 678 | const struct tr_s_node *b = &tr->s_nodes[i + 1u]; | ||
| 679 | |||
| 680 | return a->t + f*(b->t - a->t); | ||
| 681 | } | ||
| 682 | |||
| 683 | void | ||
| 684 | tr_sample_at_s (const struct tr_transition *tr, double s, struct tr_sample *out) | ||
| 685 | { | ||
| 686 | if (!out) | ||
| 687 | return; | ||
| 688 | |||
| 689 | memset (out, 0, sizeof *out); | ||
| 690 | if (!tr) | ||
| 691 | return; | ||
| 692 | |||
| 693 | double s_clamped = tr_clamp (s, 0.0, tr->length); | ||
| 694 | double t = tr_time_at_length (tr, s_clamped); | ||
| 695 | tr_sample (tr, t, out); | ||
| 696 | out->s = s_clamped; | ||
| 697 | } | ||
| 698 | |||
| 699 | int | ||
| 700 | tr_build (struct tr_transition *out, | ||
| 701 | struct vec2 r0, | ||
| 702 | struct vec2 r1, | ||
| 703 | struct vec2 v0, | ||
| 704 | struct vec2 v1, | ||
| 705 | double vmax, | ||
| 706 | double amax, | ||
| 707 | double jmax) | ||
| 708 | { | ||
| 709 | if (!out) | ||
| 710 | return TR_ERR_INVALID_ARG; | ||
| 711 | if (!tr_limits_valid (vmax, amax, jmax)) | ||
| 712 | return TR_ERR_LIMITS; | ||
| 713 | |||
| 714 | memset (out, 0, sizeof *out); | ||
| 715 | out->vmax = vmax; | ||
| 716 | out->amax = amax; | ||
| 717 | out->jmax = jmax; | ||
| 718 | |||
| 719 | struct tr_axis_limits lim = { vmax, amax, jmax }; | ||
| 720 | |||
| 721 | double tx = 0.0; | ||
| 722 | double ty = 0.0; | ||
| 723 | int rc = tr_axis_min_duration (r0.x, r1.x, v0.x, v1.x, &lim, &tx); | ||
| 724 | if (rc != TR_OK) return rc; | ||
| 725 | rc = tr_axis_min_duration (r0.y, r1.y, v0.y, v1.y, &lim, &ty); | ||
| 726 | if (rc != TR_OK) return rc; | ||
| 727 | |||
| 728 | double T = fmax (tx, ty); | ||
| 729 | |||
| 730 | /* Add a tiny numerical margin so the shorter axis can be reconstructed at T. */ | ||
| 731 | T += 1e-8*fmax (1.0, T); | ||
| 732 | |||
| 733 | rc = tr_axis_build_fixed (&out->x, r0.x, r1.x, v0.x, v1.x, T, &lim); | ||
| 734 | if (rc != TR_OK) return rc; | ||
| 735 | rc = tr_axis_build_fixed (&out->y, r0.y, r1.y, v0.y, v1.y, T, &lim); | ||
| 736 | if (rc != TR_OK) return rc; | ||
| 737 | |||
| 738 | out->duration = T; | ||
| 739 | |||
| 740 | rc = tr_build_s_table (out); | ||
| 741 | if (rc != TR_OK) | ||
| 742 | return rc; | ||
| 743 | |||
| 744 | return TR_OK; | ||
| 745 | } | ||
| 746 | |||
| 747 | void | ||
| 748 | tr_sample (const struct tr_transition *tr, double t, struct tr_sample *out) | ||
| 749 | { | ||
| 750 | if (!out) | ||
| 751 | return; | ||
| 752 | |||
| 753 | memset (out, 0, sizeof *out); | ||
| 754 | if (!tr) | ||
| 755 | return; | ||
| 756 | |||
| 757 | t = tr_clamp (t, 0.0, tr->duration); | ||
| 758 | out->t = t; | ||
| 759 | out->s = tr_length_at_time (tr, t); | ||
| 760 | |||
| 761 | tr_axis_eval (&tr->x, t, &out->r.x, &out->v.x, &out->a.x, &out->j.x); | ||
| 762 | tr_axis_eval (&tr->y, t, &out->r.y, &out->v.y, &out->a.y, &out->j.y); | ||
| 763 | } | ||
| 764 | |||
| 765 | const char * | ||
| 766 | tr_status_string (int status) | ||
| 767 | { | ||
| 768 | switch (status) { | ||
| 769 | case TR_OK: return "ok"; | ||
| 770 | case TR_ERR_INVALID_ARG: return "invalid argument"; | ||
| 771 | case TR_ERR_LIMITS: return "invalid limits"; | ||
| 772 | case TR_ERR_INFEASIBLE: return "infeasible boundary state"; | ||
| 773 | case TR_ERR_NUMERIC: return "numeric failure"; | ||
| 774 | case TR_ERR_NO_PROFILE: return "no transition profile found"; | ||
| 775 | default: return "unknown transition status"; | ||
| 776 | } | ||
| 777 | } | ||
diff --git a/src/transition.h b/src/transition.h new file mode 100644 index 0000000..70b3ae9 --- /dev/null +++ b/src/transition.h | |||
| @@ -0,0 +1,106 @@ | |||
| 1 | #ifndef INCLUDED_TRANSITION_V3_SPARAM_H | ||
| 2 | #define INCLUDED_TRANSITION_V3_SPARAM_H | ||
| 3 | |||
| 4 | #include <stdint.h> | ||
| 5 | #include "vec2.h" | ||
| 6 | |||
| 7 | /* | ||
| 8 | * Time-optimal jerk-limited transition for independent X/Y axes. | ||
| 9 | * | ||
| 10 | * The planner treats X and Y as independent 1D axes with identical symmetric | ||
| 11 | * limits for both directions: | ||
| 12 | * |v_axis| <= vmax, |a_axis| <= amax, |j_axis| <= jmax. | ||
| 13 | * | ||
| 14 | * Boundary acceleration is fixed to zero on both axes. Jerk is a bounded | ||
| 15 | * control, not a state; tr_sample() reports j=0 outside the motion interval, | ||
| 16 | * but the time-optimal profile may jump from 0 to +/-jmax at t=0 and jump back | ||
| 17 | * to 0 at t=T. If continuous jerk is required, the problem is snap-limited, | ||
| 18 | * not jerk-limited. | ||
| 19 | * | ||
| 20 | * The transition can be sampled either by time t or by travelled arclength s. | ||
| 21 | * Arclength is computed as | ||
| 22 | * s(t) = integral_0^t hypot(vx(tau), vy(tau)) d tau. | ||
| 23 | * | ||
| 24 | * For fast repeated sampling by s, tr_transition stores an internal monotone | ||
| 25 | * lookup table parameterized by arclength. The dynamic profile is still stored | ||
| 26 | * as time-polynomial axis phases; the s-table only maps s -> t. | ||
| 27 | */ | ||
| 28 | |||
| 29 | #define TR_S_TABLE_CAP 2049u | ||
| 30 | |||
| 31 | #define TR_S_PARAM_TABLE_UNIFORM_BY_LENGTH 1 | ||
| 32 | |||
| 33 | enum tr_status { | ||
| 34 | TR_OK = 0, | ||
| 35 | TR_ERR_INVALID_ARG = -1, | ||
| 36 | TR_ERR_LIMITS = -2, | ||
| 37 | TR_ERR_INFEASIBLE = -3, | ||
| 38 | TR_ERR_NUMERIC = -4, | ||
| 39 | TR_ERR_NO_PROFILE = -5 | ||
| 40 | }; | ||
| 41 | |||
| 42 | struct tr_axis_phase { | ||
| 43 | double t_begin; | ||
| 44 | double dt; | ||
| 45 | double q0; | ||
| 46 | double v0; | ||
| 47 | double a0; | ||
| 48 | double j; | ||
| 49 | }; | ||
| 50 | |||
| 51 | struct tr_axis_plan { | ||
| 52 | struct tr_axis_phase phases[16]; | ||
| 53 | uint32_t count; | ||
| 54 | double duration; | ||
| 55 | double q0, q1; | ||
| 56 | double v0, v1; | ||
| 57 | }; | ||
| 58 | |||
| 59 | struct tr_s_node { | ||
| 60 | double s; | ||
| 61 | double t; | ||
| 62 | }; | ||
| 63 | |||
| 64 | struct tr_transition { | ||
| 65 | struct tr_axis_plan x; | ||
| 66 | struct tr_axis_plan y; | ||
| 67 | double duration; | ||
| 68 | double length; | ||
| 69 | |||
| 70 | /* Uniform arclength parameterization: s_nodes[i].s is approximately | ||
| 71 | * i*length/(s_node_count-1), and s_nodes[i].t is the corresponding time. | ||
| 72 | */ | ||
| 73 | uint32_t s_node_count; | ||
| 74 | double s_step; | ||
| 75 | struct tr_s_node s_nodes[TR_S_TABLE_CAP]; | ||
| 76 | |||
| 77 | double vmax, amax, jmax; | ||
| 78 | }; | ||
| 79 | |||
| 80 | struct tr_sample { | ||
| 81 | double t; | ||
| 82 | double s; | ||
| 83 | struct vec2 r; | ||
| 84 | struct vec2 v; | ||
| 85 | struct vec2 a; | ||
| 86 | struct vec2 j; | ||
| 87 | }; | ||
| 88 | |||
| 89 | int tr_build (struct tr_transition *out, | ||
| 90 | struct vec2 r0, | ||
| 91 | struct vec2 r1, | ||
| 92 | struct vec2 v0, | ||
| 93 | struct vec2 v1, | ||
| 94 | double vmax, | ||
| 95 | double amax, | ||
| 96 | double jmax); | ||
| 97 | |||
| 98 | void tr_sample (const struct tr_transition *tr, double t, struct tr_sample *out); | ||
| 99 | void tr_sample_at_s (const struct tr_transition *tr, double s, struct tr_sample *out); | ||
| 100 | |||
| 101 | double tr_length_at_time (const struct tr_transition *tr, double t); | ||
| 102 | double tr_time_at_length (const struct tr_transition *tr, double s); | ||
| 103 | |||
| 104 | const char *tr_status_string (int status); | ||
| 105 | |||
| 106 | #endif /* INCLUDED_TRANSITION_V3_SPARAM_H */ | ||
diff --git a/src/utils.c b/src/utils.c new file mode 100644 index 0000000..67d0a84 --- /dev/null +++ b/src/utils.c | |||
| @@ -0,0 +1,135 @@ | |||
| 1 | // src/utils.c | ||
| 2 | #include <stddef.h> | ||
| 3 | #include <stdarg.h> | ||
| 4 | #include <unistd.h> | ||
| 5 | #include <sys/stat.h> | ||
| 6 | #include <sys/mman.h> | ||
| 7 | #include <string.h> | ||
| 8 | #include <errno.h> | ||
| 9 | #include <fcntl.h> | ||
| 10 | |||
| 11 | #include "utils.h" | ||
| 12 | |||
| 13 | const char *progname; | ||
| 14 | |||
| 15 | struct sv | ||
| 16 | mmap_whole (int fd) | ||
| 17 | { | ||
| 18 | struct sv sv; | ||
| 19 | |||
| 20 | struct stat st; | ||
| 21 | int ret = fstat (fd, &st); | ||
| 22 | UNUSED (ret); | ||
| 23 | ASSERT_MSG (ret != -1, "fstat: %s", strerror (errno)); | ||
| 24 | ASSERT (S_ISREG (st.st_mode)); | ||
| 25 | |||
| 26 | posix_fadvise (fd, 0, st.st_size, POSIX_FADV_SEQUENTIAL | | ||
| 27 | POSIX_FADV_WILLNEED | | ||
| 28 | POSIX_FADV_NOREUSE); | ||
| 29 | |||
| 30 | sv.beg = mmap (NULL, st.st_size, PROT_READ, MAP_PRIVATE | | ||
| 31 | MAP_POPULATE | | ||
| 32 | MAP_NONBLOCK, fd, 0); | ||
| 33 | ASSERT_MSG (sv.beg != MAP_FAILED, "mmap: %s", strerror (errno)); | ||
| 34 | posix_madvise ((void *) sv.beg, st.st_size, MADV_HUGEPAGE | MADV_WILLNEED); | ||
| 35 | |||
| 36 | sv.end = sv.beg + st.st_size; | ||
| 37 | |||
| 38 | return sv; | ||
| 39 | } | ||
| 40 | |||
| 41 | struct sv | ||
| 42 | read_until_eof (struct arena *a, int fd) | ||
| 43 | { | ||
| 44 | struct arena_checkpoint cp = arena_checkpoint (a, 1); | ||
| 45 | size_t reserve = 4096; | ||
| 46 | |||
| 47 | size_t read_total = 0; | ||
| 48 | for (;;) { | ||
| 49 | arena_reserve (a, reserve, 1); | ||
| 50 | ssize_t bytes_read = | ||
| 51 | read (fd, arena_next_free (a, 1), arena_room (a, 1)); | ||
| 52 | |||
| 53 | if (bytes_read < 0) { | ||
| 54 | DEBUG ("read: %s", strerror (errno)); | ||
| 55 | arena_rollback_to (a, cp); | ||
| 56 | return (struct sv) {0}; | ||
| 57 | } | ||
| 58 | |||
| 59 | if (bytes_read == 0) | ||
| 60 | break; | ||
| 61 | |||
| 62 | read_total += bytes_read; | ||
| 63 | |||
| 64 | arena_allocate_fast (a, bytes_read, 1); | ||
| 65 | reserve *= 2; | ||
| 66 | } | ||
| 67 | |||
| 68 | if (a->tail->free == cp.free) | ||
| 69 | return (struct sv) {0}; | ||
| 70 | |||
| 71 | char *ptr = arena_coalesce_from_fast (a, cp, read_total); | ||
| 72 | return (struct sv) { | ||
| 73 | .beg = ptr, | ||
| 74 | .end = ptr + read_total, | ||
| 75 | }; | ||
| 76 | } | ||
| 77 | |||
| 78 | struct location | ||
| 79 | find_location (struct sv haystack, struct sv needle) | ||
| 80 | { | ||
| 81 | ASSERT (needle.beg >= haystack.beg); | ||
| 82 | ASSERT (needle.end <= haystack.end); | ||
| 83 | |||
| 84 | struct location loc = { .beg = { 1, 1 } }; | ||
| 85 | |||
| 86 | const char *head; | ||
| 87 | for (head = haystack.beg; head < needle.beg; ++head) { | ||
| 88 | loc.beg.column += 1; | ||
| 89 | if (*head == '\n') { | ||
| 90 | loc.beg.line += 1; | ||
| 91 | loc.beg.column = 1; | ||
| 92 | } | ||
| 93 | } | ||
| 94 | |||
| 95 | loc.end.line = loc.beg.line; | ||
| 96 | loc.end.column = loc.beg.column - 1; | ||
| 97 | |||
| 98 | for (; head < needle.end; ++head) { | ||
| 99 | loc.end.column += 1; | ||
| 100 | if (*head == '\n') { | ||
| 101 | loc.end.line += 1; | ||
| 102 | loc.end.column = 1; | ||
| 103 | } | ||
| 104 | } | ||
| 105 | |||
| 106 | return loc; | ||
| 107 | } | ||
| 108 | |||
| 109 | void | ||
| 110 | print_location (const char *filename, struct location loc, | ||
| 111 | int alignment, const char *format, ...) | ||
| 112 | { | ||
| 113 | int printed = 0; | ||
| 114 | |||
| 115 | printed += printf ("%s:", filename); | ||
| 116 | if (loc.end.line > loc.beg.line) { | ||
| 117 | printed += printf ("%d-%d", loc.beg.line, loc.end.line); | ||
| 118 | } else { | ||
| 119 | printed += printf ("%d:%d-%d", loc.beg.line, loc.beg.column, | ||
| 120 | loc.end.column); | ||
| 121 | } printed += printf (": info: "); | ||
| 122 | |||
| 123 | while (printed < alignment) { | ||
| 124 | putchar (' '); | ||
| 125 | printed += 1; | ||
| 126 | } | ||
| 127 | |||
| 128 | va_list ap; | ||
| 129 | va_start (ap, format); | ||
| 130 | vprintf (format, ap); | ||
| 131 | va_end (ap); | ||
| 132 | printf ("\n"); | ||
| 133 | } | ||
| 134 | |||
| 135 | // src/utils.c ends here | ||
diff --git a/src/utils.h b/src/utils.h new file mode 100644 index 0000000..b6c38d5 --- /dev/null +++ b/src/utils.h | |||
| @@ -0,0 +1,132 @@ | |||
| 1 | // src/utils.h | ||
| 2 | |||
| 3 | #ifndef INCLUDED_UTILS_H | ||
| 4 | #define INCLUDED_UTILS_H | ||
| 5 | |||
| 6 | #include <stdio.h> | ||
| 7 | #include <stdlib.h> | ||
| 8 | #include <stdint.h> | ||
| 9 | #include <string.h> | ||
| 10 | #include <time.h> | ||
| 11 | |||
| 12 | #include "sv.h" | ||
| 13 | #include "arena.h" | ||
| 14 | |||
| 15 | #define NOP() do {} while (0) | ||
| 16 | |||
| 17 | #define ARRAY_LENGTH(ARR) (sizeof (ARR)/sizeof (*(ARR))) | ||
| 18 | |||
| 19 | #ifndef NDEBUG | ||
| 20 | #include <assert.h> | ||
| 21 | #define ASSERT assert | ||
| 22 | #else | ||
| 23 | #define ASSERT(...) NOP () | ||
| 24 | #endif | ||
| 25 | |||
| 26 | #define MALLOC malloc | ||
| 27 | #define REALLOC realloc | ||
| 28 | #define FREE free | ||
| 29 | |||
| 30 | #define UNUSED(EXP) ((void) EXP) | ||
| 31 | |||
| 32 | #define FALLTHROUGH __attribute__ ((__fallthrough__)) | ||
| 33 | |||
| 34 | #define STRINGIFY(ARG) #ARG | ||
| 35 | #define TO_STRING(ARG) STRINGIFY (ARG) | ||
| 36 | |||
| 37 | #ifndef NDEBUG | ||
| 38 | #define DEBUG(FMT, ...) \ | ||
| 39 | fprintf (stderr, __FILE__ ":" TO_STRING (__LINE__) ": %s: " FMT "\n", \ | ||
| 40 | __func__, ##__VA_ARGS__) | ||
| 41 | #define LOG(FMT, ...) \ | ||
| 42 | fprintf (stderr, __FILE__ ":" TO_STRING (__LINE__) ": %s: " FMT "\n", \ | ||
| 43 | __func__, ##__VA_ARGS__) | ||
| 44 | #else | ||
| 45 | #define DEBUG(...) NOP () | ||
| 46 | #define LOG(FMT, ...) \ | ||
| 47 | fprintf (stderr, "%s: " FMT "\n", progname, ##__VA_ARGS__) | ||
| 48 | #endif | ||
| 49 | |||
| 50 | #define FATAL(FMT, ...) LOG ("fatal: " FMT, ##__VA_ARGS__) | ||
| 51 | #define ERROR(FMT, ...) LOG ("error: " FMT, ##__VA_ARGS__) | ||
| 52 | #define WARNING(FMT, ...) LOG ("warning: " FMT, ##__VA_ARGS__) | ||
| 53 | #define NOTICE(FMT, ...) LOG ("notice: " FMT, ##__VA_ARGS__) | ||
| 54 | #define INFO(FMT, ...) LOG ("info: " FMT, ##__VA_ARGS__) | ||
| 55 | |||
| 56 | #define DIE(FMT, ...) do { \ | ||
| 57 | FATAL (FMT, ##__VA_ARGS__); \ | ||
| 58 | exit (EXIT_FAILURE); \ | ||
| 59 | } while (0) | ||
| 60 | |||
| 61 | #ifndef NDEBUG | ||
| 62 | #define ASSERT_MSG(EXP, FMT, ...) do if (!(EXP)) { \ | ||
| 63 | DEBUG (FMT, ##__VA_ARGS__); \ | ||
| 64 | exit (EXIT_FAILURE); \ | ||
| 65 | } while (0) | ||
| 66 | #else | ||
| 67 | #define ASSERT_MSG(EXP, FMT, ...) NOP () | ||
| 68 | #endif | ||
| 69 | |||
| 70 | #define MEASURE(FMT, ...) \ | ||
| 71 | for (struct timespec _ts0, _ts1, *_once = NULL; \ | ||
| 72 | clock_gettime (CLOCK_MONOTONIC, &_ts0), !_once; \ | ||
| 73 | clock_gettime (CLOCK_MONOTONIC, &_ts1), \ | ||
| 74 | DEBUG (FMT " %.6fs\n", ##__VA_ARGS__, \ | ||
| 75 | (_ts1.tv_sec - _ts0.tv_sec ) + \ | ||
| 76 | (_ts1.tv_nsec - _ts0.tv_nsec) / 1e9), \ | ||
| 77 | _once += 1) | ||
| 78 | |||
| 79 | #define MIN(A, B) ((A) <= (B) ? (A) : (B)) | ||
| 80 | |||
| 81 | struct timer_scope { | ||
| 82 | char *fmt; | ||
| 83 | struct timespec start; | ||
| 84 | }; | ||
| 85 | |||
| 86 | static void | ||
| 87 | timer_end (struct timer_scope *t) | ||
| 88 | { | ||
| 89 | struct timespec end; | ||
| 90 | clock_gettime (CLOCK_MONOTONIC, &end); | ||
| 91 | |||
| 92 | double s = ((end.tv_sec - t->start.tv_sec) + | ||
| 93 | (end.tv_nsec - t->start.tv_nsec)/1e9); | ||
| 94 | |||
| 95 | fprintf (stderr, t->fmt, s); | ||
| 96 | if (t->fmt[strlen (t->fmt) - 1] != ' ') | ||
| 97 | putc (' ', stderr); | ||
| 98 | fprintf (stderr, "took %.6fs\n", s); | ||
| 99 | free (t->fmt); | ||
| 100 | } | ||
| 101 | |||
| 102 | #define MEASURE_SCOPE(FMT, ...) \ | ||
| 103 | __attribute__ ((cleanup (timer_end))) struct timer_scope __ts; \ | ||
| 104 | asprintf (&__ts.fmt, \ | ||
| 105 | __FILE__ ":" TO_STRING (__LINE__) ": %s: " FMT, \ | ||
| 106 | __func__, ##__VA_ARGS__); \ | ||
| 107 | clock_gettime (CLOCK_MONOTONIC, &__ts.start) | ||
| 108 | |||
| 109 | struct location { | ||
| 110 | struct { | ||
| 111 | int line; | ||
| 112 | int column; | ||
| 113 | } beg; | ||
| 114 | struct { | ||
| 115 | int line; | ||
| 116 | int column; | ||
| 117 | } end; | ||
| 118 | }; | ||
| 119 | |||
| 120 | extern const char *progname; | ||
| 121 | |||
| 122 | struct sv mmap_whole (int fd); | ||
| 123 | struct sv read_until_eof (struct arena *, int fd); | ||
| 124 | |||
| 125 | struct location find_location (struct sv haystack, struct sv needle); | ||
| 126 | void print_location (const char *filename, struct location, int alignment, const char *format, ...); | ||
| 127 | |||
| 128 | void print_back_trace (int skip); | ||
| 129 | |||
| 130 | #endif // INCLUDED_UTILS_H | ||
| 131 | |||
| 132 | // src/utils.h ends here | ||
diff --git a/src/vec2.c b/src/vec2.c new file mode 100644 index 0000000..7c325fe --- /dev/null +++ b/src/vec2.c | |||
| @@ -0,0 +1,67 @@ | |||
| 1 | #include "vec2.h" | ||
| 2 | #include <math.h> | ||
| 3 | |||
| 4 | struct vec2 | ||
| 5 | vec2_add (struct vec2 a, struct vec2 b) | ||
| 6 | { | ||
| 7 | return (struct vec2) { a.x + b.x, a.y + b.y }; | ||
| 8 | } | ||
| 9 | |||
| 10 | struct vec2 | ||
| 11 | vec2_sub (struct vec2 a, struct vec2 b) | ||
| 12 | { | ||
| 13 | return (struct vec2) { a.x - b.x, a.y - b.y }; | ||
| 14 | } | ||
| 15 | |||
| 16 | struct vec2 | ||
| 17 | vec2_scale (struct vec2 a, double k) | ||
| 18 | { | ||
| 19 | return (struct vec2) { a.x*k, a.y*k }; | ||
| 20 | } | ||
| 21 | |||
| 22 | double | ||
| 23 | vec2_dot (struct vec2 a, struct vec2 b) | ||
| 24 | { | ||
| 25 | return a.x*b.x + a.y*b.y; | ||
| 26 | } | ||
| 27 | |||
| 28 | double | ||
| 29 | vec2_norm (struct vec2 a) | ||
| 30 | { | ||
| 31 | return hypot (a.x, a.y); | ||
| 32 | } | ||
| 33 | |||
| 34 | double | ||
| 35 | vec2_dist (struct vec2 a, struct vec2 b) | ||
| 36 | { | ||
| 37 | return vec2_norm (vec2_sub (a, b)); | ||
| 38 | } | ||
| 39 | |||
| 40 | struct vec2 | ||
| 41 | vec2_unit (struct vec2 a) | ||
| 42 | { | ||
| 43 | double n = vec2_norm (a); | ||
| 44 | |||
| 45 | // if (n <= VEC2_EPS) | ||
| 46 | // return (struct vec2) { 0, 0 }; | ||
| 47 | |||
| 48 | return vec2_scale (a, 1/n); | ||
| 49 | } | ||
| 50 | |||
| 51 | double | ||
| 52 | vec2_angle0 (struct vec2 a) | ||
| 53 | { | ||
| 54 | return atan2 (a.y, a.x); | ||
| 55 | } | ||
| 56 | |||
| 57 | static double | ||
| 58 | clampd (double x, double lo, double hi) | ||
| 59 | { | ||
| 60 | return x < lo ? lo : (x > hi ? hi : x); | ||
| 61 | } | ||
| 62 | |||
| 63 | double | ||
| 64 | vec2_angle (struct vec2 a, struct vec2 b) | ||
| 65 | { | ||
| 66 | return acos (clampd (vec2_dot (a, b)/(vec2_norm (a)*vec2_norm (b)), 0, 1)); | ||
| 67 | } | ||
diff --git a/src/vec2.h b/src/vec2.h new file mode 100644 index 0000000..95dc3b6 --- /dev/null +++ b/src/vec2.h | |||
| @@ -0,0 +1,18 @@ | |||
| 1 | #ifndef INCLUDED_VEC2_H | ||
| 2 | #define INCLUDED_VEC2_H | ||
| 3 | |||
| 4 | struct vec2 { | ||
| 5 | double x, y; | ||
| 6 | }; | ||
| 7 | |||
| 8 | double vec2_norm (struct vec2 a); | ||
| 9 | struct vec2 vec2_unit (struct vec2 a); | ||
| 10 | struct vec2 vec2_scale (struct vec2 a, double k); | ||
| 11 | struct vec2 vec2_add (struct vec2 a, struct vec2 b); | ||
| 12 | struct vec2 vec2_sub (struct vec2 a, struct vec2 b); | ||
| 13 | double vec2_dot (struct vec2 a, struct vec2 b); | ||
| 14 | double vec2_dist (struct vec2 a, struct vec2 b); | ||
| 15 | double vec2_angle (struct vec2 a, struct vec2 b); | ||
| 16 | double vec2_angle0 (struct vec2 a); | ||
| 17 | |||
| 18 | #endif // INCLUDED_VEC2_H | ||
