GLS.NGDManager.pas 96 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533253425352536253725382539254025412542254325442545254625472548254925502551255225532554255525562557255825592560256125622563256425652566256725682569257025712572257325742575257625772578257925802581258225832584258525862587258825892590259125922593259425952596259725982599260026012602260326042605260626072608260926102611261226132614261526162617261826192620262126222623262426252626262726282629263026312632263326342635263626372638263926402641264226432644264526462647264826492650265126522653265426552656265726582659266026612662266326642665266626672668266926702671267226732674267526762677267826792680268126822683268426852686268726882689269026912692269326942695269626972698269927002701270227032704270527062707270827092710271127122713271427152716271727182719272027212722272327242725272627272728272927302731273227332734273527362737273827392740274127422743274427452746274727482749275027512752275327542755275627572758275927602761276227632764276527662767276827692770277127722773277427752776277727782779278027812782278327842785278627872788278927902791279227932794279527962797279827992800280128022803280428052806280728082809281028112812281328142815281628172818281928202821282228232824282528262827282828292830283128322833283428352836283728382839284028412842284328442845284628472848284928502851285228532854285528562857285828592860286128622863286428652866286728682869287028712872287328742875287628772878287928802881288228832884288528862887288828892890289128922893289428952896289728982899290029012902290329042905290629072908290929102911291229132914291529162917291829192920292129222923292429252926292729282929293029312932293329342935293629372938293929402941294229432944294529462947294829492950295129522953
  1. //
  2. // The graphics engine GLScene
  3. //
  4. unit GLS.NGDManager;
  5. (*
  6. The Newton Game Dynamics Manager for GLScene.
  7. Notes: This code is still under development so any part of it may change at anytime.
  8. *)
  9. interface
  10. {.$I GLS.Scene.inc }
  11. uses
  12. System.Classes, // TComponent TList TWriter TReader TPersistent
  13. System.SysUtils,
  14. System.Math, // Samevalue isZero to compare single
  15. System.Types,
  16. NGD.Import,
  17. /// NGD.Joints, // old joints
  18. /// Physics.NewtonImport, // new version 4.0
  19. Stage.VectorTypes,
  20. Stage.VectorGeometry, // PGLVector TGLVector TGLMatrix PGLMatrix NullHmgVector...
  21. GLS.VectorLists, // TGLAffineVectorList for Tree
  22. GLS.XCollection, // TXCollection file function
  23. GLS.GeometryBB, // For show debug
  24. GLS.BaseClasses,
  25. GLS.PersistentClasses,
  26. GLS.Scene,
  27. Stage.Manager,
  28. GLS.Coordinates,
  29. GLS.Objects,
  30. GLS.GeomObjects,
  31. GLS.VectorFileObjects, // cube cone freeform...
  32. GLS.Color;
  33. type
  34. TGLNGDHeightField = record
  35. heightArray: array of Word;
  36. width: Integer;
  37. depth: Integer;
  38. gridDiagonals: Boolean;
  39. widthDepthScale: Single;
  40. heightScale: Single;
  41. end;
  42. TGLNGDBehaviour = class;
  43. TGLNGDManager = class;
  44. TGLNGDSurfaceItem = class;
  45. TGLNGDJoint = class;
  46. TGLNGDSolverModels = (smExact = 0, smLinear1, smLinear2, smLinear3, smLinear4, smLinear5,
  47. smLinear6, smLinear7, smLinear8, smLinear9);
  48. TGLNGDFrictionModels = (fmExact = 0, fmAdaptive);
  49. TGLNGDPickedActions = (paAttach = 0, paMove, paDetach);
  50. TGLNGDManagerDebug = (mdShowGeometry, mdShowAABB, mdShowCenterOfMass, mdShowContact, mdShowJoint,
  51. mdShowForce, mdShowAppliedForce, mdShowAppliedVelocity);
  52. TGLNGDManagerDebugs = set of TGLNGDManagerDebug;
  53. TGLNGDCollisions = (nc_Primitive = 0, nc_Convex, nc_BBox, nc_BSphere, nc_Tree, nc_Mesh, nc_Null,
  54. nc_HeightField, nc_NGDFile);
  55. TGLNGDJoints = (nj_BallAndSocket, nj_Hinge, nj_Slider, nj_Corkscrew, nj_Universal,
  56. nj_CustomBallAndSocket, nj_CustomHinge, nj_CustomSlider, nj_UpVector, nj_KinematicController);
  57. TGLNGDBehaviourList = class(TList)
  58. protected
  59. function GetBehav(index: Integer): TGLNGDBehaviour;
  60. procedure PutBehav(index: Integer; Item: TGLNGDBehaviour);
  61. public
  62. property ItemsBehav[index: Integer]: TGLNGDBehaviour read GetBehav write PutBehav; default;
  63. end;
  64. // Events for Newton Callback
  65. TCollisionIteratorEvent = procedure(const userData: Pointer; vertexCount: Integer;
  66. const cfaceArray: PdFloat; faceId: Integer) of object;
  67. TApplyForceAndTorqueEvent = procedure(const cbody: PNewtonBody; timestep: dFloat;
  68. threadIndex: Integer) of object;
  69. TSetTransformEvent = procedure(const cbody: PNewtonBody; const cmatrix: PdFloat;
  70. threadIndex: Integer) of object;
  71. TSerializeEvent = procedure(serializeHandle: Pointer; const cbuffer: Pointer; size: Cardinal)
  72. of object;
  73. TDeSerializeEvent = procedure(serializeHandle: Pointer; buffer: Pointer; size: Cardinal)
  74. of object;
  75. TAABBOverlapEvent = function(const cmaterial: PNewtonMaterial; const cbody0: PNewtonBody;
  76. const cbody1: PNewtonBody; threadIndex: Integer): Boolean of object;
  77. TContactProcessEvent = procedure(const ccontact: PNewtonJoint; timestep: dFloat;
  78. threadIndex: Integer) of object;
  79. TGLNGDDebugOption = class(TPersistent)
  80. strict private
  81. FManager: TGLNGDManager;
  82. FGeomColorDyn: TGLColor; // Green
  83. FGeomColorStat: TGLColor; // Red
  84. FAABBColor: TGLColor; // Yellow
  85. FAABBColorSleep: TGLColor; // Orange
  86. FCenterOfMassColor: TGLColor; // Purple dot
  87. FContactColor: TGLColor; // White
  88. FJointAxisColor: TGLColor; // Blue
  89. FJointPivotColor: TGLColor; // Aquamarine
  90. FForceColor: TGLColor; // Black
  91. FAppliedForceColor: TGLColor; // Silver
  92. FAppliedVelocityColor: TGLColor; // Lime
  93. FCustomColor: TGLColor; // Aqua
  94. FDotAxisSize: Single; // 1
  95. FManagerDebugs: TGLNGDManagerDebugs; // Default All false
  96. procedure SetManagerDebugs(const Value: TGLNGDManagerDebugs);
  97. procedure SetDotAxisSize(const Value: Single);
  98. function StoredDotAxis: Boolean;
  99. public
  100. constructor Create(AOwner: TComponent);
  101. destructor Destroy; override;
  102. published
  103. property GeomColorDyn: TGLColor read FGeomColorDyn write FGeomColorDyn;
  104. property GeomColorStat: TGLColor read FGeomColorStat write FGeomColorStat;
  105. property AABBColor: TGLColor read FAABBColor write FAABBColor;
  106. property AABBColorSleep: TGLColor read FAABBColorSleep write FAABBColorSleep;
  107. property CenterOfMassColor: TGLColor read FCenterOfMassColor write FCenterOfMassColor;
  108. property ContactColor: TGLColor read FContactColor write FContactColor;
  109. property JointAxisColor: TGLColor read FJointAxisColor write FJointAxisColor;
  110. property JointPivotColor: TGLColor read FJointPivotColor write FJointPivotColor;
  111. property ForceColor: TGLColor read FForceColor write FForceColor;
  112. property AppliedForceColor: TGLColor read FAppliedForceColor write FAppliedForceColor;
  113. property AppliedVelocityColor: TGLColor read FAppliedVelocityColor write FAppliedVelocityColor;
  114. property CustomColor: TGLColor read FCustomColor write FCustomColor;
  115. property NGDManagerDebugs: TGLNGDManagerDebugs read FManagerDebugs write SetManagerDebugs
  116. default [];
  117. property DotAxisSize: Single read FDotAxisSize write SetDotAxisSize stored StoredDotAxis;
  118. end;
  119. TGLNGDManager = class(TComponent)
  120. strict private
  121. FVisible: Boolean; // Show Debug at design time
  122. FVisibleAtRunTime: Boolean; // Show Debug at run time
  123. FDllVersion: Integer;
  124. FSolverModel: TGLNGDSolverModels; // Default=Exact
  125. FFrictionModel: TGLNGDFrictionModels; // Default=Exact
  126. FMinimumFrameRate: Integer; // Default=60
  127. FWorldSizeMin: TGLCoordinates; // Default=-100, -100, -100
  128. FWorldSizeMax: TGLCoordinates; // Default=100, 100, 100
  129. FThreadCount: Integer; // Default=1
  130. FGravity: TGLCoordinates; // Default=(0,-9.81,0)
  131. FNewtonSurfaceItem: TCollection;
  132. FNewtonSurfacePair: TOwnedCollection;
  133. FNewtonJointGroup: TOwnedCollection;
  134. FNewtonDebugOption: TGLNGDDebugOption;
  135. FGLLines: TGLLines;
  136. private
  137. FNewtonWorld: PNewtonWorld;
  138. FNGDBehaviours: TGLNGDBehaviourList;
  139. FCurrentColor: TGLColor;
  140. protected
  141. procedure Loaded; override;
  142. procedure SetVisible(const Value: Boolean);
  143. procedure SetVisibleAtRunTime(const Value: Boolean);
  144. procedure SetSolverModel(const Value: TGLNGDSolverModels);
  145. procedure SetFrictionModel(const Value: TGLNGDFrictionModels);
  146. procedure SetMinimumFrameRate(const Value: Integer);
  147. procedure SetThreadCount(const Value: Integer);
  148. procedure SetGLLines(const Value: TGLLines);
  149. function GetBodyCount: Integer;
  150. function GetConstraintCount: Integer;
  151. procedure AddNode(const coords: TGLCustomCoordinates); overload;
  152. procedure AddNode(const X, Y, Z: Single); overload;
  153. procedure AddNode(const Value: TGLVector); overload;
  154. procedure AddNode(const Value: TAffineVector); overload;
  155. procedure RebuildAllMaterial;
  156. procedure RebuildAllJoint(Sender: TObject);
  157. // Events
  158. procedure NotifyWorldSizeChange(Sender: TObject);
  159. procedure NotifyChange(Sender: TObject); // Debug view
  160. public
  161. constructor Create(AOwner: TComponent); override;
  162. destructor Destroy; override;
  163. procedure Step(deltatime: Single);
  164. published
  165. property Visible: Boolean read FVisible write SetVisible default True;
  166. property VisibleAtRunTime: Boolean read FVisibleAtRunTime write SetVisibleAtRunTime
  167. default False;
  168. property SolverModel: TGLNGDSolverModels read FSolverModel write SetSolverModel default smExact;
  169. property FrictionModel: TGLNGDFrictionModels read FFrictionModel write SetFrictionModel
  170. default fmExact;
  171. property MinimumFrameRate: Integer read FMinimumFrameRate write SetMinimumFrameRate default 60;
  172. property ThreadCount: Integer read FThreadCount write SetThreadCount default 1;
  173. property DllVersion: Integer read FDllVersion;
  174. property NewtonBodyCount: Integer read GetBodyCount;
  175. property NewtonConstraintCount: Integer read GetConstraintCount;
  176. property Gravity: TGLCoordinates read FGravity write FGravity;
  177. property WorldSizeMin: TGLCoordinates read FWorldSizeMin write FWorldSizeMin;
  178. property WorldSizeMax: TGLCoordinates read FWorldSizeMax write FWorldSizeMax;
  179. property NewtonSurfaceItem: TCollection read FNewtonSurfaceItem write FNewtonSurfaceItem;
  180. property NewtonSurfacePair: TOwnedCollection read FNewtonSurfacePair write FNewtonSurfacePair;
  181. property DebugOption: TGLNGDDebugOption read FNewtonDebugOption write FNewtonDebugOption;
  182. property Line: TGLLines read FGLLines write SetGLLines;
  183. property NewtonJoint: TOwnedCollection read FNewtonJointGroup write FNewtonJointGroup;
  184. end;
  185. // Basis structures for Behaviour style implementations.
  186. TGLNGDBehaviour = class(TGLBehaviour)
  187. private
  188. FManager: TGLNGDManager;
  189. FManagerName: string;
  190. FInitialized: Boolean;
  191. FNewtonBody: PNewtonBody;
  192. FCollision: PNewtonCollision;
  193. FNewtonBodyMatrix: TGLMatrix; // Position and Orientation
  194. FContinuousCollisionMode: Boolean; // Default=False
  195. FNewtonCollisions: TGLNGDCollisions;
  196. FCollisionIteratorEvent: TCollisionIteratorEvent;
  197. FOwnerBaseSceneObject: TGLBaseSceneObject;
  198. // FNullCollisionMass: Single; // Default=0
  199. FTreeCollisionOptimize: Boolean; // Default=True
  200. FConvexCollisionTolerance: Single; // Default=0.01 1%
  201. FFileCollision: string;
  202. FSurfaceItem: TGLNGDSurfaceItem;
  203. FHeightFieldOptions: TGLNGDHeightField;
  204. protected
  205. procedure Initialize; virtual;
  206. procedure Finalize; virtual;
  207. procedure WriteToFiler(writer: TWriter); override;
  208. procedure ReadFromFiler(reader: TReader); override;
  209. procedure Loaded; override;
  210. procedure SetManager(Value: TGLNGDManager);
  211. procedure SetNewtonBodyMatrix(const Value: TGLMatrix);
  212. procedure SetContinuousCollisionMode(const Value: Boolean);
  213. function GetNewtonBodyMatrix: TGLMatrix;
  214. function GetNewtonBodyAABB: TAABB;
  215. procedure UpdCollision; virtual;
  216. procedure Render; virtual;
  217. procedure SetNewtonCollisions(const Value: TGLNGDCollisions);
  218. procedure SetNewtonSurfaceItem(const Value: TGLNGDSurfaceItem);
  219. procedure SetHeightFieldOptions(const Value: TGLNGDHeightField);
  220. function GetPrimitiveCollision(): PNewtonCollision;
  221. function GetConvexCollision(): PNewtonCollision;
  222. function GetBBoxCollision(): PNewtonCollision;
  223. function GetBSphereCollision(): PNewtonCollision;
  224. function GetTreeCollision(): PNewtonCollision;
  225. function GetMeshCollision(): PNewtonCollision;
  226. function GetNullCollision(): PNewtonCollision;
  227. function GetHeightFieldCollision(): PNewtonCollision;
  228. function GetNGDFileCollision(): PNewtonCollision;
  229. function StoredTolerance: Boolean;
  230. // Event
  231. procedure OnCollisionIteratorEvent(const userData: Pointer; vertexCount: Integer;
  232. const cfaceArray: PdFloat; faceId: Integer);
  233. // CallBack
  234. class procedure NewtonCollisionIterator(const userData: Pointer; vertexCount: Integer;
  235. const faceArray: PdFloat; faceId: Integer); static; cdecl;
  236. class procedure NewtonSerialize(serializeHandle: Pointer; const buffer: Pointer;
  237. size: Cardinal); static; cdecl;
  238. class procedure NewtonDeserialize(serializeHandle: Pointer; buffer: Pointer; size: Cardinal);
  239. static; cdecl;
  240. public
  241. constructor Create(AOwner: TXCollection); override;
  242. destructor Destroy; override;
  243. procedure Reinitialize;
  244. property Initialized: Boolean read FInitialized;
  245. class function UniqueItem: Boolean; override;
  246. property NewtonBodyMatrix: TGLMatrix read GetNewtonBodyMatrix write SetNewtonBodyMatrix;
  247. property NewtonBodyAABB: TAABB read GetNewtonBodyAABB;
  248. procedure Serialize(filename: string);
  249. procedure DeSerialize(filename: string);
  250. property HeightFieldOptions: TGLNGDHeightField read FHeightFieldOptions
  251. write SetHeightFieldOptions;
  252. published
  253. property Manager: TGLNGDManager read FManager write SetManager;
  254. property ContinuousCollisionMode: Boolean read FContinuousCollisionMode
  255. write SetContinuousCollisionMode default False;
  256. property NGDNewtonCollisions: TGLNGDCollisions read FNewtonCollisions write SetNewtonCollisions
  257. default nc_Primitive;
  258. property TreeCollisionOptimize: Boolean read FTreeCollisionOptimize write FTreeCollisionOptimize
  259. default True;
  260. property ConvexCollisionTolerance: Single read FConvexCollisionTolerance
  261. write FConvexCollisionTolerance stored StoredTolerance;
  262. property FileCollision: string read FFileCollision write FFileCollision;
  263. property NGDSurfaceItem: TGLNGDSurfaceItem read FSurfaceItem write SetNewtonSurfaceItem;
  264. end;
  265. TGLNGDDynamic = class(TGLNGDBehaviour)
  266. strict private
  267. FAABBmin: TGLCoordinates;
  268. FAABBmax: TGLCoordinates;
  269. FForce: TGLCoordinates;
  270. FTorque: TGLCoordinates;
  271. FCenterOfMass: TGLCoordinates;
  272. FAutoSleep: Boolean; // Default=True
  273. FLinearDamping: Single; // default=0.1
  274. FAngularDamping: TGLCoordinates; // Default=0.1
  275. FDensity: Single; // Default=1
  276. FUseGravity: Boolean; // Default=True
  277. FNullCollisionVolume: Single; // Default=0
  278. FApplyForceAndTorqueEvent: TApplyForceAndTorqueEvent;
  279. FSetTransformEvent: TSetTransformEvent;
  280. FCustomForceAndTorqueEvent: TApplyForceAndTorqueEvent;
  281. // Read Only
  282. FVolume: Single;
  283. FMass: Single;
  284. FAppliedForce: TGLCoordinates;
  285. FAppliedTorque: TGLCoordinates;
  286. FAppliedOmega: TGLCoordinates;
  287. FAppliedVelocity: TGLCoordinates;
  288. function StoredDensity: Boolean;
  289. function StoredLinearDamping: Boolean;
  290. function StoredNullCollisionVolume: Boolean;
  291. protected
  292. procedure SetAutoSleep(const Value: Boolean);
  293. procedure SetLinearDamping(const Value: Single);
  294. procedure SetDensity(const Value: Single); virtual;
  295. procedure Initialize; override;
  296. procedure Finalize; override;
  297. procedure WriteToFiler(writer: TWriter); override;
  298. procedure ReadFromFiler(reader: TReader); override;
  299. procedure Loaded; override;
  300. procedure Render; override;
  301. // Events
  302. procedure NotifyCenterOfMassChange(Sender: TObject);
  303. procedure NotifyAngularDampingChange(Sender: TObject);
  304. procedure OnApplyForceAndTorqueEvent(const cbody: PNewtonBody; timestep: dFloat;
  305. threadIndex: Integer);
  306. procedure OnSetTransformEvent(const cbody: PNewtonBody; const cmatrix: PdFloat;
  307. threadIndex: Integer);
  308. // Callback
  309. class procedure NewtonApplyForceAndTorque(const body: PNewtonBody; timestep: dFloat;
  310. threadIndex: Integer); static; cdecl;
  311. class procedure NewtonSetTransform(const body: PNewtonBody; const matrix: PdFloat;
  312. threadIndex: Integer); static; cdecl;
  313. public
  314. constructor Create(AOwner: TXCollection); override;
  315. destructor Destroy; override;
  316. procedure AddImpulse(const veloc, pointposit: TGLVector);
  317. function GetOmega: TGLVector;
  318. procedure SetOmega(const Omega: TGLVector);
  319. function GetVelocity: TGLVector;
  320. procedure SetVelocity(const Velocity: TGLVector);
  321. class function FriendlyName: string; override;
  322. property CustomForceAndTorqueEvent: TApplyForceAndTorqueEvent read FCustomForceAndTorqueEvent
  323. write FCustomForceAndTorqueEvent;
  324. property Velocity: TGLVector read GetVelocity write SetVelocity;
  325. property Omega: TGLVector read GetOmega write SetOmega;
  326. published
  327. property Force: TGLCoordinates read FForce write FForce;
  328. property Torque: TGLCoordinates read FTorque write FTorque;
  329. property CenterOfMass: TGLCoordinates read FCenterOfMass write FCenterOfMass;
  330. property AutoSleep: Boolean read FAutoSleep write SetAutoSleep default True;
  331. property LinearDamping: Single read FLinearDamping write SetLinearDamping
  332. stored StoredLinearDamping;
  333. property AngularDamping: TGLCoordinates read FAngularDamping write FAngularDamping;
  334. property Density: Single read FDensity write SetDensity stored StoredDensity;
  335. property UseGravity: Boolean read FUseGravity write FUseGravity default True;
  336. property NullCollisionVolume: Single read FNullCollisionVolume write FNullCollisionVolume
  337. stored StoredNullCollisionVolume;
  338. // Read Only
  339. property AppliedOmega: TGLCoordinates read FAppliedOmega;
  340. property AppliedVelocity: TGLCoordinates read FAppliedVelocity;
  341. property AppliedForce: TGLCoordinates read FAppliedForce;
  342. property AppliedTorque: TGLCoordinates read FAppliedTorque;
  343. property Volume: Single read FVolume;
  344. property Mass: Single read FMass;
  345. end;
  346. TGLNGDStatic = class(TGLNGDBehaviour)
  347. protected
  348. procedure Render; override;
  349. public
  350. class function FriendlyName: string; override;
  351. published
  352. end;
  353. TGLNGDSurfaceItem = class(TCollectionItem)
  354. private
  355. FDisplayName: string;
  356. protected
  357. function GetDisplayName: string; override;
  358. procedure SetDisplayName(const Value: string); override;
  359. published
  360. property DisplayName;
  361. property ID;
  362. end;
  363. TGLNGDSurfacePair = class(TCollectionItem)
  364. strict private
  365. FManager: TGLNGDManager;
  366. FSurfaceItem1: TGLNGDSurfaceItem;
  367. FSurfaceItem2: TGLNGDSurfaceItem;
  368. FAABBOverlapEvent: TAABBOverlapEvent;
  369. FContactProcessEvent: TContactProcessEvent;
  370. FSoftness: Single; // 0.1
  371. FElasticity: Single; // 0.4
  372. FCollidable: Boolean; // true
  373. FStaticFriction: Single; // 0.9
  374. FKineticFriction: Single; // 0.5
  375. FContinuousCollisionMode: Boolean; // False
  376. FThickness: Boolean; // False
  377. procedure SetCollidable(const Value: Boolean);
  378. procedure SetElasticity(const Value: Single);
  379. procedure SetKineticFriction(const Value: Single);
  380. procedure SetSoftness(const Value: Single);
  381. procedure SetStaticFriction(const Value: Single);
  382. procedure SetContinuousCollisionMode(const Value: Boolean);
  383. procedure SetThickness(const Value: Boolean);
  384. function StoredElasticity: Boolean;
  385. function StoredKineticFriction: Boolean;
  386. function StoredSoftness: Boolean;
  387. function StoredStaticFriction: Boolean;
  388. private
  389. // Callback
  390. class function NewtonAABBOverlap(const material: PNewtonMaterial; const body0: PNewtonBody;
  391. const body1: PNewtonBody; threadIndex: Integer): Integer; static; cdecl;
  392. class procedure NewtonContactsProcess(const contact: PNewtonJoint; timestep: dFloat;
  393. threadIndex: Integer); static; cdecl;
  394. // Event
  395. function OnNewtonAABBOverlapEvent(const cmaterial: PNewtonMaterial; const cbody0: PNewtonBody;
  396. const cbody1: PNewtonBody; threadIndex: Integer): Boolean;
  397. procedure OnNewtonContactsProcessEvent(const ccontact: PNewtonJoint; timestep: dFloat;
  398. threadIndex: Integer);
  399. public
  400. constructor Create(Collection: TCollection); override;
  401. procedure SetMaterialItems(const item1, item2: TGLNGDSurfaceItem);
  402. property NGDSurfaceItem1: TGLNGDSurfaceItem read FSurfaceItem1;
  403. property NGDSurfaceItem2: TGLNGDSurfaceItem read FSurfaceItem2;
  404. published
  405. property Softness: Single read FSoftness write SetSoftness stored StoredSoftness;
  406. property Elasticity: Single read FElasticity write SetElasticity stored StoredElasticity;
  407. property Collidable: Boolean read FCollidable write SetCollidable default True;
  408. property StaticFriction: Single read FStaticFriction write SetStaticFriction
  409. stored StoredStaticFriction;
  410. property KineticFriction: Single read FKineticFriction write SetKineticFriction
  411. stored StoredKineticFriction;
  412. property ContinuousCollisionMode: Boolean read FContinuousCollisionMode
  413. write SetContinuousCollisionMode default False;
  414. property Thickness: Boolean read FThickness write SetThickness default False;
  415. property ContactProcessEvent: TContactProcessEvent read FContactProcessEvent
  416. write FContactProcessEvent;
  417. property AABBOverlapEvent: TAABBOverlapEvent read FAABBOverlapEvent write FAABBOverlapEvent;
  418. end;
  419. TGLNGDJointPivot = class(TPersistent)
  420. private
  421. FManager: TGLNGDManager;
  422. FPivotPoint: TGLCoordinates;
  423. FOuter: TGLNGDJoint;
  424. public
  425. constructor Create(AOwner: TComponent; aOuter: TGLNGDJoint); virtual;
  426. destructor Destroy; override;
  427. published
  428. property PivotPoint: TGLCoordinates read FPivotPoint write FPivotPoint;
  429. end;
  430. TGLNGDJointPin = class(TGLNGDJointPivot)
  431. private
  432. FPinDirection: TGLCoordinates;
  433. public
  434. constructor Create(AOwner: TComponent; aOuter: TGLNGDJoint); override;
  435. destructor Destroy; override;
  436. published
  437. property PinDirection: TGLCoordinates read FPinDirection write FPinDirection;
  438. end;
  439. TGLNGDJointPin2 = class(TGLNGDJointPin)
  440. private
  441. FPinDirection2: TGLCoordinates;
  442. public
  443. constructor Create(AOwner: TComponent; aOuter: TGLNGDJoint); override;
  444. destructor Destroy; override;
  445. published
  446. property PinDirection2: TGLCoordinates read FPinDirection2 write FPinDirection2;
  447. end;
  448. TGLNGDJointBallAndSocket = class(TGLNGDJointPivot)
  449. private
  450. FConeAngle: Single; // 90
  451. FMinTwistAngle: Single; // -90
  452. FMaxTwistAngle: Single; // 90
  453. procedure SetConeAngle(const Value: Single);
  454. procedure SetMaxTwistAngle(const Value: Single);
  455. procedure SetMinTwistAngle(const Value: Single);
  456. function StoredMaxTwistAngle: Boolean;
  457. function StoredMinTwistAngle: Boolean;
  458. function StoredConeAngle: Boolean;
  459. public
  460. constructor Create(AOwner: TComponent; aOuter: TGLNGDJoint); override;
  461. published
  462. property ConeAngle: Single read FConeAngle write SetConeAngle stored StoredConeAngle;
  463. property MinTwistAngle: Single read FMinTwistAngle write SetMinTwistAngle
  464. stored StoredMinTwistAngle;
  465. property MaxTwistAngle: Single read FMaxTwistAngle write SetMaxTwistAngle
  466. stored StoredMaxTwistAngle;
  467. end;
  468. TGLNGDJointHinge = class(TGLNGDJointPin)
  469. private
  470. FMinAngle: Single; // -90
  471. FMaxAngle: Single; // 90
  472. procedure SetMaxAngle(const Value: Single);
  473. procedure SetMinAngle(const Value: Single);
  474. function StoredMaxAngle: Boolean;
  475. function StoredMinAngle: Boolean;
  476. public
  477. constructor Create(AOwner: TComponent; aOuter: TGLNGDJoint); override;
  478. published
  479. property MinAngle: Single read FMinAngle write SetMinAngle stored StoredMinAngle;
  480. property MaxAngle: Single read FMaxAngle write SetMaxAngle stored StoredMaxAngle;
  481. end;
  482. TGLNGDJointSlider = class(TGLNGDJointPin)
  483. private
  484. FMinDistance: Single; // -10
  485. FMaxDistance: Single; // 10
  486. procedure SetMaxDistance(const Value: Single);
  487. procedure SetMinDistance(const Value: Single);
  488. function StoredMaxDistance: Boolean;
  489. function StoredMinDistance: Boolean;
  490. public
  491. constructor Create(AOwner: TComponent; aOuter: TGLNGDJoint); override;
  492. published
  493. property MinDistance: Single read FMinDistance write SetMinDistance stored StoredMinDistance;
  494. property MaxDistance: Single read FMaxDistance write SetMaxDistance stored StoredMaxDistance;
  495. end;
  496. TGLNGDJointKinematicController = class(TPersistent)
  497. private
  498. FPickModeLinear: Boolean; // False
  499. FLinearFriction: Single; // 750
  500. FAngularFriction: Single; // 250
  501. function StoredAngularFriction: Boolean;
  502. function StoredLinearFriction: Boolean;
  503. public
  504. constructor Create();
  505. published
  506. property PickModeLinear: Boolean read FPickModeLinear write FPickModeLinear default False;
  507. property LinearFriction: Single read FLinearFriction write FLinearFriction
  508. stored StoredLinearFriction;
  509. property AngularFriction: Single read FAngularFriction write FAngularFriction
  510. stored StoredAngularFriction;
  511. end;
  512. TGLNGDJoint = class(TCollectionItem)
  513. private
  514. // Global
  515. FManager: TGLNGDManager;
  516. FParentObject: TGLBaseSceneObject;
  517. FJointType: TGLNGDJoints;
  518. FStiffness: Single; // 0.9
  519. // With Two object
  520. // Every joint except nj_UpVector and nj_KinematicController
  521. FChildObject: TGLBaseSceneObject;
  522. FCollisionState: Boolean; // False
  523. // With classic joint
  524. // nj_BallAndSocket, nj_Hinge, nj_Slider, nj_Corkscrew
  525. // nj_Universal, nj_UpVector
  526. FNewtonJoint: PNewtonJoint;
  527. // With CustomJoint
  528. // nj_CustomBallAndSocket, nj_CustomHinge, nj_CustomSlider
  529. // nj_KinematicController
  530. FNewtonUserJoint: Pointer;
  531. // nj_UpVector
  532. FUPVectorDirection: TGLCoordinates;
  533. FBallAndSocketOptions: TGLNGDJointPivot;
  534. FHingeOptions: TGLNGDJointPin;
  535. FSliderOptions: TGLNGDJointPin;
  536. FCorkscrewOptions: TGLNGDJointPin;
  537. FUniversalOptions: TGLNGDJointPin2;
  538. FCustomBallAndSocketOptions: TGLNGDJointBallAndSocket;
  539. FCustomHingeOptions: TGLNGDJointHinge;
  540. FCustomSliderOptions: TGLNGDJointSlider;
  541. FKinematicOptions: TGLNGDJointKinematicController;
  542. procedure SetJointType(const Value: TGLNGDJoints);
  543. procedure SetChildObject(const Value: TGLBaseSceneObject);
  544. procedure SetCollisionState(const Value: Boolean);
  545. procedure SetParentObject(const Value: TGLBaseSceneObject);
  546. procedure SetStiffness(const Value: Single);
  547. procedure Render;
  548. function StoredStiffness: Boolean;
  549. procedure DestroyNewtonData;
  550. public
  551. constructor Create(Collection: TCollection); override;
  552. destructor Destroy; override;
  553. procedure KinematicControllerPick(pickpoint: TGLVector; PickedActions: TGLNGDPickedActions);
  554. published
  555. property BallAndSocketOptions: TGLNGDJointPivot read FBallAndSocketOptions
  556. write FBallAndSocketOptions;
  557. property HingeOptions: TGLNGDJointPin read FHingeOptions write FHingeOptions;
  558. property SliderOptions: TGLNGDJointPin read FSliderOptions write FSliderOptions;
  559. property CorkscrewOptions: TGLNGDJointPin read FCorkscrewOptions write FCorkscrewOptions;
  560. property UniversalOptions: TGLNGDJointPin2 read FUniversalOptions write FUniversalOptions;
  561. property CustomBallAndSocketOptions: TGLNGDJointBallAndSocket read FCustomBallAndSocketOptions
  562. write FCustomBallAndSocketOptions;
  563. property CustomHingeOptions: TGLNGDJointHinge read FCustomHingeOptions
  564. write FCustomHingeOptions;
  565. property CustomSliderOptions: TGLNGDJointSlider read FCustomSliderOptions
  566. write FCustomSliderOptions;
  567. property KinematicControllerOptions: TGLNGDJointKinematicController read FKinematicOptions
  568. write FKinematicOptions;
  569. property JointType: TGLNGDJoints read FJointType write SetJointType;
  570. property ParentObject: TGLBaseSceneObject read FParentObject write SetParentObject;
  571. property ChildObject: TGLBaseSceneObject read FChildObject write SetChildObject;
  572. property CollisionState: Boolean read FCollisionState write SetCollisionState default False;
  573. property Stiffness: Single read FStiffness write SetStiffness stored StoredStiffness;
  574. property UPVectorDirection: TGLCoordinates read FUPVectorDirection write FUPVectorDirection;
  575. end;
  576. // Global function
  577. function GetNGDStatic(Obj: TGLBaseSceneObject): TGLNGDStatic;
  578. function GetOrCreateNGDStatic(Obj: TGLBaseSceneObject): TGLNGDStatic;
  579. function GetNGDDynamic(Obj: TGLBaseSceneObject): TGLNGDDynamic;
  580. function GetOrCreateNGDDynamic(Obj: TGLBaseSceneObject): TGLNGDDynamic;
  581. function GetBodyFromGLSceneObject(Obj: TGLBaseSceneObject): PNewtonBody;
  582. // ----------------------------------------------------------------------
  583. implementation
  584. // ----------------------------------------------------------------------
  585. const
  586. epsilon = 0.0000001; // 1E-07
  587. function GetNGDStatic(Obj: TGLBaseSceneObject): TGLNGDStatic;
  588. begin
  589. Result := TGLNGDStatic(Obj.Behaviours.GetByClass(TGLNGDStatic));
  590. end;
  591. function GetOrCreateNGDStatic(Obj: TGLBaseSceneObject): TGLNGDStatic;
  592. begin
  593. Result := TGLNGDStatic(Obj.GetOrCreateBehaviour(TGLNGDStatic));
  594. end;
  595. function GetNGDDynamic(Obj: TGLBaseSceneObject): TGLNGDDynamic;
  596. begin
  597. Result := TGLNGDDynamic(Obj.Behaviours.GetByClass(TGLNGDDynamic));
  598. end;
  599. function GetOrCreateNGDDynamic(Obj: TGLBaseSceneObject): TGLNGDDynamic;
  600. begin
  601. Result := TGLNGDDynamic(Obj.GetOrCreateBehaviour(TGLNGDDynamic));
  602. end;
  603. function GetBodyFromGLSceneObject(Obj: TGLBaseSceneObject): PNewtonBody;
  604. var
  605. Behaviour: TGLNGDBehaviour;
  606. begin
  607. Behaviour := TGLNGDBehaviour(Obj.Behaviours.GetByClass(TGLNGDBehaviour));
  608. Assert(Behaviour <> nil, 'NGD Behaviour (static or dynamic) is missing for this object');
  609. Result := Behaviour.FNewtonBody;
  610. end;
  611. // -----------------------
  612. // TGLNGDDebugOption
  613. // -----------------------
  614. constructor TGLNGDDebugOption.Create(AOwner: TComponent);
  615. begin
  616. FManager := AOwner as TGLNGDManager;
  617. with FManager do
  618. begin
  619. FGeomColorDyn := TGLColor.CreateInitialized(self, clrGreen, NotifyChange);
  620. FGeomColorStat := TGLColor.CreateInitialized(self, clrRed, NotifyChange);
  621. FAABBColor := TGLColor.CreateInitialized(self, clrYellow, NotifyChange);
  622. FAABBColorSleep := TGLColor.CreateInitialized(self, clrOrange, NotifyChange);
  623. FCenterOfMassColor := TGLColor.CreateInitialized(self, clrPurple, NotifyChange);
  624. FContactColor := TGLColor.CreateInitialized(self, clrWhite, NotifyChange);
  625. FJointAxisColor := TGLColor.CreateInitialized(self, clrBlue, NotifyChange);
  626. FJointPivotColor := TGLColor.CreateInitialized(self, clrAquamarine, NotifyChange);
  627. FForceColor := TGLColor.CreateInitialized(self, clrBlack, NotifyChange);
  628. FAppliedForceColor := TGLColor.CreateInitialized(self, clrSilver, NotifyChange);
  629. FAppliedVelocityColor := TGLColor.CreateInitialized(self, clrLime, NotifyChange);
  630. FCustomColor := TGLColor.CreateInitialized(self, clrAqua, NotifyChange);
  631. end;
  632. FDotAxisSize := 1;
  633. FManagerDebugs := [];
  634. FManager := AOwner as TGLNGDManager;
  635. end;
  636. destructor TGLNGDDebugOption.Destroy;
  637. begin
  638. FGeomColorDyn.Free;
  639. FGeomColorStat.Free;
  640. FAABBColor.Free;
  641. FAABBColorSleep.Free;
  642. FCenterOfMassColor.Free;
  643. FContactColor.Free;
  644. FJointAxisColor.Free;
  645. FJointPivotColor.Free;
  646. FForceColor.Free;
  647. FAppliedForceColor.Free;
  648. FAppliedVelocityColor.Free;
  649. FCustomColor.Free;
  650. inherited;
  651. end;
  652. procedure TGLNGDDebugOption.SetDotAxisSize(const Value: Single);
  653. begin
  654. FDotAxisSize := Value;
  655. FManager.NotifyChange(self);
  656. end;
  657. procedure TGLNGDDebugOption.SetManagerDebugs(const Value: TGLNGDManagerDebugs);
  658. begin
  659. FManagerDebugs := Value;
  660. FManager.NotifyChange(self);
  661. end;
  662. function TGLNGDDebugOption.StoredDotAxis: Boolean;
  663. begin
  664. Result := not SameValue(FDotAxisSize, 1, epsilon);
  665. end;
  666. // ------------------------
  667. // TGLNGDManager
  668. // ------------------------
  669. procedure TGLNGDManager.AddNode(const Value: TGLVector);
  670. begin
  671. if Assigned(FGLLines) then
  672. begin
  673. FGLLines.Nodes.AddNode(Value);
  674. with (FGLLines.Nodes.Last as TGLLinesNode) do
  675. Color := FCurrentColor;
  676. end;
  677. end;
  678. procedure TGLNGDManager.AddNode(const coords: TGLCustomCoordinates);
  679. begin
  680. if Assigned(FGLLines) then
  681. begin
  682. FGLLines.Nodes.AddNode(coords);
  683. (FGLLines.Nodes.Last as TGLLinesNode).Color := FCurrentColor;
  684. end;
  685. end;
  686. procedure TGLNGDManager.AddNode(const X, Y, Z: Single);
  687. begin
  688. if Assigned(FGLLines) then
  689. begin
  690. FGLLines.Nodes.AddNode(X, Y, Z);
  691. (FGLLines.Nodes.Last as TGLLinesNode).Color := FCurrentColor;
  692. end;
  693. end;
  694. procedure TGLNGDManager.AddNode(const Value: TAffineVector);
  695. begin
  696. if Assigned(FGLLines) then
  697. begin
  698. FGLLines.Nodes.AddNode(Value);
  699. (FGLLines.Nodes.Last as TGLLinesNode).Color := FCurrentColor;
  700. end;
  701. end;
  702. constructor TGLNGDManager.Create(AOwner: TComponent);
  703. var
  704. minworld, maxworld: TGLVector;
  705. begin
  706. inherited;
  707. FNGDBehaviours := TGLNGDBehaviourList.Create;
  708. FVisible := True;
  709. FVisibleAtRunTime := False;
  710. FSolverModel := smExact;
  711. FFrictionModel := fmExact;
  712. FMinimumFrameRate := 60;
  713. FWorldSizeMin := TGLCoordinates.CreateInitialized(self, VectorMake(-100, -100, -100, 0), csPoint);
  714. FWorldSizeMax := TGLCoordinates.CreateInitialized(self, VectorMake(100, 100, 100, 0), csPoint);
  715. // Using Events because we need to call API Function when
  716. // theses TGLCoordinates change.
  717. FWorldSizeMin.OnNotifyChange := NotifyWorldSizeChange;
  718. FWorldSizeMax.OnNotifyChange := NotifyWorldSizeChange;
  719. FThreadCount := 1;
  720. FGravity := TGLCoordinates3.CreateInitialized(self, VectorMake(0, -9.81, 0, 0), csVector);
  721. FNewtonWorld := NewtonCreate(nil, nil);
  722. FDllVersion := NewtonWorldGetVersion(FNewtonWorld);
  723. // This is to prevent body out the world at startTime
  724. minworld := VectorMake(-1E50, -1E50, -1E50);
  725. maxworld := VectorMake(1E50, 1E50, 1E50);
  726. NewtonSetWorldSize(FNewtonWorld, @minworld, @maxworld);
  727. NewtonWorldSetUserData(FNewtonWorld, self);
  728. FNewtonSurfaceItem := TCollection.Create(TGLNGDSurfaceItem);
  729. FNewtonSurfacePair := TOwnedCollection.Create(self, TGLNGDSurfacePair);
  730. FNewtonJointGroup := TOwnedCollection.Create(self, TGLNGDJoint);
  731. FNewtonDebugOption := TGLNGDDebugOption.Create(self);
  732. RegisterManager(self);
  733. end;
  734. destructor TGLNGDManager.Destroy;
  735. begin
  736. // for joint before body.
  737. FreeAndNil(FNewtonJointGroup);
  738. // Unregister everything
  739. while FNGDBehaviours.Count > 0 do
  740. FNGDBehaviours[0].Manager := nil;
  741. // Clean up everything
  742. FreeAndNil(FNGDBehaviours);
  743. FreeAndNil(FWorldSizeMin);
  744. FreeAndNil(FWorldSizeMax);
  745. FreeAndNil(FGravity);
  746. FreeAndNil(FNewtonSurfaceItem);
  747. FreeAndNil(FNewtonSurfacePair);
  748. FreeAndNil(FNewtonDebugOption);
  749. NewtonDestroyAllBodies(FNewtonWorld);
  750. NewtonMaterialDestroyAllGroupID(FNewtonWorld);
  751. NewtonDestroy(FNewtonWorld);
  752. FNewtonWorld := nil;
  753. DeregisterManager(self);
  754. inherited;
  755. end;
  756. procedure TGLNGDManager.Loaded;
  757. begin
  758. inherited;
  759. NotifyWorldSizeChange(self);
  760. RebuildAllJoint(self);
  761. end;
  762. function TGLNGDManager.GetBodyCount: Integer;
  763. begin
  764. if (csDesigning in ComponentState) then
  765. Result := FNGDBehaviours.Count
  766. else
  767. Result := NewtonWorldGetBodyCount(FNewtonWorld);
  768. end;
  769. function TGLNGDManager.GetConstraintCount: Integer;
  770. begin
  771. if (csDesigning in ComponentState) then
  772. Result := FNewtonJointGroup.Count
  773. else
  774. // Constraint is the number of joint
  775. Result := NewtonWorldGetConstraintCount(FNewtonWorld);
  776. end;
  777. procedure TGLNGDManager.NotifyChange(Sender: TObject);
  778. var
  779. I: Integer;
  780. begin
  781. // This event is raise
  782. // when debugOptions properties are edited,
  783. // when a behavior is initialized/finalize,
  784. // when joints are rebuilded, (runtime only)
  785. // when visible and visibleAtRuntime are edited (designTime only),
  786. // in manager.step, and in SetGLLines.
  787. // Here the manager call render method for bodies and joints in its lists
  788. if not Assigned(FGLLines) then
  789. exit;
  790. FGLLines.Nodes.Clear;
  791. if not Visible then
  792. exit;
  793. if not(csDesigning in ComponentState) then
  794. if not VisibleAtRunTime then
  795. exit;
  796. for I := 0 to FNGDBehaviours.Count - 1 do
  797. FNGDBehaviours[I].Render;
  798. if mdShowJoint in FNewtonDebugOption.NGDManagerDebugs then
  799. for I := 0 to NewtonJoint.Count - 1 do //
  800. (NewtonJoint.Items[I] as TGLNGDJoint).Render;
  801. end;
  802. procedure TGLNGDManager.SetFrictionModel(const Value: TGLNGDFrictionModels);
  803. begin
  804. FFrictionModel := Value;
  805. if not(csDesigning in ComponentState) then
  806. NewtonSetFrictionModel(FNewtonWorld, Ord(FFrictionModel));
  807. end;
  808. procedure TGLNGDManager.SetGLLines(const Value: TGLLines);
  809. begin
  810. if Assigned(FGLLines) then
  811. FGLLines.Nodes.Clear;
  812. FGLLines := Value;
  813. if Assigned(FGLLines) then
  814. begin
  815. FGLLines.SplineMode := lsmSegments;
  816. FGLLines.NodesAspect := lnaInvisible;
  817. FGLLines.Options := [loUseNodeColorForLines];
  818. FGLLines.Pickable := False;
  819. NotifyChange(self);
  820. end;
  821. end;
  822. procedure TGLNGDManager.SetMinimumFrameRate(const Value: Integer);
  823. begin
  824. if (Value >= 60) and (Value <= 1000) then
  825. FMinimumFrameRate := Value;
  826. if not(csDesigning in ComponentState) then
  827. NewtonSetMinimumFrameRate(FNewtonWorld, FMinimumFrameRate);
  828. end;
  829. procedure TGLNGDManager.SetSolverModel(const Value: TGLNGDSolverModels);
  830. begin
  831. FSolverModel := Value;
  832. if not(csDesigning in ComponentState) then
  833. NewtonSetSolverModel(FNewtonWorld, Ord(FSolverModel));
  834. end;
  835. procedure TGLNGDManager.SetThreadCount(const Value: Integer);
  836. begin
  837. if Value > 0 then
  838. FThreadCount := Value;
  839. NewtonSetThreadsCount(FNewtonWorld, FThreadCount);
  840. FThreadCount := NewtonGetThreadsCount(FNewtonWorld);
  841. end;
  842. procedure TGLNGDManager.SetVisible(const Value: Boolean);
  843. begin
  844. FVisible := Value;
  845. if (csDesigning in ComponentState) then
  846. NotifyChange(self);
  847. end;
  848. procedure TGLNGDManager.SetVisibleAtRunTime(const Value: Boolean);
  849. begin
  850. FVisibleAtRunTime := Value;
  851. if (csDesigning in ComponentState) then
  852. NotifyChange(self);
  853. end;
  854. procedure TGLNGDManager.NotifyWorldSizeChange(Sender: TObject);
  855. begin
  856. if not(csDesigning in ComponentState) then
  857. NewtonSetWorldSize(FNewtonWorld, @FWorldSizeMin.AsVector, @FWorldSizeMax.AsVector);
  858. end;
  859. procedure TGLNGDManager.RebuildAllJoint(Sender: TObject);
  860. procedure BuildBallAndSocket(Joint: TGLNGDJoint);
  861. begin
  862. with Joint do
  863. if Assigned(FParentObject) and Assigned(FChildObject) then
  864. begin
  865. FNewtonJoint := NewtonConstraintCreateBall(FNewtonWorld,
  866. @(FBallAndSocketOptions.FPivotPoint.AsVector), GetBodyFromGLSceneObject(FChildObject),
  867. GetBodyFromGLSceneObject(FParentObject));
  868. NewtonJointSetCollisionState(FNewtonJoint, Ord(FCollisionState));
  869. NewtonJointSetStiffness(FNewtonJoint, FStiffness);
  870. end;
  871. end;
  872. procedure BuildHinge(Joint: TGLNGDJoint);
  873. begin
  874. with Joint do
  875. if Assigned(FParentObject) and Assigned(FChildObject) then
  876. begin
  877. FNewtonJoint := NewtonConstraintCreateHinge(FNewtonWorld,
  878. @(FHingeOptions.FPivotPoint.AsVector), @(FHingeOptions.FPinDirection.AsVector),
  879. GetBodyFromGLSceneObject(FChildObject), GetBodyFromGLSceneObject(FParentObject));
  880. NewtonJointSetCollisionState(FNewtonJoint, Ord(FCollisionState));
  881. NewtonJointSetStiffness(FNewtonJoint, FStiffness);
  882. end;
  883. end;
  884. procedure BuildSlider(Joint: TGLNGDJoint);
  885. begin
  886. with Joint do
  887. if Assigned(FParentObject) and Assigned(FChildObject) then
  888. begin
  889. FNewtonJoint := NewtonConstraintCreateSlider(FNewtonWorld,
  890. @(FSliderOptions.FPivotPoint.AsVector), @(FSliderOptions.FPinDirection.AsVector),
  891. GetBodyFromGLSceneObject(FChildObject), GetBodyFromGLSceneObject(FParentObject));
  892. NewtonJointSetCollisionState(FNewtonJoint, Ord(FCollisionState));
  893. NewtonJointSetStiffness(FNewtonJoint, FStiffness);
  894. end;
  895. end;
  896. procedure BuildCorkscrew(Joint: TGLNGDJoint);
  897. begin
  898. with Joint do
  899. if Assigned(FParentObject) and Assigned(FChildObject) then
  900. begin
  901. FNewtonJoint := NewtonConstraintCreateCorkscrew(FNewtonWorld,
  902. @(FCorkscrewOptions.FPivotPoint.AsVector), @(FCorkscrewOptions.FPinDirection.AsVector),
  903. GetBodyFromGLSceneObject(FChildObject), GetBodyFromGLSceneObject(FParentObject));
  904. NewtonJointSetCollisionState(FNewtonJoint, Ord(FCollisionState));
  905. NewtonJointSetStiffness(FNewtonJoint, FStiffness);
  906. end;
  907. end;
  908. procedure BuildUniversal(Joint: TGLNGDJoint);
  909. begin
  910. with Joint do
  911. if Assigned(FParentObject) and Assigned(FChildObject) then
  912. begin
  913. FNewtonJoint := NewtonConstraintCreateUniversal(FNewtonWorld,
  914. @(FUniversalOptions.FPivotPoint.AsVector), @(FUniversalOptions.FPinDirection.AsVector),
  915. @(FUniversalOptions.FPinDirection2.AsVector), GetBodyFromGLSceneObject(FChildObject),
  916. GetBodyFromGLSceneObject(FParentObject));
  917. NewtonJointSetCollisionState(FNewtonJoint, Ord(FCollisionState));
  918. NewtonJointSetStiffness(FNewtonJoint, FStiffness);
  919. end;
  920. end;
  921. procedure BuildCustomBallAndSocket(Joint: TGLNGDJoint);
  922. var
  923. pinAndPivot: TGLMatrix;
  924. begin
  925. with Joint do
  926. if Assigned(FParentObject) and Assigned(FChildObject) then
  927. begin
  928. pinAndPivot := IdentityHmgMatrix;
  929. pinAndPivot.W := FCustomBallAndSocketOptions.FPivotPoint.AsVector;
  930. (* // from dJointLibrary.dll
  931. FNewtonUserJoint := CreateCustomBallAndSocket(@pinAndPivot,
  932. GetBodyFromGLSceneObject(FChildObject),
  933. GetBodyFromGLSceneObject(FParentObject));
  934. BallAndSocketSetConeAngle(FNewtonUserJoint,
  935. DegToRadian(FCustomBallAndSocketOptions.FConeAngle));
  936. BallAndSocketSetTwistAngle(FNewtonUserJoint,
  937. DegToRadian(FCustomBallAndSocketOptions.FMinTwistAngle),
  938. DegToRadian(FCustomBallAndSocketOptions.FMaxTwistAngle));
  939. CustomSetBodiesCollisionState(FNewtonUserJoint, Ord(FCollisionState));
  940. NewtonJointSetStiffness(CustomGetNewtonJoint(FNewtonUserJoint),
  941. FStiffness);
  942. *)
  943. end;
  944. end;
  945. procedure BuildCustomHinge(Joint: TGLNGDJoint);
  946. var
  947. pinAndPivot: TGLMatrix;
  948. bso: TGLBaseSceneObject;
  949. begin
  950. (* Newton wait from FPinAndPivotMatrix a structure like that:
  951. First row: the pin direction
  952. Second and third rows are set to create an orthogonal matrix
  953. Fourth: The pivot position
  954. The BaseSceneObjects direction is the third row,
  955. because the first row is the right vector (second row is up vector). *)
  956. with Joint do
  957. if Assigned(FParentObject) and Assigned(FChildObject) then
  958. begin
  959. bso := TGLBaseSceneObject.Create(FManager);
  960. bso.AbsolutePosition := FCustomHingeOptions.FPivotPoint.AsVector;
  961. bso.AbsoluteDirection := FCustomHingeOptions.FPinDirection.AsVector;
  962. pinAndPivot := bso.AbsoluteMatrix;
  963. pinAndPivot.X := bso.AbsoluteMatrix.Z;
  964. pinAndPivot.Z := bso.AbsoluteMatrix.X;
  965. bso.Free;
  966. (* from dJointLibrary.dll
  967. FNewtonUserJoint := CreateCustomHinge(@pinAndPivot,
  968. GetBodyFromGLSceneObject(FChildObject),
  969. GetBodyFromGLSceneObject(FParentObject));
  970. HingeEnableLimits(FNewtonUserJoint, 1);
  971. HingeSetLimits(FNewtonUserJoint,
  972. DegToRadian(FCustomHingeOptions.FMinAngle),
  973. DegToRadian(FCustomHingeOptions.FMaxAngle));
  974. CustomSetBodiesCollisionState(FNewtonUserJoint, Ord(FCollisionState));
  975. NewtonJointSetStiffness(CustomGetNewtonJoint(FNewtonUserJoint),
  976. FStiffness);
  977. CustomSetUserData(FNewtonUserJoint, CustomHingeOptions);
  978. *)
  979. end;
  980. end;
  981. procedure BuildCustomSlider(Joint: TGLNGDJoint);
  982. var
  983. pinAndPivot: TGLMatrix;
  984. bso: TGLBaseSceneObject;
  985. begin
  986. (*
  987. Newton wait from FPinAndPivotMatrix a structure like that:
  988. First row: the pin direction
  989. Second and third rows are set to create an orthogonal matrix
  990. Fourth: The pivot position
  991. In GLS.Scene, the GLBaseSceneObjects direction is the third row,
  992. because the first row is the right vector (second row is up vector).
  993. *)
  994. with Joint do
  995. if Assigned(FParentObject) and Assigned(FChildObject) then
  996. begin
  997. bso := TGLBaseSceneObject.Create(FManager);
  998. bso.AbsolutePosition := FCustomSliderOptions.FPivotPoint.AsVector;
  999. bso.AbsoluteDirection := FCustomSliderOptions.FPinDirection.AsVector;
  1000. pinAndPivot := bso.AbsoluteMatrix;
  1001. pinAndPivot.X := bso.AbsoluteMatrix.Z;
  1002. pinAndPivot.Z := bso.AbsoluteMatrix.X;
  1003. bso.Free;
  1004. (* from dJointLibrary.dll
  1005. FNewtonUserJoint := CreateCustomSlider(@pinAndPivot,
  1006. GetBodyFromGLSceneObject(FChildObject),
  1007. GetBodyFromGLSceneObject(FParentObject));
  1008. SliderEnableLimits(FNewtonUserJoint, 1);
  1009. SliderSetLimits(FNewtonUserJoint, FCustomSliderOptions.FMinDistance,
  1010. FCustomSliderOptions.FMaxDistance);
  1011. NewtonJointSetStiffness(CustomGetNewtonJoint(FNewtonUserJoint), 0);
  1012. CustomSetBodiesCollisionState(FNewtonUserJoint, Ord(FCollisionState));
  1013. CustomSetUserData(FNewtonUserJoint, CustomSliderOptions);
  1014. *)
  1015. end;
  1016. end;
  1017. procedure BuildUpVector(Joint: TGLNGDJoint);
  1018. begin
  1019. with Joint do
  1020. if Assigned(FParentObject) then
  1021. begin
  1022. FNewtonJoint := NewtonConstraintCreateUpVector(FNewtonWorld, @FUPVectorDirection.AsVector,
  1023. GetBodyFromGLSceneObject(FParentObject));
  1024. end;
  1025. end;
  1026. procedure BuildKinematicController(Joint: TGLNGDJoint);
  1027. begin
  1028. // do nothing
  1029. end;
  1030. procedure BuildOneJoint(Joint: TGLNGDJoint);
  1031. begin
  1032. case Joint.FJointType of
  1033. nj_BallAndSocket:
  1034. begin
  1035. Joint.DestroyNewtonData;
  1036. BuildBallAndSocket(Joint);
  1037. end;
  1038. nj_Hinge:
  1039. begin
  1040. Joint.DestroyNewtonData;
  1041. BuildHinge(Joint);
  1042. end;
  1043. nj_Slider:
  1044. begin
  1045. Joint.DestroyNewtonData;
  1046. BuildSlider(Joint);
  1047. end;
  1048. nj_Corkscrew:
  1049. begin
  1050. Joint.DestroyNewtonData;
  1051. BuildCorkscrew(Joint);
  1052. end;
  1053. nj_Universal:
  1054. begin
  1055. Joint.DestroyNewtonData;
  1056. BuildUniversal(Joint);
  1057. end;
  1058. nj_CustomBallAndSocket:
  1059. begin
  1060. Joint.DestroyNewtonData;
  1061. BuildCustomBallAndSocket(Joint);
  1062. end;
  1063. nj_CustomHinge:
  1064. begin
  1065. Joint.DestroyNewtonData;
  1066. BuildCustomHinge(Joint);
  1067. end;
  1068. nj_CustomSlider:
  1069. begin
  1070. Joint.DestroyNewtonData;
  1071. BuildCustomSlider(Joint);
  1072. end;
  1073. nj_UpVector:
  1074. begin
  1075. Joint.DestroyNewtonData;
  1076. BuildUpVector(Joint);
  1077. end;
  1078. nj_KinematicController:
  1079. begin
  1080. // DestroyJoint(Joint);
  1081. // BuildKinematicController(Joint);
  1082. end;
  1083. end;
  1084. end;
  1085. var
  1086. I: Integer;
  1087. begin
  1088. if not(csDesigning in ComponentState) and not(csLoading in ComponentState) then
  1089. begin
  1090. if Sender is TGLNGDManager then
  1091. for I := 0 to NewtonJoint.Count - 1 do
  1092. BuildOneJoint(NewtonJoint.Items[I] as TGLNGDJoint);
  1093. if (Sender is TGLNGDJoint) then
  1094. BuildOneJoint((Sender as TGLNGDJoint));
  1095. if Sender is TGLCoordinates then
  1096. BuildOneJoint(((Sender as TGLCoordinates).Owner as TGLNGDJoint));
  1097. NotifyChange(self);
  1098. end;
  1099. end;
  1100. procedure TGLNGDManager.RebuildAllMaterial;
  1101. procedure BuildMaterialPair;
  1102. var
  1103. I, ID0, ID1: Integer;
  1104. begin
  1105. for I := 0 to FNewtonSurfacePair.Count - 1 do
  1106. with (FNewtonSurfacePair.Items[I] as TGLNGDSurfacePair) do
  1107. begin
  1108. if Assigned(NGDSurfaceItem1) and Assigned(NGDSurfaceItem2) then
  1109. begin
  1110. ID0 := NGDSurfaceItem1.ID;
  1111. ID1 := NGDSurfaceItem2.ID;
  1112. NewtonMaterialSetContinuousCollisionMode(FNewtonWorld, ID0, ID1,
  1113. Ord(ContinuousCollisionMode));
  1114. if Thickness then
  1115. NewtonMaterialSetSurfaceThickness(FNewtonWorld, ID0, ID1, 1);
  1116. NewtonMaterialSetDefaultSoftness(FNewtonWorld, ID0, ID1, Softness);
  1117. NewtonMaterialSetDefaultElasticity(FNewtonWorld, ID0, ID1, Elasticity);
  1118. NewtonMaterialSetDefaultCollidable(FNewtonWorld, ID0, ID1, Ord(Collidable));
  1119. NewtonMaterialSetDefaultFriction(FNewtonWorld, ID0, ID1, StaticFriction, KineticFriction);
  1120. NewtonMaterialSetCollisionCallback(FNewtonWorld, ID0, ID1, FNewtonSurfacePair.Items[I],
  1121. @TGLNGDSurfacePair.NewtonAABBOverlap, @TGLNGDSurfacePair.NewtonContactsProcess);
  1122. end;
  1123. end;
  1124. end;
  1125. var
  1126. I: Integer;
  1127. maxID: Integer;
  1128. begin
  1129. maxID := 0;
  1130. if not(csDesigning in ComponentState) then
  1131. begin
  1132. // for newton materials
  1133. NewtonMaterialDestroyAllGroupID(FNewtonWorld);
  1134. // Creates materialID
  1135. for I := 0 to FNewtonSurfaceItem.Count - 1 do
  1136. maxID := MaxInteger((FNewtonSurfaceItem.Items[I] as TGLNGDSurfaceItem).ID, maxID);
  1137. for I := 0 to maxID - 1 do
  1138. NewtonMaterialCreateGroupID(FNewtonWorld);
  1139. // assign matID to bodies
  1140. for I := 0 to FNGDBehaviours.Count - 1 do
  1141. with FNGDBehaviours[I] do
  1142. if Assigned(FSurfaceItem) then
  1143. NewtonBodySetMaterialGroupID(FNewtonBody, FSurfaceItem.ID)
  1144. else
  1145. NewtonBodySetMaterialGroupID(FNewtonBody, 0);
  1146. // Set values to newton material pair :callback userdata friction...
  1147. BuildMaterialPair;
  1148. end;
  1149. end;
  1150. procedure TGLNGDManager.Step(deltatime: Single);
  1151. begin
  1152. if not(csDesigning in ComponentState) then
  1153. NewtonUpdate(FNewtonWorld, deltatime);
  1154. NotifyChange(self);
  1155. end;
  1156. // ---------------------------
  1157. // TGLNGDBehaviour
  1158. // ---------------------------
  1159. constructor TGLNGDBehaviour.Create(AOwner: TXCollection);
  1160. begin
  1161. inherited;
  1162. FInitialized := False;
  1163. FOwnerBaseSceneObject := OwnerBaseSceneObject;
  1164. FContinuousCollisionMode := False;
  1165. FNewtonBody := nil;
  1166. FCollision := nil;
  1167. FNewtonCollisions := nc_Primitive;
  1168. FCollisionIteratorEvent := OnCollisionIteratorEvent;
  1169. FTreeCollisionOptimize := True;
  1170. FConvexCollisionTolerance := 0.01;
  1171. FFileCollision := '';
  1172. name := 'NGD Static';
  1173. end;
  1174. destructor TGLNGDBehaviour.Destroy;
  1175. begin
  1176. if Assigned(FManager) then
  1177. Manager := nil; // This will call finalize
  1178. inherited;
  1179. end;
  1180. procedure TGLNGDBehaviour.Finalize;
  1181. var
  1182. I: Integer;
  1183. begin
  1184. FInitialized := False;
  1185. if Assigned(FManager) then
  1186. begin
  1187. if Assigned(FManager.NewtonJoint) then
  1188. for I := FManager.NewtonJoint.Count - 1 downto 0 do
  1189. begin
  1190. if ((FManager.NewtonJoint.Items[I] as TGLNGDJoint).ParentObject = FOwnerBaseSceneObject) or
  1191. ((FManager.NewtonJoint.Items[I] as TGLNGDJoint).ChildObject = FOwnerBaseSceneObject) then
  1192. begin
  1193. FManager.NewtonJoint.Items[I].Free;
  1194. end;
  1195. end;
  1196. NewtonDestroyBody(FManager.FNewtonWorld, FNewtonBody);
  1197. FNewtonBody := nil;
  1198. FCollision := nil;
  1199. end;
  1200. end;
  1201. function TGLNGDBehaviour.GetBBoxCollision: PNewtonCollision;
  1202. var
  1203. vc: array [0 .. 7] of TGLVector;
  1204. I: Integer;
  1205. begin
  1206. for I := 0 to 8 - 1 do
  1207. vc[I] := AABBToBB(FOwnerBaseSceneObject.AxisAlignedBoundingBoxEx).BBox[I];
  1208. Result := NewtonCreateConvexHull(FManager.FNewtonWorld, 8, @vc[0], SizeOf(TGLVector),
  1209. 0.01, 0, nil);
  1210. end;
  1211. function TGLNGDBehaviour.GetBSphereCollision: PNewtonCollision;
  1212. var
  1213. boundingSphere: TBSphere;
  1214. collisionOffsetMatrix: TGLMatrix;
  1215. begin
  1216. AABBToBSphere(FOwnerBaseSceneObject.AxisAlignedBoundingBoxEx, boundingSphere);
  1217. collisionOffsetMatrix := IdentityHmgMatrix;
  1218. collisionOffsetMatrix.W := VectorMake(boundingSphere.Center, 1);
  1219. Result := NewtonCreateSphere(FManager.FNewtonWorld, boundingSphere.Radius, boundingSphere.Radius,
  1220. boundingSphere.Radius, 0, @collisionOffsetMatrix);
  1221. end;
  1222. function TGLNGDBehaviour.GetConvexCollision: PNewtonCollision;
  1223. var
  1224. I, J: Integer;
  1225. vertexArray: array of TVertex;
  1226. begin
  1227. if FOwnerBaseSceneObject is TGLBaseMesh then
  1228. begin
  1229. with (FOwnerBaseSceneObject as TGLBaseMesh) do
  1230. begin
  1231. for I := 0 to MeshObjects.Count - 1 do
  1232. for J := 0 to MeshObjects[I].Vertices.Count - 1 do
  1233. begin
  1234. SetLength(vertexArray, Length(vertexArray) + 1);
  1235. vertexArray[Length(vertexArray) - 1] := MeshObjects[I].Vertices[J];
  1236. end;
  1237. if Length(vertexArray) > 0 then
  1238. Result := NewtonCreateConvexHull(FManager.FNewtonWorld, Length(vertexArray),
  1239. @vertexArray[0], SizeOf(TVertex), FConvexCollisionTolerance, 0, nil)
  1240. else
  1241. Result := GetNullCollision;
  1242. end;
  1243. end
  1244. else
  1245. Result := GetNullCollision;
  1246. end;
  1247. function TGLNGDBehaviour.GetHeightFieldCollision: PNewtonCollision;
  1248. var
  1249. I: Integer;
  1250. attributeMap: array of ShortInt;
  1251. begin
  1252. SetLength(attributeMap, Length(FHeightFieldOptions.heightArray));
  1253. for I := 0 to Length(FHeightFieldOptions.heightArray) - 1 do
  1254. attributeMap[I] := 0;
  1255. Result := NewtonCreateHeightFieldCollision(FManager.FNewtonWorld, FHeightFieldOptions.width,
  1256. FHeightFieldOptions.depth, Ord(FHeightFieldOptions.gridDiagonals),
  1257. PUnsigned_short(FHeightFieldOptions.heightArray), P2Char(attributeMap),
  1258. FHeightFieldOptions.widthDepthScale, FHeightFieldOptions.heightScale, 0);
  1259. end;
  1260. function TGLNGDBehaviour.GetMeshCollision: PNewtonCollision;
  1261. var
  1262. collisionArray: array of PNewtonCollision;
  1263. I, J: Integer;
  1264. vertexArray: array of TVertex;
  1265. begin
  1266. if FOwnerBaseSceneObject is TGLBaseMesh then
  1267. begin
  1268. with (FOwnerBaseSceneObject as TGLBaseMesh) do
  1269. begin
  1270. // Iterate trough mesh of GLobject
  1271. for I := 0 to MeshObjects.Count - 1 do
  1272. begin
  1273. // Iterate trough vertices of mesh
  1274. for J := 0 to MeshObjects[I].Vertices.Count - 1 do
  1275. begin
  1276. SetLength(vertexArray, Length(vertexArray) + 1);
  1277. vertexArray[Length(vertexArray) - 1] := MeshObjects[I].Vertices[J];
  1278. end;
  1279. if Length(vertexArray) > 3 then
  1280. begin
  1281. SetLength(collisionArray, Length(collisionArray) + 1);
  1282. collisionArray[Length(collisionArray) - 1] :=
  1283. NewtonCreateConvexHull(FManager.FNewtonWorld, Length(vertexArray), @vertexArray[0],
  1284. SizeOf(TVertex), FConvexCollisionTolerance, 0, nil);
  1285. // Remove last collision if the newton function was not successful
  1286. if collisionArray[Length(collisionArray) - 1] = nil then
  1287. SetLength(collisionArray, Length(collisionArray) - 1);
  1288. end;
  1289. SetLength(vertexArray, 0);
  1290. end;
  1291. if Length(collisionArray) > 0 then
  1292. Result := NewtonCreateCompoundCollision(FManager.FNewtonWorld, Length(collisionArray),
  1293. TCollisionPrimitiveArray(@collisionArray[0]), 0)
  1294. else
  1295. Result := GetNullCollision;
  1296. end;
  1297. end
  1298. else
  1299. Result := GetNullCollision;
  1300. end;
  1301. function TGLNGDBehaviour.GetNewtonBodyMatrix: TGLMatrix;
  1302. begin
  1303. if Assigned(FManager) then
  1304. NewtonBodyGetmatrix(FNewtonBody, @FNewtonBodyMatrix);
  1305. Result := FNewtonBodyMatrix;
  1306. end;
  1307. function TGLNGDBehaviour.GetNewtonBodyAABB: TAABB;
  1308. begin
  1309. if Assigned(FManager) then
  1310. NewtonBodyGetAABB(FNewtonBody, @(Result.min), @(Result.max));
  1311. end;
  1312. function TGLNGDBehaviour.GetNGDFileCollision: PNewtonCollision;
  1313. var
  1314. MyFile: TFileStream;
  1315. begin
  1316. if FileExists(FFileCollision) then
  1317. begin
  1318. MyFile := TFileStream.Create(FFileCollision, fmOpenRead);
  1319. Result := NewtonCreateCollisionFromSerialization(FManager.FNewtonWorld,
  1320. @TGLNGDBehaviour.NewtonDeserialize, Pointer(MyFile));
  1321. MyFile.Free;
  1322. end
  1323. else
  1324. Result := NewtonCreateNull(FManager.FNewtonWorld);
  1325. end;
  1326. function TGLNGDBehaviour.GetNullCollision: PNewtonCollision;
  1327. begin
  1328. Result := NewtonCreateNull(FManager.FNewtonWorld);
  1329. end;
  1330. function TGLNGDBehaviour.GetPrimitiveCollision: PNewtonCollision;
  1331. var
  1332. collisionOffsetMatrix: TGLMatrix; // For cone capsule and cylinder
  1333. begin
  1334. collisionOffsetMatrix := IdentityHmgMatrix;
  1335. if (FOwnerBaseSceneObject is TGLCube) then
  1336. begin
  1337. with (FOwnerBaseSceneObject as TGLCube) do
  1338. Result := NewtonCreateBox(FManager.FNewtonWorld, CubeWidth, CubeHeight, CubeDepth, 0, @collisionOffsetMatrix);
  1339. end
  1340. else if (FOwnerBaseSceneObject is TGLSphere) then
  1341. begin
  1342. with (FOwnerBaseSceneObject as TGLSphere) do
  1343. Result := NewtonCreateSphere(FManager.FNewtonWorld, Radius, Radius, Radius, 0,
  1344. @collisionOffsetMatrix);
  1345. end
  1346. else if (FOwnerBaseSceneObject is TGLCone) then
  1347. begin
  1348. collisionOffsetMatrix := MatrixMultiply(collisionOffsetMatrix, CreateRotationMatrixZ(Pi / 2.0));
  1349. with (FOwnerBaseSceneObject as TGLCone) do
  1350. Result := NewtonCreateCone(FManager.FNewtonWorld, BottomRadius, Height, 0,
  1351. @collisionOffsetMatrix);
  1352. end
  1353. else if (FOwnerBaseSceneObject is TGLCapsule) then
  1354. begin
  1355. collisionOffsetMatrix := MatrixMultiply(collisionOffsetMatrix, CreateRotationMatrixY(Pi / 2.0));
  1356. with (FOwnerBaseSceneObject as TGLCapsule) do
  1357. // Use Cylinder shape for buoyancy
  1358. Result := NewtonCreateCapsule(FManager.FNewtonWorld, Radius, Height + 2 * Radius, 0,
  1359. @collisionOffsetMatrix);
  1360. end
  1361. else if (FOwnerBaseSceneObject is TGLCylinder) then
  1362. begin
  1363. collisionOffsetMatrix := MatrixMultiply(collisionOffsetMatrix, CreateRotationMatrixZ(Pi / 2.0));
  1364. with (FOwnerBaseSceneObject as TGLCylinder) do
  1365. Result := NewtonCreateCylinder(FManager.FNewtonWorld, BottomRadius, Height, 0,
  1366. @collisionOffsetMatrix);
  1367. end
  1368. else
  1369. Result := GetNullCollision;
  1370. end;
  1371. function TGLNGDBehaviour.GetTreeCollision: PNewtonCollision;
  1372. var
  1373. meshIndex, triangleIndex: Integer;
  1374. triangleList: TGLAffineVectorList;
  1375. v: array [0 .. 2] of TAffineVector;
  1376. begin
  1377. if FOwnerBaseSceneObject is TGLBaseMesh then
  1378. begin
  1379. with (FOwnerBaseSceneObject as TGLBaseMesh) do
  1380. begin
  1381. Result := NewtonCreateTreeCollision(FManager.FNewtonWorld, 0);
  1382. NewtonTreeCollisionBeginBuild(Result);
  1383. for meshIndex := 0 to MeshObjects.Count - 1 do
  1384. begin
  1385. triangleList := MeshObjects[meshIndex].ExtractTriangles;
  1386. for triangleIndex := 0 to triangleList.Count - 1 do
  1387. begin
  1388. if triangleIndex mod 3 = 0 then
  1389. begin
  1390. v[0] := triangleList.Items[triangleIndex];
  1391. // ScaleVector(v[0], FOwnerBaseSceneObject.Scale.X);
  1392. v[1] := triangleList.Items[triangleIndex + 1];
  1393. // ScaleVector(v[1], FOwnerBaseSceneObject.Scale.Y);
  1394. v[2] := triangleList.Items[triangleIndex + 2];
  1395. // ScaleVector(v[2], FOwnerBaseSceneObject.Scale.Z);
  1396. NewtonTreeCollisionAddFace(Result, 3, @(v), SizeOf(TAffineVector), 1);
  1397. end;
  1398. end;
  1399. triangleList.Free;
  1400. end;
  1401. NewtonTreeCollisionEndBuild(Result, Ord(FTreeCollisionOptimize));
  1402. end;
  1403. end
  1404. else
  1405. Result := GetNullCollision;
  1406. end;
  1407. procedure TGLNGDBehaviour.Initialize;
  1408. begin
  1409. FInitialized := True;
  1410. if Assigned(FManager) then
  1411. begin
  1412. // Creates NewtonBody with null collision
  1413. FCollision := NewtonCreateNull(FManager.FNewtonWorld);
  1414. FNewtonBodyMatrix := FOwnerBaseSceneObject.AbsoluteMatrix;
  1415. FNewtonBody := NewtonCreateBody(FManager.FNewtonWorld, FCollision, @FNewtonBodyMatrix);
  1416. // Release NewtonCollision
  1417. NewtonReleaseCollision(FManager.FNewtonWorld, FCollision);
  1418. // Set Link between glscene and newton
  1419. NewtonBodySetUserdata(FNewtonBody, self);
  1420. // Set position and orientation
  1421. SetNewtonBodyMatrix(FOwnerBaseSceneObject.AbsoluteMatrix);
  1422. // Set Collision
  1423. UpdCollision;
  1424. end;
  1425. end;
  1426. procedure TGLNGDBehaviour.Loaded;
  1427. var
  1428. mng: TComponent;
  1429. begin
  1430. inherited;
  1431. if FManagerName <> '' then
  1432. begin
  1433. mng := FindManager(TGLNGDManager, FManagerName);
  1434. if Assigned(mng) then
  1435. Manager := TGLNGDManager(mng);
  1436. FManagerName := '';
  1437. end;
  1438. if Assigned(FManager) then
  1439. begin
  1440. SetContinuousCollisionMode(FContinuousCollisionMode);
  1441. end;
  1442. end;
  1443. class procedure TGLNGDBehaviour.NewtonCollisionIterator(const userData: Pointer;
  1444. vertexCount: Integer; const faceArray: PdFloat; faceId: Integer)cdecl;
  1445. begin
  1446. TGLNGDBehaviour(userData).FCollisionIteratorEvent(userData, vertexCount, faceArray, faceId);
  1447. end;
  1448. // Serializes are called by NGDBehaviour to save and load collision in file
  1449. // It's better to save/load big collisions [over 50000 polygones] to reduce
  1450. // loading time
  1451. class procedure TGLNGDBehaviour.NewtonDeserialize(serializeHandle, buffer: Pointer;
  1452. size: Cardinal)cdecl;
  1453. begin
  1454. TFileStream(serializeHandle).read(buffer^, size);
  1455. end;
  1456. class procedure TGLNGDBehaviour.NewtonSerialize(serializeHandle: Pointer; const buffer: Pointer;
  1457. size: Cardinal)cdecl;
  1458. begin
  1459. TFileStream(serializeHandle).write(buffer^, size);
  1460. end;
  1461. procedure TGLNGDBehaviour.OnCollisionIteratorEvent(const userData: Pointer; vertexCount: Integer;
  1462. const cfaceArray: PdFloat; faceId: Integer);
  1463. var
  1464. I: Integer;
  1465. v0, v1: array [0 .. 2] of Single;
  1466. vA: array of Single;
  1467. begin
  1468. // This algorithme draw Collision Shape for Debuggin.
  1469. // Taken to Sascha Willems in SDLNewton-Demo at
  1470. // http://www.saschawillems.de/?page_id=82
  1471. // Leave if there is no or to much vertex
  1472. if (vertexCount = 0) then
  1473. exit;
  1474. SetLength(vA, vertexCount * 3);
  1475. Move(cfaceArray^, vA[0], vertexCount * 3 * SizeOf(Single));
  1476. v0[0] := vA[(vertexCount - 1) * 3];
  1477. v0[1] := vA[(vertexCount - 1) * 3 + 1];
  1478. v0[2] := vA[(vertexCount - 1) * 3 + 2];
  1479. for I := 0 to vertexCount - 1 do
  1480. begin
  1481. v1[0] := vA[I * 3];
  1482. v1[1] := vA[I * 3 + 1];
  1483. v1[2] := vA[I * 3 + 2];
  1484. FManager.AddNode(v0[0], v0[1], v0[2]);
  1485. FManager.AddNode(v1[0], v1[1], v1[2]);
  1486. v0 := v1;
  1487. end;
  1488. end;
  1489. procedure TGLNGDBehaviour.Reinitialize;
  1490. begin
  1491. if Initialized then
  1492. begin
  1493. // Set Appropriate NewtonCollision
  1494. UpdCollision();
  1495. // Set position and orientation
  1496. SetNewtonBodyMatrix(FOwnerBaseSceneObject.AbsoluteMatrix);
  1497. end;
  1498. Loaded;
  1499. end;
  1500. procedure TGLNGDBehaviour.Render;
  1501. var
  1502. M: TGLMatrix;
  1503. begin
  1504. // Rebuild collision in design time
  1505. if (csDesigning in FOwnerBaseSceneObject.ComponentState) then
  1506. Reinitialize;
  1507. if self is TGLNGDDynamic then
  1508. FManager.FCurrentColor := FManager.DebugOption.GeomColorDyn
  1509. else
  1510. FManager.FCurrentColor := FManager.DebugOption.GeomColorStat;
  1511. M := FOwnerBaseSceneObject.AbsoluteMatrix;
  1512. if mdShowGeometry in FManager.DebugOption.NGDManagerDebugs then
  1513. NewtonCollisionForEachPolygonDo(FCollision, @M, @TGLNGDBehaviour.NewtonCollisionIterator, self);
  1514. end;
  1515. // In this procedure, we assign collision to body
  1516. // [Because when initialised, the collision for body is type NULL]
  1517. procedure TGLNGDBehaviour.UpdCollision;
  1518. var
  1519. collisionInfoRecord: TNewtonCollisionInfoRecord;
  1520. begin
  1521. case FNewtonCollisions of
  1522. nc_Primitive:
  1523. FCollision := GetPrimitiveCollision;
  1524. nc_Convex:
  1525. FCollision := GetConvexCollision;
  1526. nc_BBox:
  1527. FCollision := GetBBoxCollision;
  1528. nc_BSphere:
  1529. FCollision := GetBSphereCollision;
  1530. nc_Tree:
  1531. FCollision := GetTreeCollision;
  1532. nc_Mesh:
  1533. FCollision := GetMeshCollision;
  1534. nc_Null:
  1535. FCollision := GetNullCollision;
  1536. nc_HeightField:
  1537. FCollision := GetHeightFieldCollision;
  1538. nc_NGDFile:
  1539. FCollision := GetNGDFileCollision;
  1540. end;
  1541. if Assigned(FCollision) then
  1542. begin
  1543. NewtonBodySetCollision(FNewtonBody, FCollision);
  1544. // The API Ask for releasing Collision to avoid memory leak
  1545. NewtonCollisionGetInfo(FCollision, @collisionInfoRecord);
  1546. if collisionInfoRecord.m_collisionType > 2 then
  1547. NewtonReleaseCollision(FManager.FNewtonWorld, FCollision);
  1548. end;
  1549. end;
  1550. procedure TGLNGDBehaviour.SetContinuousCollisionMode(const Value: Boolean);
  1551. begin
  1552. // for continue collision to be active the continue collision mode must on
  1553. // the material pair of the colliding bodies as well as on at
  1554. // least one of the two colliding bodies.
  1555. // see NewtonBodySetContinuousCollisionMode
  1556. // see NewtonMaterialSetContinuousCollisionMode
  1557. FContinuousCollisionMode := Value;
  1558. if not(csDesigning in FOwnerBaseSceneObject.ComponentState) then
  1559. if Assigned(FManager) then
  1560. NewtonBodySetContinuousCollisionMode(FNewtonBody, Ord(Value));
  1561. end;
  1562. procedure TGLNGDBehaviour.SetHeightFieldOptions(const Value: TGLNGDHeightField);
  1563. begin
  1564. FHeightFieldOptions := Value;
  1565. Reinitialize;
  1566. end;
  1567. procedure TGLNGDBehaviour.SetManager(Value: TGLNGDManager);
  1568. begin
  1569. if FManager <> Value then
  1570. begin
  1571. if Assigned(FManager) then
  1572. begin
  1573. if Initialized then
  1574. Finalize;
  1575. FManager.FNGDBehaviours.Remove(self);
  1576. // FManager.NotifyChange(self);
  1577. end;
  1578. FManager := Value;
  1579. if Assigned(FManager) then
  1580. begin
  1581. Initialize;
  1582. FManager.FNGDBehaviours.Add(self);
  1583. FManager.NotifyChange(self);
  1584. end;
  1585. end;
  1586. end;
  1587. procedure TGLNGDBehaviour.SetNewtonBodyMatrix(const Value: TGLMatrix);
  1588. begin
  1589. FNewtonBodyMatrix := Value;
  1590. if Assigned(FManager) then
  1591. NewtonBodySetmatrix(FNewtonBody, @FNewtonBodyMatrix);
  1592. end;
  1593. procedure TGLNGDBehaviour.SetNewtonCollisions(const Value: TGLNGDCollisions);
  1594. begin
  1595. FNewtonCollisions := Value;
  1596. if Assigned(FManager) then
  1597. UpdCollision;
  1598. end;
  1599. procedure TGLNGDBehaviour.SetNewtonSurfaceItem(const Value: TGLNGDSurfaceItem);
  1600. begin
  1601. FSurfaceItem := Value;
  1602. FManager.RebuildAllMaterial;
  1603. end;
  1604. function TGLNGDBehaviour.StoredTolerance: Boolean;
  1605. begin
  1606. Result := not SameValue(FConvexCollisionTolerance, 0.01, epsilon);
  1607. end;
  1608. class function TGLNGDBehaviour.UniqueItem: Boolean;
  1609. begin
  1610. Result := True;
  1611. end;
  1612. procedure TGLNGDBehaviour.ReadFromFiler(reader: TReader);
  1613. var
  1614. version: Integer;
  1615. begin
  1616. inherited;
  1617. with reader do
  1618. begin
  1619. version := ReadInteger; // read data version
  1620. Assert(version <= 1); // Archive version
  1621. FManagerName := ReadString;
  1622. FContinuousCollisionMode := ReadBoolean;
  1623. read(FNewtonCollisions, SizeOf(TGLNGDCollisions));
  1624. FTreeCollisionOptimize := ReadBoolean;
  1625. if version <= 0 then
  1626. FConvexCollisionTolerance := ReadSingle
  1627. else
  1628. FConvexCollisionTolerance := ReadFloat;
  1629. FFileCollision := ReadString;
  1630. end;
  1631. end;
  1632. procedure TGLNGDBehaviour.WriteToFiler(writer: TWriter);
  1633. begin
  1634. inherited;
  1635. with writer do
  1636. begin
  1637. WriteInteger(1); // Archive version
  1638. if Assigned(FManager) then
  1639. WriteString(FManager.GetNamePath)
  1640. else
  1641. WriteString('');
  1642. WriteBoolean(FContinuousCollisionMode);
  1643. write(FNewtonCollisions, SizeOf(TGLNGDCollisions));
  1644. WriteBoolean(FTreeCollisionOptimize);
  1645. WriteFloat(FConvexCollisionTolerance);
  1646. WriteString(FFileCollision);
  1647. end;
  1648. end;
  1649. procedure TGLNGDBehaviour.Serialize(filename: string);
  1650. var
  1651. MyFile: TFileStream;
  1652. begin
  1653. MyFile := TFileStream.Create(filename, fmCreate or fmOpenReadWrite);
  1654. NewtonCollisionSerialize(FManager.FNewtonWorld, FCollision, @TGLNGDBehaviour.NewtonSerialize,
  1655. Pointer(MyFile));
  1656. MyFile.Free;
  1657. end;
  1658. procedure TGLNGDBehaviour.DeSerialize(filename: string);
  1659. var
  1660. MyFile: TFileStream;
  1661. collisionInfoRecord: TNewtonCollisionInfoRecord;
  1662. begin
  1663. MyFile := TFileStream.Create(filename, fmOpenRead);
  1664. FCollision := NewtonCreateCollisionFromSerialization(FManager.FNewtonWorld,
  1665. @TGLNGDBehaviour.NewtonDeserialize, Pointer(MyFile));
  1666. // SetCollision;
  1667. NewtonBodySetCollision(FNewtonBody, FCollision);
  1668. // Release collision
  1669. NewtonCollisionGetInfo(FCollision, @collisionInfoRecord);
  1670. if collisionInfoRecord.m_collisionType > 2 then
  1671. NewtonReleaseCollision(FManager.FNewtonWorld, FCollision);
  1672. MyFile.Free;
  1673. end;
  1674. // -------------------------
  1675. // TGLNGDDynamic
  1676. // -------------------------
  1677. procedure TGLNGDDynamic.AddImpulse(const veloc, pointposit: TGLVector);
  1678. begin
  1679. if Assigned(FNewtonBody) then
  1680. NewtonBodyAddImpulse(FNewtonBody, @veloc, @pointposit);
  1681. end;
  1682. constructor TGLNGDDynamic.Create(AOwner: TXCollection);
  1683. begin
  1684. inherited;
  1685. FAutoSleep := True;
  1686. FLinearDamping := 0.1;
  1687. FAngularDamping := TGLCoordinates.CreateInitialized(self, VectorMake(0.1, 0.1, 0.1, 0), csPoint);
  1688. FAngularDamping.OnNotifyChange := NotifyAngularDampingChange;
  1689. FDensity := 1;
  1690. FVolume := 1;
  1691. FForce := TGLCoordinates.CreateInitialized(self, NullHmgVector, csVector);
  1692. FTorque := TGLCoordinates.CreateInitialized(self, NullHmgVector, csVector);
  1693. FCenterOfMass := TGLCoordinates.CreateInitialized(self, NullHmgVector, csPoint);
  1694. FCenterOfMass.OnNotifyChange := NotifyCenterOfMassChange;
  1695. FAABBmin := TGLCoordinates.CreateInitialized(self, NullHmgVector, csPoint);
  1696. FAABBmax := TGLCoordinates.CreateInitialized(self, NullHmgVector, csPoint);
  1697. FAppliedOmega := TGLCoordinates.CreateInitialized(self, NullHmgVector, csVector);
  1698. FAppliedVelocity := TGLCoordinates.CreateInitialized(self, NullHmgVector, csVector);
  1699. FAppliedForce := TGLCoordinates.CreateInitialized(self, NullHmgVector, csVector);
  1700. FAppliedTorque := TGLCoordinates.CreateInitialized(self, NullHmgVector, csVector);
  1701. FUseGravity := True;
  1702. FNullCollisionVolume := 0;
  1703. FApplyForceAndTorqueEvent := OnApplyForceAndTorqueEvent;
  1704. FSetTransformEvent := OnSetTransformEvent;
  1705. name := 'NGD Dynamic'
  1706. end;
  1707. destructor TGLNGDDynamic.Destroy;
  1708. begin
  1709. // Clean up everything
  1710. FAngularDamping.Free;
  1711. FForce.Free;
  1712. FTorque.Free;
  1713. FCenterOfMass.Free;
  1714. FAABBmin.Free;
  1715. FAABBmax.Free;
  1716. FAppliedForce.Free;
  1717. FAppliedTorque.Free;
  1718. FAppliedVelocity.Free;
  1719. FAppliedOmega.Free;
  1720. inherited;
  1721. end;
  1722. procedure TGLNGDDynamic.Finalize;
  1723. begin
  1724. if not(csDesigning in FOwnerBaseSceneObject.ComponentState) then
  1725. if Assigned(FManager) then
  1726. begin
  1727. // Removing Callback
  1728. NewtonBodySetForceAndTorqueCallback(FNewtonBody, nil);
  1729. NewtonBodySetTransformCallback(FNewtonBody, nil);
  1730. end;
  1731. inherited;
  1732. end;
  1733. class function TGLNGDDynamic.FriendlyName: string;
  1734. begin
  1735. Result := 'NGD Dynamic';
  1736. end;
  1737. procedure TGLNGDDynamic.Initialize;
  1738. begin
  1739. inherited;
  1740. if not(csDesigning in FOwnerBaseSceneObject.ComponentState) then
  1741. if Assigned(FManager) then
  1742. begin
  1743. // Set Density, Mass and inertie matrix
  1744. SetDensity(FDensity);
  1745. // Set Callback
  1746. NewtonBodySetForceAndTorqueCallback(FNewtonBody, @TGLNGDDynamic.NewtonApplyForceAndTorque);
  1747. NewtonBodySetTransformCallback(FNewtonBody, @TGLNGDDynamic.NewtonSetTransform);
  1748. end;
  1749. end;
  1750. procedure TGLNGDDynamic.Render;
  1751. procedure DrawAABB(min, max: TGLCoordinates3);
  1752. begin
  1753. (*
  1754. // H________G
  1755. // /. /|
  1756. // / . / |
  1757. // D__._____C |
  1758. // | . | |
  1759. // | E.-----|--F
  1760. // | . | /
  1761. // |. |/
  1762. // A________B
  1763. *)
  1764. // Back
  1765. FManager.AddNode(min.X, min.Y, min.Z); // E
  1766. FManager.AddNode(max.X, min.Y, min.Z); // F
  1767. FManager.AddNode(max.X, min.Y, min.Z); // F
  1768. FManager.AddNode(max.X, max.Y, min.Z); // G
  1769. FManager.AddNode(max.X, max.Y, min.Z); // G
  1770. FManager.AddNode(min.X, max.Y, min.Z); // H
  1771. FManager.AddNode(min.X, max.Y, min.Z); // H
  1772. FManager.AddNode(min.X, min.Y, min.Z); // E
  1773. // Front
  1774. FManager.AddNode(min.X, min.Y, max.Z); // A
  1775. FManager.AddNode(max.X, min.Y, max.Z); // B
  1776. FManager.AddNode(max.X, min.Y, max.Z); // B
  1777. FManager.AddNode(max.X, max.Y, max.Z); // C
  1778. FManager.AddNode(max.X, max.Y, max.Z); // C
  1779. FManager.AddNode(min.X, max.Y, max.Z); // D
  1780. FManager.AddNode(min.X, max.Y, max.Z); // D
  1781. FManager.AddNode(min.X, min.Y, max.Z); // A
  1782. // Edges
  1783. FManager.AddNode(min.X, min.Y, max.Z); // A
  1784. FManager.AddNode(min.X, min.Y, min.Z); // E
  1785. FManager.AddNode(max.X, min.Y, max.Z); // B
  1786. FManager.AddNode(max.X, min.Y, min.Z); // F
  1787. FManager.AddNode(max.X, max.Y, max.Z); // C
  1788. FManager.AddNode(max.X, max.Y, min.Z); // G
  1789. FManager.AddNode(min.X, max.Y, max.Z); // D
  1790. FManager.AddNode(min.X, max.Y, min.Z); // H
  1791. end;
  1792. procedure DrawContact;
  1793. var
  1794. cnt: PNewtonJoint;
  1795. thisContact: PNewtonJoint;
  1796. material: PNewtonMaterial;
  1797. pos, nor: TGLVector;
  1798. begin
  1799. FManager.FCurrentColor := FManager.DebugOption.ContactColor;
  1800. cnt := NewtonBodyGetFirstContactJoint(FNewtonBody);
  1801. while cnt <> nil do
  1802. begin
  1803. thisContact := NewtonContactJointGetFirstContact(cnt);
  1804. while thisContact <> nil do
  1805. begin
  1806. material := NewtonContactGetMaterial(thisContact);
  1807. NewtonMaterialGetContactPositionAndNormal(material, FNewtonBody, @pos, @nor);
  1808. FManager.AddNode(pos);
  1809. nor := VectorAdd(pos, nor);
  1810. FManager.AddNode(nor);
  1811. thisContact := NewtonContactJointGetNextContact(cnt, thisContact);
  1812. end;
  1813. cnt := NewtonBodyGetNextContactJoint(FNewtonBody, cnt);
  1814. end;
  1815. end;
  1816. function GetAbsCom(): TGLVector;
  1817. var
  1818. M: TGLMatrix;
  1819. begin
  1820. NewtonBodyGetCentreOfMass(FNewtonBody, @Result);
  1821. M := IdentityHmgMatrix;
  1822. M.W := Result;
  1823. M.W.W := 1;
  1824. M := MatrixMultiply(M, FOwnerBaseSceneObject.AbsoluteMatrix);
  1825. Result := M.W;
  1826. end;
  1827. procedure DrawForce;
  1828. var
  1829. pos: TGLVector;
  1830. nor: TGLVector;
  1831. begin
  1832. pos := GetAbsCom;
  1833. if mdShowForce in FManager.DebugOption.NGDManagerDebugs then
  1834. begin
  1835. FManager.FCurrentColor := FManager.DebugOption.ForceColor;
  1836. nor := VectorAdd(pos, FForce.AsVector);
  1837. FManager.AddNode(pos);
  1838. FManager.AddNode(nor);
  1839. end;
  1840. if mdShowAppliedForce in FManager.DebugOption.NGDManagerDebugs then
  1841. begin
  1842. FManager.FCurrentColor := FManager.DebugOption.AppliedForceColor;
  1843. nor := VectorAdd(pos, FAppliedForce.AsVector);
  1844. FManager.AddNode(pos);
  1845. FManager.AddNode(nor);
  1846. end;
  1847. if mdShowAppliedVelocity in FManager.DebugOption.NGDManagerDebugs then
  1848. begin
  1849. FManager.FCurrentColor := FManager.DebugOption.AppliedVelocityColor;
  1850. nor := VectorAdd(pos, FAppliedVelocity.AsVector);
  1851. FManager.AddNode(pos);
  1852. FManager.AddNode(nor);
  1853. end;
  1854. end;
  1855. procedure DrawCoM;
  1856. var
  1857. com: TGLVector;
  1858. size: Single;
  1859. begin
  1860. FManager.FCurrentColor := FManager.DebugOption.CenterOfMassColor;
  1861. size := FManager.DebugOption.DotAxisSize;
  1862. com := GetAbsCom;
  1863. FManager.AddNode(VectorAdd(com, VectorMake(0, 0, size)));
  1864. FManager.AddNode(VectorAdd(com, VectorMake(0, 0, -size)));
  1865. FManager.AddNode(VectorAdd(com, VectorMake(0, size, 0)));
  1866. FManager.AddNode(VectorAdd(com, VectorMake(0, -size, 0)));
  1867. FManager.AddNode(VectorAdd(com, VectorMake(size, 0, 0)));
  1868. FManager.AddNode(VectorAdd(com, VectorMake(-size, 0, 0)));
  1869. end;
  1870. begin
  1871. inherited;
  1872. // Move/Rotate NewtonObject if matrix are not equal in design time.
  1873. if (csDesigning in FOwnerBaseSceneObject.ComponentState) then
  1874. if not MatrixEquals(NewtonBodyMatrix, FOwnerBaseSceneObject.AbsoluteMatrix) then
  1875. SetNewtonBodyMatrix(FOwnerBaseSceneObject.AbsoluteMatrix);
  1876. NewtonBodyGetAABB(FNewtonBody, @(FAABBmin.AsVector), @(FAABBmax.AsVector));
  1877. if NewtonBodyGetSleepState(FNewtonBody) = 1 then
  1878. FManager.FCurrentColor := FManager.DebugOption.AABBColorSleep
  1879. else
  1880. FManager.FCurrentColor := FManager.DebugOption.AABBColor;
  1881. if mdShowAABB in FManager.DebugOption.NGDManagerDebugs then
  1882. DrawAABB(FAABBmin, FAABBmax);
  1883. if mdShowContact in FManager.DebugOption.NGDManagerDebugs then
  1884. DrawContact;
  1885. DrawForce; // Draw Force, AppliedForce and AppliedVelocity
  1886. if mdShowCenterOfMass in FManager.DebugOption.NGDManagerDebugs then
  1887. DrawCoM;
  1888. end;
  1889. procedure TGLNGDDynamic.SetAutoSleep(const Value: Boolean);
  1890. begin
  1891. FAutoSleep := Value;
  1892. if not(csDesigning in FOwnerBaseSceneObject.ComponentState) then
  1893. if Assigned(FManager) then
  1894. NewtonBodySetAutoSleep(FNewtonBody, Ord(FAutoSleep));
  1895. end;
  1896. procedure TGLNGDDynamic.SetDensity(const Value: Single);
  1897. var
  1898. inertia: TGLVector;
  1899. origin: TGLVector;
  1900. begin
  1901. if Assigned(FManager) then
  1902. if Value >= 0 then
  1903. begin
  1904. FDensity := Value;
  1905. FVolume := NewtonConvexCollisionCalculateVolume(FCollision);
  1906. NewtonConvexCollisionCalculateInertialMatrix(FCollision, @inertia, @origin);
  1907. if IsZero(FVolume, epsilon) then
  1908. begin
  1909. FVolume := FNullCollisionVolume;
  1910. inertia := VectorMake(FNullCollisionVolume, FNullCollisionVolume, FNullCollisionVolume, 0);
  1911. end;
  1912. FMass := FVolume * FDensity;
  1913. if not(csDesigning in FOwnerBaseSceneObject.ComponentState) then
  1914. NewtonBodySetMassMatrix(FNewtonBody, FMass, FMass * inertia.X, FMass * inertia.Y,
  1915. FMass * inertia.Z);
  1916. FCenterOfMass.AsVector := origin;
  1917. end;
  1918. end;
  1919. procedure TGLNGDDynamic.SetLinearDamping(const Value: Single);
  1920. begin
  1921. if (Value >= 0) and (Value <= 1) then
  1922. FLinearDamping := Value;
  1923. if not(csDesigning in FOwnerBaseSceneObject.ComponentState) then
  1924. if Assigned(FManager) then
  1925. NewtonBodySetLinearDamping(FNewtonBody, FLinearDamping);
  1926. end;
  1927. function TGLNGDDynamic.GetOmega: TGLVector;
  1928. begin
  1929. NewtonBodyGetOmega(FNewtonBody, @Result);
  1930. end;
  1931. procedure TGLNGDDynamic.SetOmega(const Omega: TGLVector);
  1932. begin
  1933. NewtonBodySetOmega(FNewtonBody, @Omega);
  1934. end;
  1935. function TGLNGDDynamic.GetVelocity: TGLVector;
  1936. begin
  1937. NewtonBodyGetVelocity(FNewtonBody, @Result);
  1938. end;
  1939. procedure TGLNGDDynamic.SetVelocity(const Velocity: TGLVector);
  1940. begin
  1941. NewtonBodySetVelocity(FNewtonBody, @Velocity);
  1942. end;
  1943. function TGLNGDDynamic.StoredDensity: Boolean;
  1944. begin
  1945. Result := not SameValue(FDensity, 1, epsilon);
  1946. end;
  1947. function TGLNGDDynamic.StoredLinearDamping: Boolean;
  1948. begin
  1949. Result := not SameValue(FLinearDamping, 0.1, epsilon);
  1950. end;
  1951. function TGLNGDDynamic.StoredNullCollisionVolume: Boolean;
  1952. begin
  1953. Result := not SameValue(FNullCollisionVolume, 0, epsilon);
  1954. end;
  1955. procedure TGLNGDDynamic.WriteToFiler(writer: TWriter);
  1956. begin
  1957. inherited;
  1958. with writer do
  1959. begin
  1960. WriteInteger(1); // Archive version
  1961. WriteBoolean(FAutoSleep);
  1962. WriteFloat(FLinearDamping);
  1963. WriteFloat(FDensity);
  1964. WriteBoolean(FUseGravity);
  1965. WriteFloat(FNullCollisionVolume);
  1966. end;
  1967. FForce.WriteToFiler(writer);
  1968. FTorque.WriteToFiler(writer);
  1969. FCenterOfMass.WriteToFiler(writer);
  1970. FAngularDamping.WriteToFiler(writer);
  1971. end;
  1972. procedure TGLNGDDynamic.ReadFromFiler(reader: TReader);
  1973. var
  1974. version: Integer;
  1975. begin
  1976. inherited;
  1977. with reader do
  1978. begin
  1979. version := ReadInteger; // read data version
  1980. Assert(version <= 1); // Archive version
  1981. FAutoSleep := ReadBoolean;
  1982. if version <= 0 then
  1983. FLinearDamping := ReadSingle
  1984. else
  1985. FLinearDamping := ReadFloat;
  1986. if version <= 0 then
  1987. FDensity := ReadSingle
  1988. else
  1989. FDensity := ReadFloat;
  1990. // if Version >= 1 then
  1991. FUseGravity := ReadBoolean;
  1992. if version <= 0 then
  1993. FNullCollisionVolume := ReadSingle
  1994. else
  1995. FNullCollisionVolume := ReadFloat;
  1996. end;
  1997. FForce.ReadFromFiler(reader);
  1998. FTorque.ReadFromFiler(reader);
  1999. FCenterOfMass.ReadFromFiler(reader);
  2000. FAngularDamping.ReadFromFiler(reader);
  2001. end;
  2002. procedure TGLNGDDynamic.Loaded;
  2003. begin
  2004. inherited;
  2005. if Assigned(FManager) then
  2006. begin
  2007. SetAutoSleep(FAutoSleep);
  2008. SetLinearDamping(FLinearDamping);
  2009. SetDensity(FDensity);
  2010. NotifyCenterOfMassChange(self);
  2011. NotifyAngularDampingChange(self);
  2012. end;
  2013. end;
  2014. class procedure TGLNGDDynamic.NewtonApplyForceAndTorque(const body: PNewtonBody; timestep: dFloat;
  2015. threadIndex: Integer); cdecl;
  2016. begin
  2017. TGLNGDDynamic(NewtonBodyGetUserData(body)).FApplyForceAndTorqueEvent(body, timestep, threadIndex);
  2018. end;
  2019. class procedure TGLNGDDynamic.NewtonSetTransform(const body: PNewtonBody; const matrix: PdFloat;
  2020. threadIndex: Integer); cdecl;
  2021. begin
  2022. TGLNGDDynamic(NewtonBodyGetUserData(body)).FSetTransformEvent(body, matrix, threadIndex);
  2023. end;
  2024. procedure TGLNGDDynamic.NotifyAngularDampingChange(Sender: TObject);
  2025. begin
  2026. FAngularDamping.OnNotifyChange := nil;
  2027. if (FAngularDamping.X >= 0) and (FAngularDamping.X <= 1) and (FAngularDamping.Y >= 0) and
  2028. (FAngularDamping.Y <= 1) and (FAngularDamping.Z >= 0) and (FAngularDamping.Z <= 1) then
  2029. if Assigned(FManager) then
  2030. NewtonBodySetAngularDamping(FNewtonBody, @(FAngularDamping.AsVector));
  2031. FAngularDamping.OnNotifyChange := NotifyAngularDampingChange;
  2032. end;
  2033. procedure TGLNGDDynamic.NotifyCenterOfMassChange(Sender: TObject);
  2034. begin
  2035. FCenterOfMass.OnNotifyChange := nil;
  2036. if Assigned(FManager) then
  2037. NewtonBodySetCentreOfMass(FNewtonBody, @(FCenterOfMass.AsVector));
  2038. FCenterOfMass.OnNotifyChange := NotifyCenterOfMassChange;
  2039. end;
  2040. procedure TGLNGDDynamic.OnApplyForceAndTorqueEvent(const cbody: PNewtonBody; timestep: dFloat;
  2041. threadIndex: Integer);
  2042. var
  2043. worldGravity: TGLVector;
  2044. begin
  2045. // Read Only: We get the force and torque resulting from every interaction on this body
  2046. NewtonBodyGetForce(cbody, @(FAppliedForce.AsVector));
  2047. NewtonBodyGetTorque(cbody, @(FAppliedTorque.AsVector));
  2048. NewtonBodyGetVelocity(cbody, @(FAppliedVelocity.AsVector));
  2049. NewtonBodyGetOmega(cbody, @(FAppliedOmega.AsVector));
  2050. // Raise Custom event
  2051. if Assigned(FCustomForceAndTorqueEvent) then
  2052. FCustomForceAndTorqueEvent(cbody, timestep, threadIndex)
  2053. else
  2054. begin
  2055. NewtonBodySetForce(cbody, @(Force.AsVector));
  2056. NewtonBodySetTorque(cbody, @(Torque.AsVector));
  2057. // Add Gravity from World
  2058. if FUseGravity then
  2059. begin
  2060. worldGravity := VectorScale(FManager.Gravity.AsVector, FMass);
  2061. NewtonBodyAddForce(cbody, @(worldGravity));
  2062. end;
  2063. end;
  2064. end;
  2065. procedure TGLNGDDynamic.OnSetTransformEvent(const cbody: PNewtonBody; const cmatrix: PdFloat;
  2066. threadIndex: Integer);
  2067. var
  2068. epsi: Single;
  2069. begin
  2070. // The Newton API does not support scale [scale modifie value in matrix],
  2071. // so this line reset scale of the glsceneObject to (1,1,1)
  2072. // to avoid crashing the application
  2073. epsi := 0.0001;
  2074. with FOwnerBaseSceneObject do
  2075. if not SameValue(Scale.X, 1.0, epsi) or not SameValue(Scale.Y, 1.0, epsi) or
  2076. not SameValue(Scale.Z, 1.0, epsi) then
  2077. begin
  2078. Scale.SetVector(1, 1, 1);
  2079. SetNewtonBodyMatrix(AbsoluteMatrix);
  2080. end
  2081. else
  2082. // Make the Position and orientation of the glscene-Object relative to the
  2083. // NewtonBody position and orientation.
  2084. FOwnerBaseSceneObject.AbsoluteMatrix := PGLMatrix(cmatrix)^;
  2085. end;
  2086. // ------------------------
  2087. // TGLNGDStatic
  2088. // ------------------------
  2089. procedure TGLNGDStatic.Render;
  2090. begin
  2091. inherited;
  2092. // Move/Rotate NewtonObject if matrix are not equal in run time.
  2093. if not MatrixEquals(NewtonBodyMatrix, FOwnerBaseSceneObject.AbsoluteMatrix) then
  2094. SetNewtonBodyMatrix(FOwnerBaseSceneObject.AbsoluteMatrix);
  2095. end;
  2096. class function TGLNGDStatic.FriendlyName: string;
  2097. begin
  2098. Result := 'NGD Static';
  2099. end;
  2100. // ------------------------
  2101. // TGLNGDSurfaceItem
  2102. // ------------------------
  2103. function TGLNGDSurfaceItem.GetDisplayName: string;
  2104. begin
  2105. if FDisplayName = '' then
  2106. FDisplayName := 'Iron';
  2107. Result := FDisplayName;
  2108. end;
  2109. procedure TGLNGDSurfaceItem.SetDisplayName(const Value: string);
  2110. begin
  2111. inherited;
  2112. FDisplayName := Value;
  2113. end;
  2114. // ------------------------
  2115. // TGLNGDSurfacePair
  2116. // ------------------------
  2117. constructor TGLNGDSurfacePair.Create(Collection: TCollection);
  2118. begin
  2119. inherited;
  2120. FSoftness := 0.1;
  2121. FElasticity := 0.4;
  2122. FCollidable := True;
  2123. FStaticFriction := 0.9;
  2124. FKineticFriction := 0.5;
  2125. FContinuousCollisionMode := False;
  2126. FThickness := False;
  2127. FAABBOverlapEvent := OnNewtonAABBOverlapEvent;
  2128. FContactProcessEvent := OnNewtonContactsProcessEvent;
  2129. FManager := TGLNGDManager(Collection.Owner);
  2130. FManager.RebuildAllMaterial;
  2131. end;
  2132. class function TGLNGDSurfacePair.NewtonAABBOverlap(const material: PNewtonMaterial;
  2133. const body0, body1: PNewtonBody; threadIndex: Integer): Integer; cdecl;
  2134. begin
  2135. Result := Ord(TGLNGDSurfacePair(NewtonMaterialGetMaterialPairUserData(material))
  2136. .FAABBOverlapEvent(material, body0, body1, threadIndex));
  2137. end;
  2138. class procedure TGLNGDSurfacePair.NewtonContactsProcess(const contact: PNewtonJoint;
  2139. timestep: dFloat; threadIndex: Integer); cdecl;
  2140. begin
  2141. TGLNGDSurfacePair(NewtonMaterialGetMaterialPairUserData
  2142. (NewtonContactGetMaterial(NewtonContactJointGetFirstContact(contact))))
  2143. .FContactProcessEvent(contact, timestep, threadIndex);
  2144. end;
  2145. function TGLNGDSurfacePair.OnNewtonAABBOverlapEvent(const cmaterial: PNewtonMaterial;
  2146. const cbody0, cbody1: PNewtonBody; threadIndex: Integer): Boolean;
  2147. begin
  2148. Result := True;
  2149. end;
  2150. procedure TGLNGDSurfacePair.OnNewtonContactsProcessEvent(const ccontact: PNewtonJoint;
  2151. timestep: dFloat; threadIndex: Integer);
  2152. begin
  2153. //
  2154. end;
  2155. procedure TGLNGDSurfacePair.SetCollidable(const Value: Boolean);
  2156. begin
  2157. FCollidable := Value;
  2158. FManager.RebuildAllMaterial;
  2159. end;
  2160. procedure TGLNGDSurfacePair.SetContinuousCollisionMode(const Value: Boolean);
  2161. begin
  2162. FContinuousCollisionMode := Value;
  2163. FManager.RebuildAllMaterial;
  2164. end;
  2165. procedure TGLNGDSurfacePair.SetElasticity(const Value: Single);
  2166. begin
  2167. if (Value >= 0) then
  2168. FElasticity := Value;
  2169. FManager.RebuildAllMaterial;
  2170. end;
  2171. procedure TGLNGDSurfacePair.SetKineticFriction(const Value: Single);
  2172. begin
  2173. if (Value >= 0) and (Value <= 1) then
  2174. FKineticFriction := Value;
  2175. FManager.RebuildAllMaterial;
  2176. end;
  2177. procedure TGLNGDSurfacePair.SetMaterialItems(const item1, item2: TGLNGDSurfaceItem);
  2178. begin
  2179. FSurfaceItem1 := item1;
  2180. FSurfaceItem2 := item2;
  2181. FManager.RebuildAllMaterial;
  2182. end;
  2183. procedure TGLNGDSurfacePair.SetSoftness(const Value: Single);
  2184. begin
  2185. if (Value >= 0) and (Value <= 1) then
  2186. FSoftness := Value;
  2187. FManager.RebuildAllMaterial;
  2188. end;
  2189. procedure TGLNGDSurfacePair.SetStaticFriction(const Value: Single);
  2190. begin
  2191. if (Value >= 0) and (Value <= 1) then
  2192. FStaticFriction := Value;
  2193. FManager.RebuildAllMaterial;
  2194. end;
  2195. procedure TGLNGDSurfacePair.SetThickness(const Value: Boolean);
  2196. begin
  2197. FThickness := Value;
  2198. FManager.RebuildAllMaterial;
  2199. end;
  2200. function TGLNGDSurfacePair.StoredElasticity: Boolean;
  2201. begin
  2202. Result := not SameValue(FElasticity, 0.4, epsilon);
  2203. end;
  2204. function TGLNGDSurfacePair.StoredKineticFriction: Boolean;
  2205. begin
  2206. Result := not SameValue(FKineticFriction, 0.5, epsilon);
  2207. end;
  2208. function TGLNGDSurfacePair.StoredSoftness: Boolean;
  2209. begin
  2210. Result := not SameValue(FSoftness, 0.1, epsilon);
  2211. end;
  2212. function TGLNGDSurfacePair.StoredStaticFriction: Boolean;
  2213. begin
  2214. Result := not SameValue(FStaticFriction, 0.9, epsilon);
  2215. end;
  2216. // ------------------------
  2217. // TGLNGDJoint
  2218. // ------------------------
  2219. constructor TGLNGDJoint.Create(Collection: TCollection);
  2220. begin
  2221. inherited;
  2222. FCollisionState := False;
  2223. FStiffness := 0.9;
  2224. FNewtonJoint := nil;
  2225. FNewtonUserJoint := nil;
  2226. FParentObject := nil;
  2227. FChildObject := nil;
  2228. FManager := TGLNGDManager(Collection.Owner);
  2229. FBallAndSocketOptions := TGLNGDJointPivot.Create(FManager, self);
  2230. FHingeOptions := TGLNGDJointPin.Create(FManager, self);
  2231. FSliderOptions := TGLNGDJointPin.Create(FManager, self);
  2232. FCorkscrewOptions := TGLNGDJointPin.Create(FManager, self);
  2233. FUniversalOptions := TGLNGDJointPin2.Create(FManager, self);
  2234. FCustomBallAndSocketOptions := TGLNGDJointBallAndSocket.Create(FManager, self);
  2235. FCustomHingeOptions := TGLNGDJointHinge.Create(FManager, self);
  2236. FCustomSliderOptions := TGLNGDJointSlider.Create(FManager, self);
  2237. FKinematicOptions := TGLNGDJointKinematicController.Create;
  2238. FUPVectorDirection := TGLCoordinates.CreateInitialized(self, YHmgVector, csVector);
  2239. FUPVectorDirection.OnNotifyChange := FManager.RebuildAllJoint;
  2240. end;
  2241. destructor TGLNGDJoint.Destroy;
  2242. begin
  2243. DestroyNewtonData;
  2244. FParentObject := nil;
  2245. FChildObject := nil;
  2246. // Free options
  2247. FBallAndSocketOptions.Free;
  2248. FHingeOptions.Free;
  2249. FSliderOptions.Free;
  2250. FCorkscrewOptions.Free;
  2251. FUniversalOptions.Free;
  2252. FCustomBallAndSocketOptions.Free;
  2253. FCustomHingeOptions.Free;
  2254. FCustomSliderOptions.Free;
  2255. FKinematicOptions.Free;
  2256. FUPVectorDirection.Free;
  2257. inherited;
  2258. end;
  2259. procedure TGLNGDJoint.DestroyNewtonData;
  2260. begin
  2261. if FNewtonJoint <> nil then
  2262. begin
  2263. Assert((FManager <> nil) and (FManager.FNewtonWorld <> nil));
  2264. NewtonDestroyJoint(FManager.FNewtonWorld, FNewtonJoint);
  2265. FNewtonJoint := nil;
  2266. end;
  2267. if FNewtonUserJoint <> nil then
  2268. begin
  2269. (* CustomDestroyJoint(FNewtonUserJoint); *) // from dJointLibrary.dll
  2270. FNewtonUserJoint := nil;
  2271. end;
  2272. end;
  2273. procedure TGLNGDJoint.KinematicControllerPick(pickpoint: TGLVector;
  2274. PickedActions: TGLNGDPickedActions);
  2275. begin
  2276. (* CustomDestroyJoint(FNewtonUserJoint); //from dJointLibrary.dll
  2277. if FJointType = nj_KinematicController then
  2278. if Assigned(FParentObject) then
  2279. begin
  2280. // Creates the joint
  2281. if PickedActions = paAttach then
  2282. begin
  2283. if not Assigned(FNewtonUserJoint) then
  2284. if Assigned(GetNGDDynamic(FParentObject).FNewtonBody) then
  2285. FNewtonUserJoint := CreateCustomKinematicController
  2286. (GetNGDDynamic(FParentObject).FNewtonBody, @pickpoint);
  2287. end;
  2288. // Change the TargetPoint
  2289. if (PickedActions = paMove) or (PickedActions = paAttach) then
  2290. begin
  2291. if Assigned(FNewtonUserJoint) then
  2292. begin
  2293. CustomKinematicControllerSetPickMode(FNewtonUserJoint,
  2294. Ord(FKinematicOptions.FPickModeLinear));
  2295. CustomKinematicControllerSetMaxLinearFriction(FNewtonUserJoint,
  2296. FKinematicOptions.FLinearFriction);
  2297. CustomKinematicControllerSetMaxAngularFriction(FNewtonUserJoint,
  2298. FKinematicOptions.FAngularFriction);
  2299. CustomKinematicControllerSetTargetPosit(FNewtonUserJoint, @pickpoint);
  2300. end;
  2301. end;
  2302. // Delete the joint
  2303. if PickedActions = paDetach then
  2304. begin
  2305. if Assigned(FNewtonUserJoint) then
  2306. begin
  2307. CustomDestroyJoint(FNewtonUserJoint);
  2308. FNewtonUserJoint := nil;
  2309. // Reset autosleep because this joint turns it off
  2310. NewtonBodySetAutoSleep(GetNGDDynamic(FParentObject).FNewtonBody,
  2311. Ord(GetNGDDynamic(FParentObject).AutoSleep));
  2312. end;
  2313. ParentObject := nil;
  2314. end;
  2315. end;
  2316. *)
  2317. end;
  2318. procedure TGLNGDJoint.Render;
  2319. procedure DrawPivot(pivot: TGLVector);
  2320. var
  2321. size: Single;
  2322. begin
  2323. size := FManager.DebugOption.DotAxisSize;
  2324. FManager.FCurrentColor := FManager.DebugOption.JointPivotColor;
  2325. FManager.AddNode(VectorAdd(pivot, VectorMake(0, 0, size)));
  2326. FManager.AddNode(VectorAdd(pivot, VectorMake(0, 0, -size)));
  2327. FManager.AddNode(VectorAdd(pivot, VectorMake(0, size, 0)));
  2328. FManager.AddNode(VectorAdd(pivot, VectorMake(0, -size, 0)));
  2329. FManager.AddNode(VectorAdd(pivot, VectorMake(size, 0, 0)));
  2330. FManager.AddNode(VectorAdd(pivot, VectorMake(-size, 0, 0)));
  2331. end;
  2332. procedure DrawPin(pin, pivot: TGLVector);
  2333. begin
  2334. FManager.FCurrentColor := FManager.DebugOption.JointAxisColor;
  2335. FManager.AddNode(VectorAdd(pivot, pin));
  2336. FManager.AddNode(VectorAdd(pivot, VectorNegate(pin)));
  2337. end;
  2338. procedure DrawJoint(pivot: TGLVector);
  2339. begin
  2340. FManager.FCurrentColor := FManager.DebugOption.CustomColor;
  2341. FManager.AddNode(FParentObject.AbsolutePosition);
  2342. FManager.AddNode(pivot);
  2343. FManager.AddNode(pivot);
  2344. FManager.AddNode(FChildObject.AbsolutePosition);
  2345. end;
  2346. procedure DrawKinematic;
  2347. var
  2348. pickedMatrix: TGLMatrix;
  2349. size: Single;
  2350. begin
  2351. size := FManager.DebugOption.DotAxisSize;
  2352. /// From dJointLibrary.dll
  2353. /// CustomKinematicControllerGetTargetMatrix(FNewtonUserJoint, @pickedMatrix);
  2354. FManager.FCurrentColor := FManager.DebugOption.JointAxisColor;
  2355. FManager.AddNode(FParentObject.AbsolutePosition);
  2356. FManager.AddNode(pickedMatrix.W);
  2357. FManager.FCurrentColor := FManager.DebugOption.JointPivotColor;
  2358. FManager.AddNode(VectorAdd(pickedMatrix.W, VectorMake(0, 0, size)));
  2359. FManager.AddNode(VectorAdd(pickedMatrix.W, VectorMake(0, 0, -size)));
  2360. FManager.AddNode(VectorAdd(pickedMatrix.W, VectorMake(0, size, 0)));
  2361. FManager.AddNode(VectorAdd(pickedMatrix.W, VectorMake(0, -size, 0)));
  2362. FManager.AddNode(VectorAdd(pickedMatrix.W, VectorMake(size, 0, 0)));
  2363. FManager.AddNode(VectorAdd(pickedMatrix.W, VectorMake(-size, 0, 0)));
  2364. end;
  2365. begin
  2366. case FJointType of
  2367. nj_BallAndSocket:
  2368. if Assigned(FParentObject) and Assigned(FChildObject) then
  2369. begin
  2370. DrawJoint(FBallAndSocketOptions.FPivotPoint.AsVector);
  2371. DrawPivot(FBallAndSocketOptions.FPivotPoint.AsVector);
  2372. end;
  2373. nj_Hinge:
  2374. if Assigned(FParentObject) and Assigned(FChildObject) then
  2375. begin
  2376. DrawJoint(FHingeOptions.FPivotPoint.AsVector);
  2377. DrawPin(FHingeOptions.FPinDirection.AsVector, FHingeOptions.FPivotPoint.AsVector);
  2378. DrawPivot(FHingeOptions.FPivotPoint.AsVector);
  2379. end;
  2380. nj_Slider:
  2381. if Assigned(FParentObject) and Assigned(FChildObject) then
  2382. begin
  2383. DrawJoint(FSliderOptions.FPivotPoint.AsVector);
  2384. DrawPin(FSliderOptions.FPinDirection.AsVector, FSliderOptions.FPivotPoint.AsVector);
  2385. DrawPivot(FSliderOptions.FPivotPoint.AsVector);
  2386. end;
  2387. nj_Corkscrew:
  2388. if Assigned(FParentObject) and Assigned(FChildObject) then
  2389. begin
  2390. DrawJoint(FCorkscrewOptions.FPivotPoint.AsVector);
  2391. DrawPin(FCorkscrewOptions.FPinDirection.AsVector, FCorkscrewOptions.FPivotPoint.AsVector);
  2392. DrawPivot(FCorkscrewOptions.FPivotPoint.AsVector);
  2393. end;
  2394. nj_Universal:
  2395. if Assigned(FParentObject) and Assigned(FChildObject) then
  2396. begin
  2397. DrawJoint(FUniversalOptions.FPivotPoint.AsVector);
  2398. DrawPin(FUniversalOptions.FPinDirection.AsVector, FUniversalOptions.FPivotPoint.AsVector);
  2399. DrawPin(FUniversalOptions.FPinDirection2.AsVector, FUniversalOptions.FPivotPoint.AsVector);
  2400. DrawPivot(FUniversalOptions.FPivotPoint.AsVector);
  2401. end;
  2402. nj_CustomBallAndSocket:
  2403. if Assigned(FParentObject) and Assigned(FChildObject) then
  2404. begin
  2405. DrawJoint(FCustomBallAndSocketOptions.FPivotPoint.AsVector);
  2406. DrawPivot(FCustomBallAndSocketOptions.FPivotPoint.AsVector);
  2407. end;
  2408. nj_CustomHinge:
  2409. if Assigned(FParentObject) and Assigned(FChildObject) then
  2410. begin
  2411. DrawJoint(FCustomHingeOptions.FPivotPoint.AsVector);
  2412. DrawPin(FCustomHingeOptions.FPinDirection.AsVector,
  2413. FCustomHingeOptions.FPivotPoint.AsVector);
  2414. DrawPivot(FCustomHingeOptions.FPivotPoint.AsVector);
  2415. end;
  2416. nj_CustomSlider:
  2417. if Assigned(FParentObject) and Assigned(FChildObject) then
  2418. begin
  2419. DrawJoint(FCustomSliderOptions.FPivotPoint.AsVector);
  2420. DrawPin(FCustomSliderOptions.FPinDirection.AsVector,
  2421. FCustomSliderOptions.FPivotPoint.AsVector);
  2422. DrawPivot(FCustomSliderOptions.FPivotPoint.AsVector);
  2423. end;
  2424. nj_UpVector:
  2425. if Assigned(FParentObject) then
  2426. begin // special
  2427. FManager.FCurrentColor := FManager.DebugOption.JointAxisColor;
  2428. FManager.AddNode(FParentObject.AbsolutePosition);
  2429. FManager.AddNode(VectorAdd(FParentObject.AbsolutePosition, FUPVectorDirection.AsVector));
  2430. end;
  2431. nj_KinematicController:
  2432. if Assigned(FParentObject) and Assigned(FNewtonUserJoint) then
  2433. begin // special
  2434. DrawKinematic;
  2435. end;
  2436. end;
  2437. end;
  2438. procedure TGLNGDJoint.SetChildObject(const Value: TGLBaseSceneObject);
  2439. begin
  2440. FChildObject := Value;
  2441. FManager.RebuildAllJoint(self);
  2442. end;
  2443. procedure TGLNGDJoint.SetCollisionState(const Value: Boolean);
  2444. begin
  2445. FCollisionState := Value;
  2446. FManager.RebuildAllJoint(self);
  2447. end;
  2448. procedure TGLNGDJoint.SetJointType(const Value: TGLNGDJoints);
  2449. begin
  2450. FJointType := Value;
  2451. FManager.RebuildAllJoint(self);
  2452. end;
  2453. procedure TGLNGDJoint.SetParentObject(const Value: TGLBaseSceneObject);
  2454. begin
  2455. FParentObject := Value;
  2456. FManager.RebuildAllJoint(self);
  2457. end;
  2458. procedure TGLNGDJoint.SetStiffness(const Value: Single);
  2459. begin
  2460. if (Value >= 0) and (Value <= 1) then
  2461. begin
  2462. FStiffness := Value;
  2463. FManager.RebuildAllJoint(self);
  2464. end;
  2465. end;
  2466. function TGLNGDJoint.StoredStiffness: Boolean;
  2467. begin
  2468. Result := not SameValue(FStiffness, 0.9, epsilon);
  2469. end;
  2470. // ------------------------
  2471. // TGLNGDJointPivot
  2472. // ------------------------
  2473. constructor TGLNGDJointPivot.Create(AOwner: TComponent; aOuter: TGLNGDJoint);
  2474. begin
  2475. FManager := AOwner as TGLNGDManager;
  2476. FOuter := aOuter;
  2477. FPivotPoint := TGLCoordinates.CreateInitialized(aOuter, NullHMGPoint, csPoint);
  2478. FPivotPoint.OnNotifyChange := FManager.RebuildAllJoint;
  2479. end;
  2480. destructor TGLNGDJointPivot.Destroy;
  2481. begin
  2482. FPivotPoint.Free;
  2483. inherited;
  2484. end;
  2485. // ------------------------
  2486. // TGLNGDJointPin
  2487. // ------------------------
  2488. constructor TGLNGDJointPin.Create(AOwner: TComponent; aOuter: TGLNGDJoint);
  2489. begin
  2490. inherited;
  2491. FPinDirection := TGLCoordinates.CreateInitialized(aOuter, NullHmgVector, csVector);
  2492. FPinDirection.OnNotifyChange := FManager.RebuildAllJoint;
  2493. end;
  2494. destructor TGLNGDJointPin.Destroy;
  2495. begin
  2496. FPinDirection.Free;
  2497. inherited;
  2498. end;
  2499. // ------------------------
  2500. // TGLNGDJointPin2
  2501. // ------------------------
  2502. constructor TGLNGDJointPin2.Create(AOwner: TComponent; aOuter: TGLNGDJoint);
  2503. begin
  2504. inherited;
  2505. FPinDirection2 := TGLCoordinates.CreateInitialized(aOuter, NullHmgVector, csVector);
  2506. FPinDirection2.OnNotifyChange := FManager.RebuildAllJoint;
  2507. end;
  2508. destructor TGLNGDJointPin2.Destroy;
  2509. begin
  2510. FPinDirection2.Free;
  2511. inherited;
  2512. end;
  2513. // ------------------------
  2514. // TGLNGDJointBallAndSocket
  2515. // ------------------------
  2516. constructor TGLNGDJointBallAndSocket.Create(AOwner: TComponent; aOuter: TGLNGDJoint);
  2517. begin
  2518. inherited;
  2519. FConeAngle := 90;
  2520. FMinTwistAngle := -90;
  2521. FMaxTwistAngle := 90;
  2522. end;
  2523. procedure TGLNGDJointBallAndSocket.SetConeAngle(const Value: Single);
  2524. begin
  2525. FConeAngle := Value;
  2526. FManager.RebuildAllJoint(FOuter);
  2527. end;
  2528. procedure TGLNGDJointBallAndSocket.SetMaxTwistAngle(const Value: Single);
  2529. begin
  2530. FMaxTwistAngle := Value;
  2531. FManager.RebuildAllJoint(FOuter);
  2532. end;
  2533. procedure TGLNGDJointBallAndSocket.SetMinTwistAngle(const Value: Single);
  2534. begin
  2535. FMinTwistAngle := Value;
  2536. FManager.RebuildAllJoint(FOuter);
  2537. end;
  2538. function TGLNGDJointBallAndSocket.StoredConeAngle: Boolean;
  2539. begin
  2540. Result := not SameValue(FConeAngle, 90, epsilon);
  2541. end;
  2542. function TGLNGDJointBallAndSocket.StoredMaxTwistAngle: Boolean;
  2543. begin
  2544. Result := not SameValue(FMaxTwistAngle, 90, epsilon);
  2545. end;
  2546. function TGLNGDJointBallAndSocket.StoredMinTwistAngle: Boolean;
  2547. begin
  2548. Result := not SameValue(FMinTwistAngle, -90, epsilon);
  2549. end;
  2550. // ------------------------
  2551. // TGLNGDJointHinge
  2552. // ------------------------
  2553. constructor TGLNGDJointHinge.Create(AOwner: TComponent; aOuter: TGLNGDJoint);
  2554. begin
  2555. inherited;
  2556. FMinAngle := -90;
  2557. FMaxAngle := 90;
  2558. end;
  2559. procedure TGLNGDJointHinge.SetMaxAngle(const Value: Single);
  2560. begin
  2561. FMaxAngle := Value;
  2562. FManager.RebuildAllJoint(FOuter);
  2563. end;
  2564. procedure TGLNGDJointHinge.SetMinAngle(const Value: Single);
  2565. begin
  2566. FMinAngle := Value;
  2567. FManager.RebuildAllJoint(FOuter);
  2568. end;
  2569. function TGLNGDJointHinge.StoredMaxAngle: Boolean;
  2570. begin
  2571. Result := not SameValue(FMaxAngle, 90, epsilon);
  2572. end;
  2573. function TGLNGDJointHinge.StoredMinAngle: Boolean;
  2574. begin
  2575. Result := not SameValue(FMinAngle, -90, epsilon);
  2576. end;
  2577. // ------------------------
  2578. // TGLNGDJointSlider
  2579. // ------------------------
  2580. constructor TGLNGDJointSlider.Create(AOwner: TComponent; aOuter: TGLNGDJoint);
  2581. begin
  2582. inherited;
  2583. FMinDistance := -10;
  2584. FMaxDistance := 10;
  2585. end;
  2586. procedure TGLNGDJointSlider.SetMaxDistance(const Value: Single);
  2587. begin
  2588. FMaxDistance := Value;
  2589. FManager.RebuildAllJoint(FOuter);
  2590. end;
  2591. procedure TGLNGDJointSlider.SetMinDistance(const Value: Single);
  2592. begin
  2593. FMinDistance := Value;
  2594. FManager.RebuildAllJoint(FOuter);
  2595. end;
  2596. function TGLNGDJointSlider.StoredMaxDistance: Boolean;
  2597. begin
  2598. Result := not SameValue(FMaxDistance, 10, epsilon);
  2599. end;
  2600. function TGLNGDJointSlider.StoredMinDistance: Boolean;
  2601. begin
  2602. Result := not SameValue(FMinDistance, -10, epsilon);
  2603. end;
  2604. // ----------------------------------
  2605. // TGLNGDJointKinematicController
  2606. // ----------------------------------
  2607. constructor TGLNGDJointKinematicController.Create;
  2608. begin
  2609. FPickModeLinear := False;
  2610. FLinearFriction := 750;
  2611. FAngularFriction := 250;
  2612. end;
  2613. function TGLNGDJointKinematicController.StoredAngularFriction: Boolean;
  2614. begin
  2615. Result := not SameValue(FAngularFriction, 250, epsilon);
  2616. end;
  2617. function TGLNGDJointKinematicController.StoredLinearFriction: Boolean;
  2618. begin
  2619. Result := not SameValue(FLinearFriction, 750, epsilon);
  2620. end;
  2621. // ------------------------
  2622. // TGLNGDBehaviourList
  2623. // ------------------------
  2624. function TGLNGDBehaviourList.GetBehav(index: Integer): TGLNGDBehaviour;
  2625. begin
  2626. Result := Items[index];
  2627. end;
  2628. procedure TGLNGDBehaviourList.PutBehav(index: Integer; Item: TGLNGDBehaviour);
  2629. begin
  2630. inherited put(index, Item);
  2631. end;
  2632. // ------------------------------------------------------------------
  2633. initialization
  2634. // ------------------------------------------------------------------
  2635. RegisterXCollectionItemClass(TGLNGDDynamic);
  2636. RegisterXCollectionItemClass(TGLNGDStatic);
  2637. // ------------------------------------------------------------------
  2638. finalization
  2639. // ------------------------------------------------------------------
  2640. UnregisterXCollectionItemClass(TGLNGDDynamic);
  2641. UnregisterXCollectionItemClass(TGLNGDStatic);
  2642. // CloseNGD;
  2643. end.