├── .gitattributes
├── .gitignore
├── LICENSE
├── Physics2D
├── include
│ ├── physics2d.h
│ ├── physics2d_aabb.h
│ ├── physics2d_algorithm_2d.h
│ ├── physics2d_body.h
│ ├── physics2d_capsule.h
│ ├── physics2d_ccd.h
│ ├── physics2d_circle.h
│ ├── physics2d_collider.h
│ ├── physics2d_common.h
│ ├── physics2d_contact.h
│ ├── physics2d_detector.h
│ ├── physics2d_distance_joint.h
│ ├── physics2d_edge.h
│ ├── physics2d_ellipse.h
│ ├── physics2d_grid.h
│ ├── physics2d_integrator.h
│ ├── physics2d_joint.h
│ ├── physics2d_joints.h
│ ├── physics2d_linear.h
│ ├── physics2d_math.h
│ ├── physics2d_matrix2x2.h
│ ├── physics2d_matrix3x3.h
│ ├── physics2d_matrix4x4.h
│ ├── physics2d_narrowphase.h
│ ├── physics2d_point_joint.h
│ ├── physics2d_polygon.h
│ ├── physics2d_pulley_joint.h
│ ├── physics2d_quaternion.h
│ ├── physics2d_random.h
│ ├── physics2d_rectangle.h
│ ├── physics2d_revolute_joint.h
│ ├── physics2d_rotation_joint.h
│ ├── physics2d_sap.h
│ ├── physics2d_shape.h
│ ├── physics2d_simplex.h
│ ├── physics2d_system.h
│ ├── physics2d_tree.h
│ ├── physics2d_vector2.h
│ ├── physics2d_vector3.h
│ ├── physics2d_vector4.h
│ ├── physics2d_weld_joint.h
│ └── physics2d_world.h
└── source
│ ├── collision
│ ├── physics2d_aabb.cpp
│ ├── physics2d_capsule.cpp
│ ├── physics2d_ccd.cpp
│ ├── physics2d_circle.cpp
│ ├── physics2d_collider.cpp
│ ├── physics2d_detector.cpp
│ ├── physics2d_edge.cpp
│ ├── physics2d_ellipse.cpp
│ ├── physics2d_grid.cpp
│ ├── physics2d_narrowphase.cpp
│ ├── physics2d_polygon.cpp
│ ├── physics2d_rectangle.cpp
│ ├── physics2d_sap.cpp
│ ├── physics2d_simplex.cpp
│ └── physics2d_tree.cpp
│ ├── dynamics
│ ├── physics2d_body.cpp
│ ├── physics2d_contact.cpp
│ ├── physics2d_system.cpp
│ └── physics2d_world.cpp
│ ├── math
│ ├── physics2d_algorithm_2d.cpp
│ ├── physics2d_integrator.cpp
│ ├── physics2d_math.cpp
│ ├── physics2d_matrix2x2.cpp
│ ├── physics2d_matrix3x3.cpp
│ ├── physics2d_matrix4x4.cpp
│ ├── physics2d_quaternion.cpp
│ ├── physics2d_vector2.cpp
│ ├── physics2d_vector3.cpp
│ └── physics2d_vector4.cpp
│ └── other
│ ├── physics2d_common.cpp
│ └── physics2d_random.cpp
├── README.md
├── README_zh_CN.md
└── xmake.lua
/.gitattributes:
--------------------------------------------------------------------------------
1 | ###############################################################################
2 | # Set default behavior to automatically normalize line endings.
3 | ###############################################################################
4 | * text=auto
5 |
6 | ###############################################################################
7 | # Set default behavior for command prompt diff.
8 | #
9 | # This is need for earlier builds of msysgit that does not have it on by
10 | # default for csharp files.
11 | # Note: This is only used by command line
12 | ###############################################################################
13 | #*.cs diff=csharp
14 |
15 | ###############################################################################
16 | # Set the merge driver for project and solution files
17 | #
18 | # Merging from the command prompt will add diff markers to the files if there
19 | # are conflicts (Merging from VS is not affected by the settings below, in VS
20 | # the diff markers are never inserted). Diff markers may cause the following
21 | # file extensions to fail to load in VS. An alternative would be to treat
22 | # these files as binary and thus will always conflict and require user
23 | # intervention with every merge. To do so, just uncomment the entries below
24 | ###############################################################################
25 | #*.sln merge=binary
26 | #*.csproj merge=binary
27 | #*.vbproj merge=binary
28 | #*.vcxproj merge=binary
29 | #*.vcproj merge=binary
30 | #*.dbproj merge=binary
31 | #*.fsproj merge=binary
32 | #*.lsproj merge=binary
33 | #*.wixproj merge=binary
34 | #*.modelproj merge=binary
35 | #*.sqlproj merge=binary
36 | #*.wwaproj merge=binary
37 |
38 | ###############################################################################
39 | # behavior for image files
40 | #
41 | # image files are treated as binary by default.
42 | ###############################################################################
43 | #*.jpg binary
44 | #*.png binary
45 | #*.gif binary
46 |
47 | ###############################################################################
48 | # diff behavior for common document formats
49 | #
50 | # Convert binary document formats to text before diffing them. This feature
51 | # is only available from the command line. Turn it on by uncommenting the
52 | # entries below.
53 | ###############################################################################
54 | #*.doc diff=astextplain
55 | #*.DOC diff=astextplain
56 | #*.docx diff=astextplain
57 | #*.DOCX diff=astextplain
58 | #*.dot diff=astextplain
59 | #*.DOT diff=astextplain
60 | #*.pdf diff=astextplain
61 | #*.PDF diff=astextplain
62 | #*.rtf diff=astextplain
63 | #*.RTF diff=astextplain
64 |
--------------------------------------------------------------------------------
/.gitignore:
--------------------------------------------------------------------------------
1 | ## Ignore Visual Studio temporary files, build results, and
2 | ## files generated by popular Visual Studio add-ons.
3 | ##
4 | ## Get latest from https://github.com/github/gitignore/blob/master/VisualStudio.gitignore
5 |
6 | # MacOS Cache
7 | .DS_Store
8 |
9 | # Xmake cache
10 | .xmake/
11 | build/
12 | makefile
13 |
14 | # gcc cache
15 | gcm.cache
16 |
17 | # for VS Code
18 | .vscode/
19 |
20 | # for vim
21 | *.swp
22 | *.swo
23 | tags
24 | !tags/
25 |
26 | # Ignore packaging files
27 | winenv/
28 | *.exe
29 | *.zip
30 | *.gz
31 | *.bz2
32 | *.xz
33 | *.7z
34 | *.run
35 |
36 | # for compiler
37 | compile_commands.json
38 |
39 | # Makefile generation
40 | /core/xmake.config.h
41 | /core/.config.mak
42 | /core/**/*.o
43 | /core/**/*.b
44 | /core/**/*.a
45 | /core/**/*.obj
46 | /core/**/*.lib
47 | /core/**/*.exe
48 |
49 | # for fortran
50 | /tests/**/*.mod
51 |
52 | # for rpmbuild
53 | /scripts/rpmbuild/BUILD*/*
54 | /scripts/rpmbuild/RPMS/*
55 | /scripts/rpmbuild/SOURCES/*
56 | /scripts/rpmbuild/SRPMS/*
57 |
58 | !/xmake/actions/build/
59 |
60 | # for linux driver
61 | *.o
62 | *.ko
63 | *.mod
64 | .*.cmd
65 | *.mod.c
66 | Module.symvers
67 | modules.order
68 |
69 | # User-specific files
70 | *.rsuser
71 | *.suo
72 | *.user
73 | *.userosscache
74 | *.sln.docstates
75 |
76 | # User-specific files (MonoDevelop/Xamarin Studio)
77 | *.userprefs
78 |
79 | # Mono auto generated files
80 | mono_crash.*
81 |
82 | # Build results
83 | [Dd]ebug/
84 | [Dd]ebugPublic/
85 | [Rr]elease/
86 | [Rr]eleases/
87 | x64/
88 | x86/
89 | [Ww][Ii][Nn]32/
90 | [Aa][Rr][Mm]/
91 | [Aa][Rr][Mm]64/
92 | bld/
93 | [Bb]in/
94 | [Oo]bj/
95 | [Oo]ut/
96 | [Ll]og/
97 | [Ll]ogs/
98 |
99 | # Visual Studio 2015/2017 cache/options directory
100 | .vs/
101 | # Uncomment if you have tasks that create the project's static files in wwwroot
102 | #wwwroot/
103 |
104 | # Visual Studio 2017 auto generated files
105 | Generated\ Files/
106 |
107 | # MSTest test Results
108 | [Tt]est[Rr]esult*/
109 | [Bb]uild[Ll]og.*
110 |
111 | # NUnit
112 | *.VisualState.xml
113 | TestResult.xml
114 | nunit-*.xml
115 |
116 | # Build Results of an ATL Project
117 | [Dd]ebugPS/
118 | [Rr]eleasePS/
119 | dlldata.c
120 |
121 | # Benchmark Results
122 | BenchmarkDotNet.Artifacts/
123 |
124 | # .NET Core
125 | project.lock.json
126 | project.fragment.lock.json
127 | artifacts/
128 |
129 | # ASP.NET Scaffolding
130 | ScaffoldingReadMe.txt
131 |
132 | # StyleCop
133 | StyleCopReport.xml
134 |
135 | # Files built by Visual Studio
136 | *_i.c
137 | *_p.c
138 | *_h.h
139 | *.ilk
140 | *.meta
141 | *.obj
142 | *.iobj
143 | *.pch
144 | *.pdb
145 | *.ipdb
146 | *.pgc
147 | *.pgd
148 | *.rsp
149 | *.sbr
150 | *.tlb
151 | *.tli
152 | *.tlh
153 | *.tmp
154 | *.tmp_proj
155 | *_wpftmp.csproj
156 | *.log
157 | *.vspscc
158 | *.vssscc
159 | .builds
160 | *.pidb
161 | *.svclog
162 | *.scc
163 |
164 | # Chutzpah Test files
165 | _Chutzpah*
166 |
167 | # Visual C++ cache files
168 | ipch/
169 | *.aps
170 | *.ncb
171 | *.opendb
172 | *.opensdf
173 | *.sdf
174 | *.cachefile
175 | *.VC.db
176 | *.VC.VC.opendb
177 |
178 | # Visual Studio profiler
179 | *.psess
180 | *.vsp
181 | *.vspx
182 | *.sap
183 |
184 | # Visual Studio Trace Files
185 | *.e2e
186 |
187 | # TFS 2012 Local Workspace
188 | $tf/
189 |
190 | # Guidance Automation Toolkit
191 | *.gpState
192 |
193 | # ReSharper is a .NET coding add-in
194 | _ReSharper*/
195 | *.[Rr]e[Ss]harper
196 | *.DotSettings.user
197 |
198 | # TeamCity is a build add-in
199 | _TeamCity*
200 |
201 | # DotCover is a Code Coverage Tool
202 | *.dotCover
203 |
204 | # AxoCover is a Code Coverage Tool
205 | .axoCover/*
206 | !.axoCover/settings.json
207 |
208 | # Coverlet is a free, cross platform Code Coverage Tool
209 | coverage*.json
210 | coverage*.xml
211 | coverage*.info
212 |
213 | # Visual Studio code coverage results
214 | *.coverage
215 | *.coveragexml
216 |
217 | # NCrunch
218 | _NCrunch_*
219 | .*crunch*.local.xml
220 | nCrunchTemp_*
221 |
222 | # MightyMoose
223 | *.mm.*
224 | AutoTest.Net/
225 |
226 | # Web workbench (sass)
227 | .sass-cache/
228 |
229 | # Installshield output folder
230 | [Ee]xpress/
231 |
232 | # DocProject is a documentation generator add-in
233 | DocProject/buildhelp/
234 | DocProject/Help/*.HxT
235 | DocProject/Help/*.HxC
236 | DocProject/Help/*.hhc
237 | DocProject/Help/*.hhk
238 | DocProject/Help/*.hhp
239 | DocProject/Help/Html2
240 | DocProject/Help/html
241 |
242 | # Click-Once directory
243 | publish/
244 |
245 | # Publish Web Output
246 | *.[Pp]ublish.xml
247 | *.azurePubxml
248 | # Note: Comment the next line if you want to checkin your web deploy settings,
249 | # but database connection strings (with potential passwords) will be unencrypted
250 | *.pubxml
251 | *.publishproj
252 |
253 | # Microsoft Azure Web App publish settings. Comment the next line if you want to
254 | # checkin your Azure Web App publish settings, but sensitive information contained
255 | # in these scripts will be unencrypted
256 | PublishScripts/
257 |
258 | # NuGet Packages
259 | *.nupkg
260 | # NuGet Symbol Packages
261 | *.snupkg
262 | # The packages folder can be ignored because of Package Restore
263 | **/[Pp]ackages/*
264 | # except build/, which is used as an MSBuild target.
265 | !**/[Pp]ackages/build/
266 | # Uncomment if necessary however generally it will be regenerated when needed
267 | #!**/[Pp]ackages/repositories.config
268 | # NuGet v3's project.json files produces more ignorable files
269 | *.nuget.props
270 | *.nuget.targets
271 |
272 | # Microsoft Azure Build Output
273 | csx/
274 | *.build.csdef
275 |
276 | # Microsoft Azure Emulator
277 | ecf/
278 | rcf/
279 |
280 | # Windows Store app package directories and files
281 | AppPackages/
282 | BundleArtifacts/
283 | Package.StoreAssociation.xml
284 | _pkginfo.txt
285 | *.appx
286 | *.appxbundle
287 | *.appxupload
288 |
289 | # Visual Studio cache files
290 | # files ending in .cache can be ignored
291 | *.[Cc]ache
292 | # but keep track of directories ending in .cache
293 | !?*.[Cc]ache/
294 |
295 | # Others
296 | ClientBin/
297 | ~$*
298 | *~
299 | *.dbmdl
300 | *.dbproj.schemaview
301 | *.jfm
302 | *.pfx
303 | *.publishsettings
304 | orleans.codegen.cs
305 |
306 | # Including strong name files can present a security risk
307 | # (https://github.com/github/gitignore/pull/2483#issue-259490424)
308 | #*.snk
309 |
310 | # Since there are multiple workflows, uncomment next line to ignore bower_components
311 | # (https://github.com/github/gitignore/pull/1529#issuecomment-104372622)
312 | #bower_components/
313 |
314 | # RIA/Silverlight projects
315 | Generated_Code/
316 |
317 | # Backup & report files from converting an old project file
318 | # to a newer Visual Studio version. Backup files are not needed,
319 | # because we have git ;-)
320 | _UpgradeReport_Files/
321 | Backup*/
322 | UpgradeLog*.XML
323 | UpgradeLog*.htm
324 | ServiceFabricBackup/
325 | *.rptproj.bak
326 |
327 | # SQL Server files
328 | *.mdf
329 | *.ldf
330 | *.ndf
331 |
332 | # Business Intelligence projects
333 | *.rdl.data
334 | *.bim.layout
335 | *.bim_*.settings
336 | *.rptproj.rsuser
337 | *- [Bb]ackup.rdl
338 | *- [Bb]ackup ([0-9]).rdl
339 | *- [Bb]ackup ([0-9][0-9]).rdl
340 |
341 | # Microsoft Fakes
342 | FakesAssemblies/
343 |
344 | # GhostDoc plugin setting file
345 | *.GhostDoc.xml
346 |
347 | # Node.js Tools for Visual Studio
348 | .ntvs_analysis.dat
349 | node_modules/
350 |
351 | # Visual Studio 6 build log
352 | *.plg
353 |
354 | # Visual Studio 6 workspace options file
355 | *.opt
356 |
357 | # Visual Studio 6 auto-generated workspace file (contains which files were open etc.)
358 | *.vbw
359 |
360 | # Visual Studio LightSwitch build output
361 | **/*.HTMLClient/GeneratedArtifacts
362 | **/*.DesktopClient/GeneratedArtifacts
363 | **/*.DesktopClient/ModelManifest.xml
364 | **/*.Server/GeneratedArtifacts
365 | **/*.Server/ModelManifest.xml
366 | _Pvt_Extensions
367 |
368 | # Paket dependency manager
369 | .paket/paket.exe
370 | paket-files/
371 |
372 | # FAKE - F# Make
373 | .fake/
374 |
375 | # CodeRush personal settings
376 | .cr/personal
377 |
378 | # Python Tools for Visual Studio (PTVS)
379 | __pycache__/
380 | *.pyc
381 |
382 | # Cake - Uncomment if you are using it
383 | # tools/**
384 | # !tools/packages.config
385 |
386 | # Tabs Studio
387 | *.tss
388 |
389 | # Telerik's JustMock configuration file
390 | *.jmconfig
391 |
392 | # BizTalk build output
393 | *.btp.cs
394 | *.btm.cs
395 | *.odx.cs
396 | *.xsd.cs
397 |
398 | # OpenCover UI analysis results
399 | OpenCover/
400 |
401 | # Azure Stream Analytics local run output
402 | ASALocalRun/
403 |
404 | # MSBuild Binary and Structured Log
405 | *.binlog
406 |
407 | # NVidia Nsight GPU debugger configuration file
408 | *.nvuser
409 |
410 | # MFractors (Xamarin productivity tool) working folder
411 | .mfractor/
412 |
413 | # Local History for Visual Studio
414 | .localhistory/
415 |
416 | # BeatPulse healthcheck temp database
417 | healthchecksdb
418 |
419 | # Backup folder for Package Reference Convert tool in Visual Studio 2017
420 | MigrationBackup/
421 |
422 | # Ionide (cross platform F# VS Code tools) working folder
423 | .ionide/
424 |
425 | # Fody - auto-generated XML schema
426 | FodyWeavers.xsd
--------------------------------------------------------------------------------
/LICENSE:
--------------------------------------------------------------------------------
1 | MIT License
2 |
3 | Copyright (c) 2021 ACRL
4 |
5 | Permission is hereby granted, free of charge, to any person obtaining a copy
6 | of this software and associated documentation files (the "Software"), to deal
7 | in the Software without restriction, including without limitation the rights
8 | to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9 | copies of the Software, and to permit persons to whom the Software is
10 | furnished to do so, subject to the following conditions:
11 |
12 | The above copyright notice and this permission notice shall be included in all
13 | copies or substantial portions of the Software.
14 |
15 | THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16 | IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17 | FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18 | AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19 | LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20 | OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21 | SOFTWARE.
22 |
--------------------------------------------------------------------------------
/Physics2D/include/physics2d.h:
--------------------------------------------------------------------------------
1 | #ifndef PHYSICS2D_H
2 | #define PHYSICS2D_H
3 |
4 | #include "physics2d_detector.h"
5 | #include "physics2d_collider.h"
6 | #include "physics2d_tree.h"
7 |
8 | #include "physics2d_ccd.h"
9 | #include "physics2d_common.h"
10 | #include "physics2d_shape.h"
11 | #include "physics2d_algorithm_2d.h"
12 | #include "physics2d_system.h"
13 | #include "physics2d_math.h"
14 | #include "physics2d_linear.h"
15 | #include "physics2d_integrator.h"
16 | #include "physics2d_world.h"
17 | #include "physics2d_joint.h"
18 | #include "physics2d_contact.h"
19 | #include "physics2d_random.h"
20 | #include "physics2d_narrowphase.h"
21 |
22 |
23 | #endif
24 |
--------------------------------------------------------------------------------
/Physics2D/include/physics2d_aabb.h:
--------------------------------------------------------------------------------
1 | #ifndef PHYSICS2D_BROADPHASE_AABB_H
2 | #define PHYSICS2D_BROADPHASE_AABB_H
3 |
4 | #include "physics2d_linear.h"
5 | #include "physics2d_shape.h"
6 |
7 | namespace Physics2D
8 | {
9 | class Body;
10 |
11 | struct PHYSICS2D_API AABB
12 | {
13 | AABB() = default;
14 | AABB(const Vector2& topLeft, const real& boxWidth, const real& boxHeight);
15 | AABB(const Vector2& topLeft, const Vector2& bottomRight);
16 | real width = 0;
17 | real height = 0;
18 | Vector2 position;
19 | inline Vector2 topLeft()const;
20 | inline Vector2 topRight()const;
21 | inline Vector2 bottomLeft()const;
22 | inline Vector2 bottomRight()const;
23 |
24 | inline real minimumX()const;
25 | inline real minimumY()const;
26 | inline real maximumX()const;
27 | inline real maximumY()const;
28 |
29 | bool collide(const AABB& other) const;
30 | void expand(const real& factor);
31 | void scale(const real& factor);
32 | void clear();
33 | AABB& unite(const AABB& other);
34 | real surfaceArea()const;
35 | real volume()const;
36 | bool isSubset(const AABB& other)const;
37 | bool isEmpty()const;
38 | bool operator==(const AABB& other)const;
39 | bool raycast(const Vector2& start, const Vector2& direction)const;
40 | ///
41 | /// Create AABB from shape.
42 | ///
43 | /// shape source
44 | /// AABB scale factor. Default factor 1 means making tight AABB
45 | ///
46 | static AABB fromShape(const ShapePrimitive& shape, const real& factor = 0);
47 | static AABB fromBody(Body* body, const real& factor = 0);
48 | static AABB fromBox(const Vector2& topLeft, const Vector2& bottomRight);
49 | ///
50 | /// Check if two aabbs are overlapping
51 | ///
52 | ///
53 | ///
54 | ///
55 | static bool collide(const AABB& src, const AABB& target);
56 | ///
57 | /// Return two aabb union result
58 | ///
59 | ///
60 | ///
61 | ///
62 | static AABB unite(const AABB& src, const AABB& target, const real& factor = 0);
63 | ///
64 | /// Check if b is subset of a
65 | ///
66 | ///
67 | ///
68 | ///
69 | static bool isSubset(const AABB& a, const AABB& b);
70 |
71 | static void expand(AABB& aabb, const real& factor = 0.0);
72 |
73 | static bool raycast(const AABB& aabb, const Vector2& start, const Vector2& direction);
74 |
75 | };
76 |
77 |
78 | }
79 | #endif
--------------------------------------------------------------------------------
/Physics2D/include/physics2d_algorithm_2d.h:
--------------------------------------------------------------------------------
1 | #ifndef PHYSICS2D_ALGORITHM_GRAPHICS_2D
2 | #define PHYSICS2D_ALGORITHM_GRAPHICS_2D
3 |
4 | #include "physics2d_linear.h"
5 | #include "physics2d_common.h"
6 | namespace Physics2D
7 | {
8 | class PHYSICS2D_API GeometryAlgorithm2D
9 | {
10 | public:
11 | class PHYSICS2D_API Clipper
12 | {
13 | public:
14 | /**
15 | * \brief Sutherland Hodgman Polygon Clipping. All points is stored in counter clock winding.\n
16 | * By convention:\n
17 | * p0 -> p1 -> p2 -> p0 constructs a triangle
18 | * \param polygon
19 | * \param clipRegion
20 | * \return
21 | */
22 | static Container::Vector sutherlandHodgmentPolygonClipping(const Container::Vector& polygon, const Container::Vector& clipRegion);
23 | };
24 |
25 | /**
26 | * \brief Check if point a,b,c are collinear using triangle area method
27 | * \param a point a
28 | * \param b point b
29 | * \param c point c
30 | * \return
31 | */
32 | static bool isCollinear(const Vector2& a, const Vector2& b, const Vector2& c);
33 | /**
34 | * \brief Check if point c is on line segment ab using line projection and set-union method
35 | * \param a end of segment a
36 | * \param b end of segment b
37 | * \param c point c
38 | * \return
39 | */
40 | static bool isPointOnSegment(const Vector2& a, const Vector2& b, const Vector2& c);
41 | /**
42 | * \brief Check if point c is on line segment ab, given a,b,c is already collinear by calculating cross product
43 | * \param a
44 | * \param b
45 | * \param c
46 | * \param epsilon
47 | * \return
48 | */
49 | static bool fuzzyIsPointOnSegment(const Vector2& a, const Vector2& b, const Vector2& c, const real& epsilon = Constant::GeometryEpsilon);
50 | static bool fuzzyIsCollinear(const Vector2& a, const Vector2& b, const Vector2& c);
51 | /**
52 | * \brief Calculate intersected point between line ab and line cd.\n
53 | * Notices: overlapping is NOT considered as a kind of intersection situation in this function
54 | * \param a
55 | * \param b
56 | * \param c
57 | * \param d
58 | * \return if there is a actual intersected point.
59 | */
60 | static std::optional lineSegmentIntersection(const Vector2& a, const Vector2& b, const Vector2& c, const Vector2& d);
61 | /**
62 | * \brief line intersection
63 | * \param p1
64 | * \param p2
65 | * \param q1
66 | * \param q2
67 | * \return
68 | */
69 | static Vector2 lineIntersection(const Vector2& p1, const Vector2& p2, const Vector2& q1, const Vector2& q2);
70 | /**
71 | * \brief Calculate the center of circum-circle from triangle abc
72 | * \param a
73 | * \param b
74 | * \param c
75 | * \return
76 | */
77 | static std::optional triangleCircumcenter(const Vector2& a, const Vector2& b, const Vector2& c);
78 | /**
79 | * \brief Calculate the center of inscribed-circle from triangle abc. If a,b,c can not form a triangle, return nothing
80 | * \param a
81 | * \param b
82 | * \param c
83 | * \return
84 | */
85 | static std::optional triangleIncenter(const Vector2& a, const Vector2& b, const Vector2& c);
86 | /**
87 | * \brief Calculate circum-circle given three points that can form a triangle. If a,b,c can not form a triangle, return nothing
88 | * \param a
89 | * \param b
90 | * \param c
91 | * \return
92 | */
93 | static std::optional> calculateCircumcircle(const Vector2& a, const Vector2& b, const Vector2& c);
94 | /**
95 | * \brief Calculate inscribed circle given three points that can form a triangle. If a,b,c can not form a triangle, return nothing.
96 | * \param a
97 | * \param b
98 | * \param c
99 | * \return
100 | */
101 | static std::optional> calculateInscribedCircle(const Vector2& a, const Vector2& b, const Vector2& c);
102 | /**
103 | * \brief Check if a polygon is convex
104 | * \param vertices
105 | * \return
106 | */
107 | static bool isConvexPolygon(const Container::Vector& vertices);
108 | /**
109 | * \brief Convex hull algorithm: Graham Scan. Given a series of points, find the convex polygon that can contains all of these points.
110 | * \param vertices
111 | * \return
112 | */
113 | static Container::Vector grahamScan(const Container::Vector& vertices);
114 | /**
115 | * \brief Calculate point on ellipse that is the shortest length to point p(aka projection point).
116 | * \param a
117 | * \param b
118 | * \param p
119 | * \param epsilon
120 | * \return
121 | */
122 | static Vector2 shortestLengthPointOfEllipse(const real& a, const real& b, const Vector2& p, const real& epsilon = Constant::GeometryEpsilon);
123 | /**
124 | * \brief Calculate the centroid of triangle.
125 | * \param a1
126 | * \param a2
127 | * \param a3
128 | * \return
129 | */
130 | static Vector2 triangleCentroid(const Vector2& a1, const Vector2& a2, const Vector2& a3);
131 | /**
132 | * \brief Calculate the area of triangle use cross product.
133 | * \param a1
134 | * \param a2
135 | * \param a3
136 | * \return
137 | */
138 | static real triangleArea(const Vector2& a1, const Vector2& a2, const Vector2& a3);
139 | /**
140 | * \brief Calculate mass center of 'convex' polygon
141 | * \param vertices
142 | * \return
143 | */
144 | static Vector2 calculateCenter(const Container::Vector& vertices);
145 | static Vector2 calculateCenter(const std::list& vertices);
146 | /**
147 | * \brief Calculate two points on line segment and ellipse respectively. The length of two points is the shortest distance of line segment and ellipse
148 | * \param a major axis a
149 | * \param b minor axis b
150 | * \param p1 line segment point 1
151 | * \param p2 line segment point 2
152 | * \return
153 | */
154 | static std::tuple shortestLengthLineSegmentEllipse(const real& a, const real& b, const Vector2& p1, const Vector2& p2);
155 | /**
156 | * \brief Calculate point on line segment ab, if point 'p' can cast ray in 'dir' direction on line segment ab. \n
157 | * Algorithm from wikipedia Line-line intersection.
158 | * \param p ray start point
159 | * \param dir ray direction
160 | * \param a line segment point a
161 | * \param b line segment point b
162 | * \return
163 | */
164 | static std::optional raycast(const Vector2& p, const Vector2& dir, const Vector2& a, const Vector2& b);
165 | static std::optional> raycastAABB(const Vector2& p, const Vector2& dir, const Vector2& topLeft, const Vector2& bottomRight);
166 | static bool isPointOnAABB(const Vector2& p, const Vector2& topLeft, const Vector2& bottomRight);
167 | /**
168 | * \brief Rotate point 'p' around point 'center' by 'angle' degrees
169 | * \param p
170 | * \param center
171 | * \param angle
172 | * \return
173 | */
174 | static Vector2 rotate(const Vector2& p, const Vector2& center, const real& angle);
175 | /**
176 | * \brief Calculate the projection axis of ellipse in user-define direction.
177 | * \param a
178 | * \param b
179 | * \param direction
180 | * \return the maximum point in ellipse
181 | */
182 | static Vector2 calculateEllipseProjectionPoint(const real& a, const real& b, const Vector2& direction);
183 | static Vector2 calculateCapsuleProjectionPoint(const real& halfWidth, const real& halfHeight, const Vector2& direction);
184 | static Vector2 calculateSectorProjectionPoint(const real& startRadian, const real& spanRadian, const real& radius, const Vector2& direction);
185 | static bool triangleContainsOrigin(const Vector2& a, const Vector2& b, const Vector2& c);
186 | static bool isPointOnSameSide(const Vector2& edgePoint1, const Vector2& edgePoint2, const Vector2& refPoint, const Vector2 targetPoint);
187 | /**
188 | * \brief calculate normal of line segment with direction of refDirection
189 | * \param edgePoint1
190 | * \param edgePoint2
191 | * \param refDirection
192 | * \return
193 | */
194 | static Vector2 lineSegmentNormal(const Vector2& edgePoint1, const Vector2& edgePoint2, const Vector2& refDirection);
195 | /**
196 | * \brief calculate point on line segment ab that is the shortest length to point p
197 | * \param a point a
198 | * \param b point b
199 | * \param p target point
200 | * \return
201 | */
202 | static Vector2 pointToLineSegment(const Vector2& a, const Vector2& b, const Vector2& p);
203 | /**
204 | * \brief ray-ray intersection with no exception check, be sure two rays must can intersect.
205 | * \param p1
206 | * \param dir1
207 | * \param p2
208 | * \param dir2
209 | * \return
210 | */
211 | static Vector2 rayRayIntersectionUnsafe(const Vector2& p1, const Vector2& dir1, const Vector2& p2, const Vector2& dir2);
212 | };
213 | }
214 | #endif
215 |
--------------------------------------------------------------------------------
/Physics2D/include/physics2d_body.h:
--------------------------------------------------------------------------------
1 | #ifndef PHYSICS2D_BODY_H
2 | #define PHYSICS2D_BODY_H
3 | #include "physics2d_aabb.h"
4 | #include "physics2d_math.h"
5 | #include "physics2d_common.h"
6 | #include "physics2d_shape.h"
7 | #include "physics2d_integrator.h"
8 |
9 | #include "physics2d_capsule.h"
10 | #include "physics2d_circle.h"
11 |
12 | #include "physics2d_edge.h"
13 | #include "physics2d_ellipse.h"
14 | #include "physics2d_polygon.h"
15 | #include "physics2d_rectangle.h"
16 |
17 |
18 | namespace Physics2D
19 | {
20 | class PHYSICS2D_API Body
21 | {
22 | public:
23 | struct PHYSICS2D_API BodyPair
24 | {
25 | using BodyPairID = uint64_t;
26 | static BodyPairID generateBodyPairID(Body* bodyA, Body* bodyB);
27 | static BodyPair generateBodyPair(Body* bodyA, Body* bodyB);
28 | BodyPairID pairID;
29 | Body* bodyA;
30 | Body* bodyB;
31 | };
32 |
33 | enum class PHYSICS2D_API BodyType
34 | {
35 | Kinematic,
36 | Static,
37 | Dynamic,
38 | Bullet
39 | };
40 |
41 | struct PHYSICS2D_API PhysicsAttribute
42 | {
43 | Vector2 position;
44 | Vector2 velocity;
45 | real rotation = 0;
46 | real angularVelocity = 0;
47 | void step(const real& dt);
48 | };
49 |
50 | Body() = default;
51 | Vector2& position();
52 |
53 | Vector2& velocity();
54 |
55 | real& rotation();
56 |
57 | real& angularVelocity();
58 |
59 | Vector2& forces();
60 | void clearTorque();
61 |
62 | real& torques();
63 |
64 | Vector2& lastPosition();
65 | real& lastRotation();
66 | uint32_t& sleepCountdown();
67 |
68 | Shape* shape() const;
69 | void setShape(Shape* shape);
70 |
71 | BodyType type() const;
72 | void setType(const BodyType& type);
73 |
74 | real mass() const;
75 | void setMass(const real& mass);
76 |
77 | real inertia() const;
78 |
79 | AABB aabb(const real& factor = Constant::AABBExpansionFactor) const;
80 |
81 | real friction() const;
82 | void setFriction(const real& friction);
83 |
84 | bool sleep() const;
85 | void setSleep(bool sleep);
86 |
87 | real inverseMass() const;
88 | real inverseInertia() const;
89 |
90 | PhysicsAttribute physicsAttribute() const;
91 | void setPhysicsAttribute(const PhysicsAttribute& info);
92 |
93 | void stepPosition(const real& dt);
94 |
95 | void applyImpulse(const Vector2& impulse, const Vector2& r);
96 | Vector2 toLocalPoint(const Vector2& point) const;
97 | Vector2 toWorldPoint(const Vector2& point) const;
98 | Vector2 toActualPoint(const Vector2& point) const;
99 |
100 | uint32_t id() const;
101 | void setId(const uint32_t& id);
102 |
103 | uint32_t bitmask() const;
104 | void setBitmask(const uint32_t& bitmask);
105 |
106 | real restitution() const;
107 | void setRestitution(const real& restitution);
108 |
109 | real kineticEnergy() const;
110 |
111 | private:
112 | void calcInertia();
113 |
114 | uint32_t m_id;
115 | uint32_t m_bitmask = 1;
116 |
117 | real m_mass = 0;
118 | real m_inertia = 0;
119 | real m_invMass = 0;
120 | real m_invInertia = 0;
121 |
122 | Vector2 m_position;
123 | Vector2 m_velocity;
124 | real m_rotation = 0;
125 | real m_angularVelocity = 0;
126 |
127 | Vector2 m_lastPosition;
128 | real m_lastRotation = 0;
129 |
130 | Vector2 m_forces;
131 | real m_torques = 0;
132 |
133 | Shape* m_shape;
134 | BodyType m_type = BodyType::Static;
135 |
136 | bool m_sleep = false;
137 | real m_friction = 0.1f;
138 | real m_restitution = 0.0f;
139 |
140 | uint32_t m_sleepCountdown = 0;
141 | };
142 | }
143 | #endif
144 |
--------------------------------------------------------------------------------
/Physics2D/include/physics2d_capsule.h:
--------------------------------------------------------------------------------
1 | #ifndef PHYSICS2D_SHAPE_CAPSULE_H
2 | #define PHYSICS2D_SHAPE_CAPSULE_H
3 | #include "physics2d_shape.h"
4 | namespace Physics2D
5 | {
6 | class PHYSICS2D_API Capsule : public Shape
7 | {
8 | public:
9 | Capsule(real width = 0.0f, real height = 0.0f);
10 | bool contains(const Vector2& point, const real& epsilon) override;
11 | void scale(const real& factor) override;
12 | Vector2 center() const override;
13 | void set(real width, real height);
14 | void setWidth(real width);
15 | void setHeight(real height);
16 | real width()const;
17 | real height()const;
18 | real halfWidth()const;
19 | real halfHeight()const;
20 | Vector2 topLeft()const;
21 | Vector2 bottomLeft()const;
22 | Vector2 topRight()const;
23 | Vector2 bottomRight()const;
24 | Container::Vector boxVertices()const;
25 | private:
26 |
27 | real m_halfWidth;
28 | real m_halfHeight;
29 | };
30 | }
31 | #endif
--------------------------------------------------------------------------------
/Physics2D/include/physics2d_ccd.h:
--------------------------------------------------------------------------------
1 | #ifndef PHYSICS2D_COLLISION_CCD_H
2 | #define PHYSICS2D_COLLISION_CCD_H
3 | #include "physics2d_detector.h"
4 |
5 | #include "physics2d_body.h"
6 | #include "physics2d_grid.h"
7 | #include "physics2d_tree.h"
8 |
9 | namespace Physics2D
10 | {
11 | ///
12 | /// Continuous Collision Detection
13 | /// This class is implemented by bisection and re-sampling. Both them are costly.
14 | ///
15 | class PHYSICS2D_API CCD
16 | {
17 | public:
18 | struct PHYSICS2D_API AABBShot
19 | {
20 | AABBShot(const AABB& box, const Body::PhysicsAttribute& attr, const real& t) : aabb(box), attribute(attr),
21 | time(t)
22 | {
23 | }
24 |
25 | AABB aabb;
26 | Body::PhysicsAttribute attribute;
27 | real time = 0;
28 | };
29 |
30 | struct PHYSICS2D_API IndexSection
31 | {
32 | int forward = -1;
33 | int backward = -1;
34 | };
35 |
36 | struct PHYSICS2D_API CCDPair
37 | {
38 | CCDPair() = default;
39 |
40 | CCDPair(const real& time, Body* target) : toi(time), body(target)
41 | {
42 | }
43 |
44 | real toi = 0.0;
45 | Body* body = nullptr;
46 | };
47 |
48 | using BroadphaseTrajectory = Container::Vector;
49 | static std::tuple buildTrajectoryAABB(Body* body, const real& dt);
50 | static std::tuple, AABB> buildTrajectoryAABB(
51 | Body* body, const Vector2& target, const real& dt);
52 | static std::optional findBroadphaseRoot(Body* staticBody,
53 | const BroadphaseTrajectory& staticTrajectory,
54 | Body* dynamicBody,
55 | const BroadphaseTrajectory& dynamicTrajectory,
56 | const real& dt);
57 | static std::optional findNarrowphaseRoot(Body* staticBody, const BroadphaseTrajectory& staticTrajectory,
58 | Body* dynamicBody, const BroadphaseTrajectory& dynamicTrajectory,
59 | const IndexSection& index, const real& dt);
60 |
61 | static std::optional> query(Tree& tree, Body* body, const real& dt);
62 | static std::optional> query(UniformGrid& grid, Body* body, const real& dt);
63 | static std::optional earliestTOI(const Container::Vector& pairs,
64 | const real& epsilon = Constant::GeometryEpsilon);
65 | };
66 | }
67 | #endif
68 |
--------------------------------------------------------------------------------
/Physics2D/include/physics2d_circle.h:
--------------------------------------------------------------------------------
1 | #ifndef PHYSICS2D_SHAPE_CIRCLE_H
2 | #define PHYSICS2D_SHAPE_CIRCLE_H
3 | #include "physics2d_shape.h"
4 | namespace Physics2D
5 | {
6 | class PHYSICS2D_API Circle : public Shape
7 | {
8 |
9 | public:
10 | Circle(real radius = 0);
11 |
12 | real radius() const;
13 | void setRadius(const real& radius);
14 | void scale(const real& factor) override;
15 | bool contains(const Vector2& point, const real& epsilon = Constant::GeometryEpsilon) override;
16 | Vector2 center()const override;
17 | private:
18 | real m_radius;
19 | };
20 | }
21 | #endif
--------------------------------------------------------------------------------
/Physics2D/include/physics2d_collider.h:
--------------------------------------------------------------------------------
1 | #ifndef PHYSICS2D_COLLIDER_H
2 | #define PHYSICS2D_COLLIDER_H
3 |
4 | namespace Physics2D
5 | {
6 |
7 | }
8 | #endif
--------------------------------------------------------------------------------
/Physics2D/include/physics2d_common.h:
--------------------------------------------------------------------------------
1 | #ifndef PHYSICS2D_COMMON_H
2 | #define PHYSICS2D_COMMON_H
3 |
4 |
5 | #include "cassert"
6 | #include
7 | #include
8 | #include
9 | #include
10 | #include
11 | #include
12 | #include
13 | #include
14 | #include