A data transfer object is a [[Plain Old Data|POD]] object that has been optimized for network transfer.
This utilizes lessons learned in [[Structure Optimization]] but includes different strategies for either:
* Reducing the size of the transferred data
* Increasing Resiliency against corruption
[[Protobuff|Protobuffs]] are a great example of a library creating DTOs.
## Field Serialization
### Booleans
For many [[Boolean Math|boolean]] flags, use a bitfield instead to represent them (1-bit per flag instead of 8 for a bool).
### Velocity
If the field represents a velocity, but most objects are at rest, then encode a 'at rest' flag of some kind, and avoid sending the velocity if it's set.
### Quaternions
Quaternions are represented by 4 values, $(x,y,z,w)$ , but you can calculate any one of the pairs with the 'smallest 3' method.
#### Smallest 3
The lengths of a Quaternion add up to $1$: $x^2+y^2+z^2+w^2 = 1$
Pick the largest, let's say $w$. You can reconstruct $w$ with: $w = \sqrt{1 - x^2 - y^2 - z^2}$ we pick the largest to reconstruct because larger [[IEE-754]] floats have less precision.
Take two bits to encode which of the components is the largest component and send that over the network as well.
#### Bit Compression
As quaternions are essentially a vector, you can reduce the precision significantly while still having it point in the same direction.
### Positions
* If a position can be bounded, you can apply bit-crunching to cover only the expected range.
* If you only need a certain amount of precision, you can try fixed point encoding.
## Error Checking
#grow
Simple [[Checksum#CRC|CRC]] checks could be done.
Keeping a record of the packet # allows for out-of-order packet transmission detection errors.
---
# References
https://gafferongames.com/post/serialization_strategies/
https://gafferongames.com/post/snapshot_compression/