NGD.Manager.pas 96 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522252325242525252625272528252925302531253225332534253525362537253825392540254125422543254425452546254725482549255025512552255325542555255625572558255925602561256225632564256525662567256825692570257125722573257425752576257725782579258025812582258325842585258625872588258925902591259225932594259525962597259825992600260126022603260426052606260726082609261026112612261326142615261626172618261926202621262226232624262526262627262826292630263126322633263426352636263726382639264026412642264326442645264626472648264926502651265226532654265526562657265826592660266126622663266426652666266726682669267026712672267326742675267626772678267926802681268226832684268526862687268826892690269126922693269426952696269726982699270027012702270327042705270627072708270927102711271227132714271527162717271827192720272127222723272427252726272727282729273027312732273327342735273627372738273927402741274227432744274527462747274827492750275127522753275427552756275727582759276027612762276327642765276627672768276927702771277227732774277527762777277827792780278127822783278427852786278727882789279027912792279327942795279627972798279928002801280228032804280528062807280828092810281128122813281428152816281728182819282028212822282328242825282628272828282928302831283228332834283528362837283828392840284128422843284428452846284728482849285028512852285328542855285628572858285928602861286228632864286528662867286828692870287128722873287428752876287728782879288028812882288328842885288628872888288928902891289228932894289528962897289828992900290129022903290429052906290729082909291029112912291329142915291629172918291929202921292229232924292529262927292829292930293129322933293429352936293729382939294029412942294329442945294629472948294929502951295229532954
  1. //
  2. // The multimedia graphics platform GLScene https://github.com/glscene
  3. //
  4. unit NGD.Manager;
  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 GLScene.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. /// NGD.NewtonImport, // new version 4.0
  19. GLS.VectorTypes,
  20. GLS.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. GLS.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,
  1339. @collisionOffsetMatrix);
  1340. end
  1341. else if (FOwnerBaseSceneObject is TGLSphere) then
  1342. begin
  1343. with (FOwnerBaseSceneObject as TGLSphere) do
  1344. Result := NewtonCreateSphere(FManager.FNewtonWorld, Radius, Radius, Radius, 0,
  1345. @collisionOffsetMatrix);
  1346. end
  1347. else if (FOwnerBaseSceneObject is TGLCone) then
  1348. begin
  1349. collisionOffsetMatrix := MatrixMultiply(collisionOffsetMatrix, CreateRotationMatrixZ(Pi / 2.0));
  1350. with (FOwnerBaseSceneObject as TGLCone) do
  1351. Result := NewtonCreateCone(FManager.FNewtonWorld, BottomRadius, Height, 0,
  1352. @collisionOffsetMatrix);
  1353. end
  1354. else if (FOwnerBaseSceneObject is TGLCapsule) then
  1355. begin
  1356. collisionOffsetMatrix := MatrixMultiply(collisionOffsetMatrix, CreateRotationMatrixY(Pi / 2.0));
  1357. with (FOwnerBaseSceneObject as TGLCapsule) do
  1358. // Use Cylinder shape for buoyancy
  1359. Result := NewtonCreateCapsule(FManager.FNewtonWorld, Radius, Height + 2 * Radius, 0,
  1360. @collisionOffsetMatrix);
  1361. end
  1362. else if (FOwnerBaseSceneObject is TGLCylinder) then
  1363. begin
  1364. collisionOffsetMatrix := MatrixMultiply(collisionOffsetMatrix, CreateRotationMatrixZ(Pi / 2.0));
  1365. with (FOwnerBaseSceneObject as TGLCylinder) do
  1366. Result := NewtonCreateCylinder(FManager.FNewtonWorld, BottomRadius, Height, 0,
  1367. @collisionOffsetMatrix);
  1368. end
  1369. else
  1370. Result := GetNullCollision;
  1371. end;
  1372. function TGLNGDBehaviour.GetTreeCollision: PNewtonCollision;
  1373. var
  1374. meshIndex, triangleIndex: Integer;
  1375. triangleList: TGLAffineVectorList;
  1376. v: array [0 .. 2] of TAffineVector;
  1377. begin
  1378. if FOwnerBaseSceneObject is TGLBaseMesh then
  1379. begin
  1380. with (FOwnerBaseSceneObject as TGLBaseMesh) do
  1381. begin
  1382. Result := NewtonCreateTreeCollision(FManager.FNewtonWorld, 0);
  1383. NewtonTreeCollisionBeginBuild(Result);
  1384. for meshIndex := 0 to MeshObjects.Count - 1 do
  1385. begin
  1386. triangleList := MeshObjects[meshIndex].ExtractTriangles;
  1387. for triangleIndex := 0 to triangleList.Count - 1 do
  1388. begin
  1389. if triangleIndex mod 3 = 0 then
  1390. begin
  1391. v[0] := triangleList.Items[triangleIndex];
  1392. // ScaleVector(v[0], FOwnerBaseSceneObject.Scale.X);
  1393. v[1] := triangleList.Items[triangleIndex + 1];
  1394. // ScaleVector(v[1], FOwnerBaseSceneObject.Scale.Y);
  1395. v[2] := triangleList.Items[triangleIndex + 2];
  1396. // ScaleVector(v[2], FOwnerBaseSceneObject.Scale.Z);
  1397. NewtonTreeCollisionAddFace(Result, 3, @(v), SizeOf(TAffineVector), 1);
  1398. end;
  1399. end;
  1400. triangleList.Free;
  1401. end;
  1402. NewtonTreeCollisionEndBuild(Result, Ord(FTreeCollisionOptimize));
  1403. end;
  1404. end
  1405. else
  1406. Result := GetNullCollision;
  1407. end;
  1408. procedure TGLNGDBehaviour.Initialize;
  1409. begin
  1410. FInitialized := True;
  1411. if Assigned(FManager) then
  1412. begin
  1413. // Creates NewtonBody with null collision
  1414. FCollision := NewtonCreateNull(FManager.FNewtonWorld);
  1415. FNewtonBodyMatrix := FOwnerBaseSceneObject.AbsoluteMatrix;
  1416. FNewtonBody := NewtonCreateBody(FManager.FNewtonWorld, FCollision, @FNewtonBodyMatrix);
  1417. // Release NewtonCollision
  1418. NewtonReleaseCollision(FManager.FNewtonWorld, FCollision);
  1419. // Set Link between glscene and newton
  1420. NewtonBodySetUserdata(FNewtonBody, self);
  1421. // Set position and orientation
  1422. SetNewtonBodyMatrix(FOwnerBaseSceneObject.AbsoluteMatrix);
  1423. // Set Collision
  1424. UpdCollision;
  1425. end;
  1426. end;
  1427. procedure TGLNGDBehaviour.Loaded;
  1428. var
  1429. mng: TComponent;
  1430. begin
  1431. inherited;
  1432. if FManagerName <> '' then
  1433. begin
  1434. mng := FindManager(TGLNGDManager, FManagerName);
  1435. if Assigned(mng) then
  1436. Manager := TGLNGDManager(mng);
  1437. FManagerName := '';
  1438. end;
  1439. if Assigned(FManager) then
  1440. begin
  1441. SetContinuousCollisionMode(FContinuousCollisionMode);
  1442. end;
  1443. end;
  1444. class procedure TGLNGDBehaviour.NewtonCollisionIterator(const userData: Pointer;
  1445. vertexCount: Integer; const faceArray: PdFloat; faceId: Integer)cdecl;
  1446. begin
  1447. TGLNGDBehaviour(userData).FCollisionIteratorEvent(userData, vertexCount, faceArray, faceId);
  1448. end;
  1449. // Serializes are called by NGDBehaviour to save and load collision in file
  1450. // It's better to save/load big collisions [over 50000 polygones] to reduce
  1451. // loading time
  1452. class procedure TGLNGDBehaviour.NewtonDeserialize(serializeHandle, buffer: Pointer;
  1453. size: Cardinal)cdecl;
  1454. begin
  1455. TFileStream(serializeHandle).read(buffer^, size);
  1456. end;
  1457. class procedure TGLNGDBehaviour.NewtonSerialize(serializeHandle: Pointer; const buffer: Pointer;
  1458. size: Cardinal)cdecl;
  1459. begin
  1460. TFileStream(serializeHandle).write(buffer^, size);
  1461. end;
  1462. procedure TGLNGDBehaviour.OnCollisionIteratorEvent(const userData: Pointer; vertexCount: Integer;
  1463. const cfaceArray: PdFloat; faceId: Integer);
  1464. var
  1465. I: Integer;
  1466. v0, v1: array [0 .. 2] of Single;
  1467. vA: array of Single;
  1468. begin
  1469. // This algorithme draw Collision Shape for Debuggin.
  1470. // Taken to Sascha Willems in SDLNewton-Demo at
  1471. // http://www.saschawillems.de/?page_id=82
  1472. // Leave if there is no or to much vertex
  1473. if (vertexCount = 0) then
  1474. exit;
  1475. SetLength(vA, vertexCount * 3);
  1476. Move(cfaceArray^, vA[0], vertexCount * 3 * SizeOf(Single));
  1477. v0[0] := vA[(vertexCount - 1) * 3];
  1478. v0[1] := vA[(vertexCount - 1) * 3 + 1];
  1479. v0[2] := vA[(vertexCount - 1) * 3 + 2];
  1480. for I := 0 to vertexCount - 1 do
  1481. begin
  1482. v1[0] := vA[I * 3];
  1483. v1[1] := vA[I * 3 + 1];
  1484. v1[2] := vA[I * 3 + 2];
  1485. FManager.AddNode(v0[0], v0[1], v0[2]);
  1486. FManager.AddNode(v1[0], v1[1], v1[2]);
  1487. v0 := v1;
  1488. end;
  1489. end;
  1490. procedure TGLNGDBehaviour.Reinitialize;
  1491. begin
  1492. if Initialized then
  1493. begin
  1494. // Set Appropriate NewtonCollision
  1495. UpdCollision();
  1496. // Set position and orientation
  1497. SetNewtonBodyMatrix(FOwnerBaseSceneObject.AbsoluteMatrix);
  1498. end;
  1499. Loaded;
  1500. end;
  1501. procedure TGLNGDBehaviour.Render;
  1502. var
  1503. M: TGLMatrix;
  1504. begin
  1505. // Rebuild collision in design time
  1506. if (csDesigning in FOwnerBaseSceneObject.ComponentState) then
  1507. Reinitialize;
  1508. if self is TGLNGDDynamic then
  1509. FManager.FCurrentColor := FManager.DebugOption.GeomColorDyn
  1510. else
  1511. FManager.FCurrentColor := FManager.DebugOption.GeomColorStat;
  1512. M := FOwnerBaseSceneObject.AbsoluteMatrix;
  1513. if mdShowGeometry in FManager.DebugOption.NGDManagerDebugs then
  1514. NewtonCollisionForEachPolygonDo(FCollision, @M, @TGLNGDBehaviour.NewtonCollisionIterator, self);
  1515. end;
  1516. // In this procedure, we assign collision to body
  1517. // [Because when initialised, the collision for body is type NULL]
  1518. procedure TGLNGDBehaviour.UpdCollision;
  1519. var
  1520. collisionInfoRecord: TNewtonCollisionInfoRecord;
  1521. begin
  1522. case FNewtonCollisions of
  1523. nc_Primitive:
  1524. FCollision := GetPrimitiveCollision;
  1525. nc_Convex:
  1526. FCollision := GetConvexCollision;
  1527. nc_BBox:
  1528. FCollision := GetBBoxCollision;
  1529. nc_BSphere:
  1530. FCollision := GetBSphereCollision;
  1531. nc_Tree:
  1532. FCollision := GetTreeCollision;
  1533. nc_Mesh:
  1534. FCollision := GetMeshCollision;
  1535. nc_Null:
  1536. FCollision := GetNullCollision;
  1537. nc_HeightField:
  1538. FCollision := GetHeightFieldCollision;
  1539. nc_NGDFile:
  1540. FCollision := GetNGDFileCollision;
  1541. end;
  1542. if Assigned(FCollision) then
  1543. begin
  1544. NewtonBodySetCollision(FNewtonBody, FCollision);
  1545. // The API Ask for releasing Collision to avoid memory leak
  1546. NewtonCollisionGetInfo(FCollision, @collisionInfoRecord);
  1547. if collisionInfoRecord.m_collisionType > 2 then
  1548. NewtonReleaseCollision(FManager.FNewtonWorld, FCollision);
  1549. end;
  1550. end;
  1551. procedure TGLNGDBehaviour.SetContinuousCollisionMode(const Value: Boolean);
  1552. begin
  1553. // for continue collision to be active the continue collision mode must on
  1554. // the material pair of the colliding bodies as well as on at
  1555. // least one of the two colliding bodies.
  1556. // see NewtonBodySetContinuousCollisionMode
  1557. // see NewtonMaterialSetContinuousCollisionMode
  1558. FContinuousCollisionMode := Value;
  1559. if not(csDesigning in FOwnerBaseSceneObject.ComponentState) then
  1560. if Assigned(FManager) then
  1561. NewtonBodySetContinuousCollisionMode(FNewtonBody, Ord(Value));
  1562. end;
  1563. procedure TGLNGDBehaviour.SetHeightFieldOptions(const Value: TGLNGDHeightField);
  1564. begin
  1565. FHeightFieldOptions := Value;
  1566. Reinitialize;
  1567. end;
  1568. procedure TGLNGDBehaviour.SetManager(Value: TGLNGDManager);
  1569. begin
  1570. if FManager <> Value then
  1571. begin
  1572. if Assigned(FManager) then
  1573. begin
  1574. if Initialized then
  1575. Finalize;
  1576. FManager.FNGDBehaviours.Remove(self);
  1577. // FManager.NotifyChange(self);
  1578. end;
  1579. FManager := Value;
  1580. if Assigned(FManager) then
  1581. begin
  1582. Initialize;
  1583. FManager.FNGDBehaviours.Add(self);
  1584. FManager.NotifyChange(self);
  1585. end;
  1586. end;
  1587. end;
  1588. procedure TGLNGDBehaviour.SetNewtonBodyMatrix(const Value: TGLMatrix);
  1589. begin
  1590. FNewtonBodyMatrix := Value;
  1591. if Assigned(FManager) then
  1592. NewtonBodySetmatrix(FNewtonBody, @FNewtonBodyMatrix);
  1593. end;
  1594. procedure TGLNGDBehaviour.SetNewtonCollisions(const Value: TGLNGDCollisions);
  1595. begin
  1596. FNewtonCollisions := Value;
  1597. if Assigned(FManager) then
  1598. UpdCollision;
  1599. end;
  1600. procedure TGLNGDBehaviour.SetNewtonSurfaceItem(const Value: TGLNGDSurfaceItem);
  1601. begin
  1602. FSurfaceItem := Value;
  1603. FManager.RebuildAllMaterial;
  1604. end;
  1605. function TGLNGDBehaviour.StoredTolerance: Boolean;
  1606. begin
  1607. Result := not SameValue(FConvexCollisionTolerance, 0.01, epsilon);
  1608. end;
  1609. class function TGLNGDBehaviour.UniqueItem: Boolean;
  1610. begin
  1611. Result := True;
  1612. end;
  1613. procedure TGLNGDBehaviour.ReadFromFiler(reader: TReader);
  1614. var
  1615. version: Integer;
  1616. begin
  1617. inherited;
  1618. with reader do
  1619. begin
  1620. version := ReadInteger; // read data version
  1621. Assert(version <= 1); // Archive version
  1622. FManagerName := ReadString;
  1623. FContinuousCollisionMode := ReadBoolean;
  1624. read(FNewtonCollisions, SizeOf(TGLNGDCollisions));
  1625. FTreeCollisionOptimize := ReadBoolean;
  1626. if version <= 0 then
  1627. FConvexCollisionTolerance := ReadSingle
  1628. else
  1629. FConvexCollisionTolerance := ReadFloat;
  1630. FFileCollision := ReadString;
  1631. end;
  1632. end;
  1633. procedure TGLNGDBehaviour.WriteToFiler(writer: TWriter);
  1634. begin
  1635. inherited;
  1636. with writer do
  1637. begin
  1638. WriteInteger(1); // Archive version
  1639. if Assigned(FManager) then
  1640. WriteString(FManager.GetNamePath)
  1641. else
  1642. WriteString('');
  1643. WriteBoolean(FContinuousCollisionMode);
  1644. write(FNewtonCollisions, SizeOf(TGLNGDCollisions));
  1645. WriteBoolean(FTreeCollisionOptimize);
  1646. WriteFloat(FConvexCollisionTolerance);
  1647. WriteString(FFileCollision);
  1648. end;
  1649. end;
  1650. procedure TGLNGDBehaviour.Serialize(filename: string);
  1651. var
  1652. MyFile: TFileStream;
  1653. begin
  1654. MyFile := TFileStream.Create(filename, fmCreate or fmOpenReadWrite);
  1655. NewtonCollisionSerialize(FManager.FNewtonWorld, FCollision, @TGLNGDBehaviour.NewtonSerialize,
  1656. Pointer(MyFile));
  1657. MyFile.Free;
  1658. end;
  1659. procedure TGLNGDBehaviour.DeSerialize(filename: string);
  1660. var
  1661. MyFile: TFileStream;
  1662. collisionInfoRecord: TNewtonCollisionInfoRecord;
  1663. begin
  1664. MyFile := TFileStream.Create(filename, fmOpenRead);
  1665. FCollision := NewtonCreateCollisionFromSerialization(FManager.FNewtonWorld,
  1666. @TGLNGDBehaviour.NewtonDeserialize, Pointer(MyFile));
  1667. // SetCollision;
  1668. NewtonBodySetCollision(FNewtonBody, FCollision);
  1669. // Release collision
  1670. NewtonCollisionGetInfo(FCollision, @collisionInfoRecord);
  1671. if collisionInfoRecord.m_collisionType > 2 then
  1672. NewtonReleaseCollision(FManager.FNewtonWorld, FCollision);
  1673. MyFile.Free;
  1674. end;
  1675. // -------------------------
  1676. // TGLNGDDynamic
  1677. // -------------------------
  1678. procedure TGLNGDDynamic.AddImpulse(const veloc, pointposit: TGLVector);
  1679. begin
  1680. if Assigned(FNewtonBody) then
  1681. NewtonBodyAddImpulse(FNewtonBody, @veloc, @pointposit);
  1682. end;
  1683. constructor TGLNGDDynamic.Create(AOwner: TXCollection);
  1684. begin
  1685. inherited;
  1686. FAutoSleep := True;
  1687. FLinearDamping := 0.1;
  1688. FAngularDamping := TGLCoordinates.CreateInitialized(self, VectorMake(0.1, 0.1, 0.1, 0), csPoint);
  1689. FAngularDamping.OnNotifyChange := NotifyAngularDampingChange;
  1690. FDensity := 1;
  1691. FVolume := 1;
  1692. FForce := TGLCoordinates.CreateInitialized(self, NullHmgVector, csVector);
  1693. FTorque := TGLCoordinates.CreateInitialized(self, NullHmgVector, csVector);
  1694. FCenterOfMass := TGLCoordinates.CreateInitialized(self, NullHmgVector, csPoint);
  1695. FCenterOfMass.OnNotifyChange := NotifyCenterOfMassChange;
  1696. FAABBmin := TGLCoordinates.CreateInitialized(self, NullHmgVector, csPoint);
  1697. FAABBmax := TGLCoordinates.CreateInitialized(self, NullHmgVector, csPoint);
  1698. FAppliedOmega := TGLCoordinates.CreateInitialized(self, NullHmgVector, csVector);
  1699. FAppliedVelocity := TGLCoordinates.CreateInitialized(self, NullHmgVector, csVector);
  1700. FAppliedForce := TGLCoordinates.CreateInitialized(self, NullHmgVector, csVector);
  1701. FAppliedTorque := TGLCoordinates.CreateInitialized(self, NullHmgVector, csVector);
  1702. FUseGravity := True;
  1703. FNullCollisionVolume := 0;
  1704. FApplyForceAndTorqueEvent := OnApplyForceAndTorqueEvent;
  1705. FSetTransformEvent := OnSetTransformEvent;
  1706. name := 'NGD Dynamic'
  1707. end;
  1708. destructor TGLNGDDynamic.Destroy;
  1709. begin
  1710. // Clean up everything
  1711. FAngularDamping.Free;
  1712. FForce.Free;
  1713. FTorque.Free;
  1714. FCenterOfMass.Free;
  1715. FAABBmin.Free;
  1716. FAABBmax.Free;
  1717. FAppliedForce.Free;
  1718. FAppliedTorque.Free;
  1719. FAppliedVelocity.Free;
  1720. FAppliedOmega.Free;
  1721. inherited;
  1722. end;
  1723. procedure TGLNGDDynamic.Finalize;
  1724. begin
  1725. if not(csDesigning in FOwnerBaseSceneObject.ComponentState) then
  1726. if Assigned(FManager) then
  1727. begin
  1728. // Removing Callback
  1729. NewtonBodySetForceAndTorqueCallback(FNewtonBody, nil);
  1730. NewtonBodySetTransformCallback(FNewtonBody, nil);
  1731. end;
  1732. inherited;
  1733. end;
  1734. class function TGLNGDDynamic.FriendlyName: string;
  1735. begin
  1736. Result := 'NGD Dynamic';
  1737. end;
  1738. procedure TGLNGDDynamic.Initialize;
  1739. begin
  1740. inherited;
  1741. if not(csDesigning in FOwnerBaseSceneObject.ComponentState) then
  1742. if Assigned(FManager) then
  1743. begin
  1744. // Set Density, Mass and inertie matrix
  1745. SetDensity(FDensity);
  1746. // Set Callback
  1747. NewtonBodySetForceAndTorqueCallback(FNewtonBody, @TGLNGDDynamic.NewtonApplyForceAndTorque);
  1748. NewtonBodySetTransformCallback(FNewtonBody, @TGLNGDDynamic.NewtonSetTransform);
  1749. end;
  1750. end;
  1751. procedure TGLNGDDynamic.Render;
  1752. procedure DrawAABB(min, max: TGLCoordinates3);
  1753. begin
  1754. (*
  1755. // H________G
  1756. // /. /|
  1757. // / . / |
  1758. // D__._____C |
  1759. // | . | |
  1760. // | E.-----|--F
  1761. // | . | /
  1762. // |. |/
  1763. // A________B
  1764. *)
  1765. // Back
  1766. FManager.AddNode(min.X, min.Y, min.Z); // E
  1767. FManager.AddNode(max.X, min.Y, min.Z); // F
  1768. FManager.AddNode(max.X, min.Y, min.Z); // F
  1769. FManager.AddNode(max.X, max.Y, min.Z); // G
  1770. FManager.AddNode(max.X, max.Y, min.Z); // G
  1771. FManager.AddNode(min.X, max.Y, min.Z); // H
  1772. FManager.AddNode(min.X, max.Y, min.Z); // H
  1773. FManager.AddNode(min.X, min.Y, min.Z); // E
  1774. // Front
  1775. FManager.AddNode(min.X, min.Y, max.Z); // A
  1776. FManager.AddNode(max.X, min.Y, max.Z); // B
  1777. FManager.AddNode(max.X, min.Y, max.Z); // B
  1778. FManager.AddNode(max.X, max.Y, max.Z); // C
  1779. FManager.AddNode(max.X, max.Y, max.Z); // C
  1780. FManager.AddNode(min.X, max.Y, max.Z); // D
  1781. FManager.AddNode(min.X, max.Y, max.Z); // D
  1782. FManager.AddNode(min.X, min.Y, max.Z); // A
  1783. // Edges
  1784. FManager.AddNode(min.X, min.Y, max.Z); // A
  1785. FManager.AddNode(min.X, min.Y, min.Z); // E
  1786. FManager.AddNode(max.X, min.Y, max.Z); // B
  1787. FManager.AddNode(max.X, min.Y, min.Z); // F
  1788. FManager.AddNode(max.X, max.Y, max.Z); // C
  1789. FManager.AddNode(max.X, max.Y, min.Z); // G
  1790. FManager.AddNode(min.X, max.Y, max.Z); // D
  1791. FManager.AddNode(min.X, max.Y, min.Z); // H
  1792. end;
  1793. procedure DrawContact;
  1794. var
  1795. cnt: PNewtonJoint;
  1796. thisContact: PNewtonJoint;
  1797. material: PNewtonMaterial;
  1798. pos, nor: TGLVector;
  1799. begin
  1800. FManager.FCurrentColor := FManager.DebugOption.ContactColor;
  1801. cnt := NewtonBodyGetFirstContactJoint(FNewtonBody);
  1802. while cnt <> nil do
  1803. begin
  1804. thisContact := NewtonContactJointGetFirstContact(cnt);
  1805. while thisContact <> nil do
  1806. begin
  1807. material := NewtonContactGetMaterial(thisContact);
  1808. NewtonMaterialGetContactPositionAndNormal(material, FNewtonBody, @pos, @nor);
  1809. FManager.AddNode(pos);
  1810. nor := VectorAdd(pos, nor);
  1811. FManager.AddNode(nor);
  1812. thisContact := NewtonContactJointGetNextContact(cnt, thisContact);
  1813. end;
  1814. cnt := NewtonBodyGetNextContactJoint(FNewtonBody, cnt);
  1815. end;
  1816. end;
  1817. function GetAbsCom(): TGLVector;
  1818. var
  1819. M: TGLMatrix;
  1820. begin
  1821. NewtonBodyGetCentreOfMass(FNewtonBody, @Result);
  1822. M := IdentityHmgMatrix;
  1823. M.W := Result;
  1824. M.W.W := 1;
  1825. M := MatrixMultiply(M, FOwnerBaseSceneObject.AbsoluteMatrix);
  1826. Result := M.W;
  1827. end;
  1828. procedure DrawForce;
  1829. var
  1830. pos: TGLVector;
  1831. nor: TGLVector;
  1832. begin
  1833. pos := GetAbsCom;
  1834. if mdShowForce in FManager.DebugOption.NGDManagerDebugs then
  1835. begin
  1836. FManager.FCurrentColor := FManager.DebugOption.ForceColor;
  1837. nor := VectorAdd(pos, FForce.AsVector);
  1838. FManager.AddNode(pos);
  1839. FManager.AddNode(nor);
  1840. end;
  1841. if mdShowAppliedForce in FManager.DebugOption.NGDManagerDebugs then
  1842. begin
  1843. FManager.FCurrentColor := FManager.DebugOption.AppliedForceColor;
  1844. nor := VectorAdd(pos, FAppliedForce.AsVector);
  1845. FManager.AddNode(pos);
  1846. FManager.AddNode(nor);
  1847. end;
  1848. if mdShowAppliedVelocity in FManager.DebugOption.NGDManagerDebugs then
  1849. begin
  1850. FManager.FCurrentColor := FManager.DebugOption.AppliedVelocityColor;
  1851. nor := VectorAdd(pos, FAppliedVelocity.AsVector);
  1852. FManager.AddNode(pos);
  1853. FManager.AddNode(nor);
  1854. end;
  1855. end;
  1856. procedure DrawCoM;
  1857. var
  1858. com: TGLVector;
  1859. size: Single;
  1860. begin
  1861. FManager.FCurrentColor := FManager.DebugOption.CenterOfMassColor;
  1862. size := FManager.DebugOption.DotAxisSize;
  1863. com := GetAbsCom;
  1864. FManager.AddNode(VectorAdd(com, VectorMake(0, 0, size)));
  1865. FManager.AddNode(VectorAdd(com, VectorMake(0, 0, -size)));
  1866. FManager.AddNode(VectorAdd(com, VectorMake(0, size, 0)));
  1867. FManager.AddNode(VectorAdd(com, VectorMake(0, -size, 0)));
  1868. FManager.AddNode(VectorAdd(com, VectorMake(size, 0, 0)));
  1869. FManager.AddNode(VectorAdd(com, VectorMake(-size, 0, 0)));
  1870. end;
  1871. begin
  1872. inherited;
  1873. // Move/Rotate NewtonObject if matrix are not equal in design time.
  1874. if (csDesigning in FOwnerBaseSceneObject.ComponentState) then
  1875. if not MatrixEquals(NewtonBodyMatrix, FOwnerBaseSceneObject.AbsoluteMatrix) then
  1876. SetNewtonBodyMatrix(FOwnerBaseSceneObject.AbsoluteMatrix);
  1877. NewtonBodyGetAABB(FNewtonBody, @(FAABBmin.AsVector), @(FAABBmax.AsVector));
  1878. if NewtonBodyGetSleepState(FNewtonBody) = 1 then
  1879. FManager.FCurrentColor := FManager.DebugOption.AABBColorSleep
  1880. else
  1881. FManager.FCurrentColor := FManager.DebugOption.AABBColor;
  1882. if mdShowAABB in FManager.DebugOption.NGDManagerDebugs then
  1883. DrawAABB(FAABBmin, FAABBmax);
  1884. if mdShowContact in FManager.DebugOption.NGDManagerDebugs then
  1885. DrawContact;
  1886. DrawForce; // Draw Force, AppliedForce and AppliedVelocity
  1887. if mdShowCenterOfMass in FManager.DebugOption.NGDManagerDebugs then
  1888. DrawCoM;
  1889. end;
  1890. procedure TGLNGDDynamic.SetAutoSleep(const Value: Boolean);
  1891. begin
  1892. FAutoSleep := Value;
  1893. if not(csDesigning in FOwnerBaseSceneObject.ComponentState) then
  1894. if Assigned(FManager) then
  1895. NewtonBodySetAutoSleep(FNewtonBody, Ord(FAutoSleep));
  1896. end;
  1897. procedure TGLNGDDynamic.SetDensity(const Value: Single);
  1898. var
  1899. inertia: TGLVector;
  1900. origin: TGLVector;
  1901. begin
  1902. if Assigned(FManager) then
  1903. if Value >= 0 then
  1904. begin
  1905. FDensity := Value;
  1906. FVolume := NewtonConvexCollisionCalculateVolume(FCollision);
  1907. NewtonConvexCollisionCalculateInertialMatrix(FCollision, @inertia, @origin);
  1908. if IsZero(FVolume, epsilon) then
  1909. begin
  1910. FVolume := FNullCollisionVolume;
  1911. inertia := VectorMake(FNullCollisionVolume, FNullCollisionVolume, FNullCollisionVolume, 0);
  1912. end;
  1913. FMass := FVolume * FDensity;
  1914. if not(csDesigning in FOwnerBaseSceneObject.ComponentState) then
  1915. NewtonBodySetMassMatrix(FNewtonBody, FMass, FMass * inertia.X, FMass * inertia.Y,
  1916. FMass * inertia.Z);
  1917. FCenterOfMass.AsVector := origin;
  1918. end;
  1919. end;
  1920. procedure TGLNGDDynamic.SetLinearDamping(const Value: Single);
  1921. begin
  1922. if (Value >= 0) and (Value <= 1) then
  1923. FLinearDamping := Value;
  1924. if not(csDesigning in FOwnerBaseSceneObject.ComponentState) then
  1925. if Assigned(FManager) then
  1926. NewtonBodySetLinearDamping(FNewtonBody, FLinearDamping);
  1927. end;
  1928. function TGLNGDDynamic.GetOmega: TGLVector;
  1929. begin
  1930. NewtonBodyGetOmega(FNewtonBody, @Result);
  1931. end;
  1932. procedure TGLNGDDynamic.SetOmega(const Omega: TGLVector);
  1933. begin
  1934. NewtonBodySetOmega(FNewtonBody, @Omega);
  1935. end;
  1936. function TGLNGDDynamic.GetVelocity: TGLVector;
  1937. begin
  1938. NewtonBodyGetVelocity(FNewtonBody, @Result);
  1939. end;
  1940. procedure TGLNGDDynamic.SetVelocity(const Velocity: TGLVector);
  1941. begin
  1942. NewtonBodySetVelocity(FNewtonBody, @Velocity);
  1943. end;
  1944. function TGLNGDDynamic.StoredDensity: Boolean;
  1945. begin
  1946. Result := not SameValue(FDensity, 1, epsilon);
  1947. end;
  1948. function TGLNGDDynamic.StoredLinearDamping: Boolean;
  1949. begin
  1950. Result := not SameValue(FLinearDamping, 0.1, epsilon);
  1951. end;
  1952. function TGLNGDDynamic.StoredNullCollisionVolume: Boolean;
  1953. begin
  1954. Result := not SameValue(FNullCollisionVolume, 0, epsilon);
  1955. end;
  1956. procedure TGLNGDDynamic.WriteToFiler(writer: TWriter);
  1957. begin
  1958. inherited;
  1959. with writer do
  1960. begin
  1961. WriteInteger(1); // Archive version
  1962. WriteBoolean(FAutoSleep);
  1963. WriteFloat(FLinearDamping);
  1964. WriteFloat(FDensity);
  1965. WriteBoolean(FUseGravity);
  1966. WriteFloat(FNullCollisionVolume);
  1967. end;
  1968. FForce.WriteToFiler(writer);
  1969. FTorque.WriteToFiler(writer);
  1970. FCenterOfMass.WriteToFiler(writer);
  1971. FAngularDamping.WriteToFiler(writer);
  1972. end;
  1973. procedure TGLNGDDynamic.ReadFromFiler(reader: TReader);
  1974. var
  1975. version: Integer;
  1976. begin
  1977. inherited;
  1978. with reader do
  1979. begin
  1980. version := ReadInteger; // read data version
  1981. Assert(version <= 1); // Archive version
  1982. FAutoSleep := ReadBoolean;
  1983. if version <= 0 then
  1984. FLinearDamping := ReadSingle
  1985. else
  1986. FLinearDamping := ReadFloat;
  1987. if version <= 0 then
  1988. FDensity := ReadSingle
  1989. else
  1990. FDensity := ReadFloat;
  1991. // if Version >= 1 then
  1992. FUseGravity := ReadBoolean;
  1993. if version <= 0 then
  1994. FNullCollisionVolume := ReadSingle
  1995. else
  1996. FNullCollisionVolume := ReadFloat;
  1997. end;
  1998. FForce.ReadFromFiler(reader);
  1999. FTorque.ReadFromFiler(reader);
  2000. FCenterOfMass.ReadFromFiler(reader);
  2001. FAngularDamping.ReadFromFiler(reader);
  2002. end;
  2003. procedure TGLNGDDynamic.Loaded;
  2004. begin
  2005. inherited;
  2006. if Assigned(FManager) then
  2007. begin
  2008. SetAutoSleep(FAutoSleep);
  2009. SetLinearDamping(FLinearDamping);
  2010. SetDensity(FDensity);
  2011. NotifyCenterOfMassChange(self);
  2012. NotifyAngularDampingChange(self);
  2013. end;
  2014. end;
  2015. class procedure TGLNGDDynamic.NewtonApplyForceAndTorque(const body: PNewtonBody; timestep: dFloat;
  2016. threadIndex: Integer); cdecl;
  2017. begin
  2018. TGLNGDDynamic(NewtonBodyGetUserData(body)).FApplyForceAndTorqueEvent(body, timestep, threadIndex);
  2019. end;
  2020. class procedure TGLNGDDynamic.NewtonSetTransform(const body: PNewtonBody; const matrix: PdFloat;
  2021. threadIndex: Integer); cdecl;
  2022. begin
  2023. TGLNGDDynamic(NewtonBodyGetUserData(body)).FSetTransformEvent(body, matrix, threadIndex);
  2024. end;
  2025. procedure TGLNGDDynamic.NotifyAngularDampingChange(Sender: TObject);
  2026. begin
  2027. FAngularDamping.OnNotifyChange := nil;
  2028. if (FAngularDamping.X >= 0) and (FAngularDamping.X <= 1) and (FAngularDamping.Y >= 0) and
  2029. (FAngularDamping.Y <= 1) and (FAngularDamping.Z >= 0) and (FAngularDamping.Z <= 1) then
  2030. if Assigned(FManager) then
  2031. NewtonBodySetAngularDamping(FNewtonBody, @(FAngularDamping.AsVector));
  2032. FAngularDamping.OnNotifyChange := NotifyAngularDampingChange;
  2033. end;
  2034. procedure TGLNGDDynamic.NotifyCenterOfMassChange(Sender: TObject);
  2035. begin
  2036. FCenterOfMass.OnNotifyChange := nil;
  2037. if Assigned(FManager) then
  2038. NewtonBodySetCentreOfMass(FNewtonBody, @(FCenterOfMass.AsVector));
  2039. FCenterOfMass.OnNotifyChange := NotifyCenterOfMassChange;
  2040. end;
  2041. procedure TGLNGDDynamic.OnApplyForceAndTorqueEvent(const cbody: PNewtonBody; timestep: dFloat;
  2042. threadIndex: Integer);
  2043. var
  2044. worldGravity: TGLVector;
  2045. begin
  2046. // Read Only: We get the force and torque resulting from every interaction on this body
  2047. NewtonBodyGetForce(cbody, @(FAppliedForce.AsVector));
  2048. NewtonBodyGetTorque(cbody, @(FAppliedTorque.AsVector));
  2049. NewtonBodyGetVelocity(cbody, @(FAppliedVelocity.AsVector));
  2050. NewtonBodyGetOmega(cbody, @(FAppliedOmega.AsVector));
  2051. // Raise Custom event
  2052. if Assigned(FCustomForceAndTorqueEvent) then
  2053. FCustomForceAndTorqueEvent(cbody, timestep, threadIndex)
  2054. else
  2055. begin
  2056. NewtonBodySetForce(cbody, @(Force.AsVector));
  2057. NewtonBodySetTorque(cbody, @(Torque.AsVector));
  2058. // Add Gravity from World
  2059. if FUseGravity then
  2060. begin
  2061. worldGravity := VectorScale(FManager.Gravity.AsVector, FMass);
  2062. NewtonBodyAddForce(cbody, @(worldGravity));
  2063. end;
  2064. end;
  2065. end;
  2066. procedure TGLNGDDynamic.OnSetTransformEvent(const cbody: PNewtonBody; const cmatrix: PdFloat;
  2067. threadIndex: Integer);
  2068. var
  2069. epsi: Single;
  2070. begin
  2071. // The Newton API does not support scale [scale modifie value in matrix],
  2072. // so this line reset scale of the glsceneObject to (1,1,1)
  2073. // to avoid crashing the application
  2074. epsi := 0.0001;
  2075. with FOwnerBaseSceneObject do
  2076. if not SameValue(Scale.X, 1.0, epsi) or not SameValue(Scale.Y, 1.0, epsi) or
  2077. not SameValue(Scale.Z, 1.0, epsi) then
  2078. begin
  2079. Scale.SetVector(1, 1, 1);
  2080. SetNewtonBodyMatrix(AbsoluteMatrix);
  2081. end
  2082. else
  2083. // Make the Position and orientation of the glscene-Object relative to the
  2084. // NewtonBody position and orientation.
  2085. FOwnerBaseSceneObject.AbsoluteMatrix := PGLMatrix(cmatrix)^;
  2086. end;
  2087. // ------------------------
  2088. // TGLNGDStatic
  2089. // ------------------------
  2090. procedure TGLNGDStatic.Render;
  2091. begin
  2092. inherited;
  2093. // Move/Rotate NewtonObject if matrix are not equal in run time.
  2094. if not MatrixEquals(NewtonBodyMatrix, FOwnerBaseSceneObject.AbsoluteMatrix) then
  2095. SetNewtonBodyMatrix(FOwnerBaseSceneObject.AbsoluteMatrix);
  2096. end;
  2097. class function TGLNGDStatic.FriendlyName: string;
  2098. begin
  2099. Result := 'NGD Static';
  2100. end;
  2101. // ------------------------
  2102. // TGLNGDSurfaceItem
  2103. // ------------------------
  2104. function TGLNGDSurfaceItem.GetDisplayName: string;
  2105. begin
  2106. if FDisplayName = '' then
  2107. FDisplayName := 'Iron';
  2108. Result := FDisplayName;
  2109. end;
  2110. procedure TGLNGDSurfaceItem.SetDisplayName(const Value: string);
  2111. begin
  2112. inherited;
  2113. FDisplayName := Value;
  2114. end;
  2115. // ------------------------
  2116. // TGLNGDSurfacePair
  2117. // ------------------------
  2118. constructor TGLNGDSurfacePair.Create(Collection: TCollection);
  2119. begin
  2120. inherited;
  2121. FSoftness := 0.1;
  2122. FElasticity := 0.4;
  2123. FCollidable := True;
  2124. FStaticFriction := 0.9;
  2125. FKineticFriction := 0.5;
  2126. FContinuousCollisionMode := False;
  2127. FThickness := False;
  2128. FAABBOverlapEvent := OnNewtonAABBOverlapEvent;
  2129. FContactProcessEvent := OnNewtonContactsProcessEvent;
  2130. FManager := TGLNGDManager(Collection.Owner);
  2131. FManager.RebuildAllMaterial;
  2132. end;
  2133. class function TGLNGDSurfacePair.NewtonAABBOverlap(const material: PNewtonMaterial;
  2134. const body0, body1: PNewtonBody; threadIndex: Integer): Integer; cdecl;
  2135. begin
  2136. Result := Ord(TGLNGDSurfacePair(NewtonMaterialGetMaterialPairUserData(material))
  2137. .FAABBOverlapEvent(material, body0, body1, threadIndex));
  2138. end;
  2139. class procedure TGLNGDSurfacePair.NewtonContactsProcess(const contact: PNewtonJoint;
  2140. timestep: dFloat; threadIndex: Integer); cdecl;
  2141. begin
  2142. TGLNGDSurfacePair(NewtonMaterialGetMaterialPairUserData
  2143. (NewtonContactGetMaterial(NewtonContactJointGetFirstContact(contact))))
  2144. .FContactProcessEvent(contact, timestep, threadIndex);
  2145. end;
  2146. function TGLNGDSurfacePair.OnNewtonAABBOverlapEvent(const cmaterial: PNewtonMaterial;
  2147. const cbody0, cbody1: PNewtonBody; threadIndex: Integer): Boolean;
  2148. begin
  2149. Result := True;
  2150. end;
  2151. procedure TGLNGDSurfacePair.OnNewtonContactsProcessEvent(const ccontact: PNewtonJoint;
  2152. timestep: dFloat; threadIndex: Integer);
  2153. begin
  2154. //
  2155. end;
  2156. procedure TGLNGDSurfacePair.SetCollidable(const Value: Boolean);
  2157. begin
  2158. FCollidable := Value;
  2159. FManager.RebuildAllMaterial;
  2160. end;
  2161. procedure TGLNGDSurfacePair.SetContinuousCollisionMode(const Value: Boolean);
  2162. begin
  2163. FContinuousCollisionMode := Value;
  2164. FManager.RebuildAllMaterial;
  2165. end;
  2166. procedure TGLNGDSurfacePair.SetElasticity(const Value: Single);
  2167. begin
  2168. if (Value >= 0) then
  2169. FElasticity := Value;
  2170. FManager.RebuildAllMaterial;
  2171. end;
  2172. procedure TGLNGDSurfacePair.SetKineticFriction(const Value: Single);
  2173. begin
  2174. if (Value >= 0) and (Value <= 1) then
  2175. FKineticFriction := Value;
  2176. FManager.RebuildAllMaterial;
  2177. end;
  2178. procedure TGLNGDSurfacePair.SetMaterialItems(const item1, item2: TGLNGDSurfaceItem);
  2179. begin
  2180. FSurfaceItem1 := item1;
  2181. FSurfaceItem2 := item2;
  2182. FManager.RebuildAllMaterial;
  2183. end;
  2184. procedure TGLNGDSurfacePair.SetSoftness(const Value: Single);
  2185. begin
  2186. if (Value >= 0) and (Value <= 1) then
  2187. FSoftness := Value;
  2188. FManager.RebuildAllMaterial;
  2189. end;
  2190. procedure TGLNGDSurfacePair.SetStaticFriction(const Value: Single);
  2191. begin
  2192. if (Value >= 0) and (Value <= 1) then
  2193. FStaticFriction := Value;
  2194. FManager.RebuildAllMaterial;
  2195. end;
  2196. procedure TGLNGDSurfacePair.SetThickness(const Value: Boolean);
  2197. begin
  2198. FThickness := Value;
  2199. FManager.RebuildAllMaterial;
  2200. end;
  2201. function TGLNGDSurfacePair.StoredElasticity: Boolean;
  2202. begin
  2203. Result := not SameValue(FElasticity, 0.4, epsilon);
  2204. end;
  2205. function TGLNGDSurfacePair.StoredKineticFriction: Boolean;
  2206. begin
  2207. Result := not SameValue(FKineticFriction, 0.5, epsilon);
  2208. end;
  2209. function TGLNGDSurfacePair.StoredSoftness: Boolean;
  2210. begin
  2211. Result := not SameValue(FSoftness, 0.1, epsilon);
  2212. end;
  2213. function TGLNGDSurfacePair.StoredStaticFriction: Boolean;
  2214. begin
  2215. Result := not SameValue(FStaticFriction, 0.9, epsilon);
  2216. end;
  2217. // ------------------------
  2218. // TGLNGDJoint
  2219. // ------------------------
  2220. constructor TGLNGDJoint.Create(Collection: TCollection);
  2221. begin
  2222. inherited;
  2223. FCollisionState := False;
  2224. FStiffness := 0.9;
  2225. FNewtonJoint := nil;
  2226. FNewtonUserJoint := nil;
  2227. FParentObject := nil;
  2228. FChildObject := nil;
  2229. FManager := TGLNGDManager(Collection.Owner);
  2230. FBallAndSocketOptions := TGLNGDJointPivot.Create(FManager, self);
  2231. FHingeOptions := TGLNGDJointPin.Create(FManager, self);
  2232. FSliderOptions := TGLNGDJointPin.Create(FManager, self);
  2233. FCorkscrewOptions := TGLNGDJointPin.Create(FManager, self);
  2234. FUniversalOptions := TGLNGDJointPin2.Create(FManager, self);
  2235. FCustomBallAndSocketOptions := TGLNGDJointBallAndSocket.Create(FManager, self);
  2236. FCustomHingeOptions := TGLNGDJointHinge.Create(FManager, self);
  2237. FCustomSliderOptions := TGLNGDJointSlider.Create(FManager, self);
  2238. FKinematicOptions := TGLNGDJointKinematicController.Create;
  2239. FUPVectorDirection := TGLCoordinates.CreateInitialized(self, YHmgVector, csVector);
  2240. FUPVectorDirection.OnNotifyChange := FManager.RebuildAllJoint;
  2241. end;
  2242. destructor TGLNGDJoint.Destroy;
  2243. begin
  2244. DestroyNewtonData;
  2245. FParentObject := nil;
  2246. FChildObject := nil;
  2247. // Free options
  2248. FBallAndSocketOptions.Free;
  2249. FHingeOptions.Free;
  2250. FSliderOptions.Free;
  2251. FCorkscrewOptions.Free;
  2252. FUniversalOptions.Free;
  2253. FCustomBallAndSocketOptions.Free;
  2254. FCustomHingeOptions.Free;
  2255. FCustomSliderOptions.Free;
  2256. FKinematicOptions.Free;
  2257. FUPVectorDirection.Free;
  2258. inherited;
  2259. end;
  2260. procedure TGLNGDJoint.DestroyNewtonData;
  2261. begin
  2262. if FNewtonJoint <> nil then
  2263. begin
  2264. Assert((FManager <> nil) and (FManager.FNewtonWorld <> nil));
  2265. NewtonDestroyJoint(FManager.FNewtonWorld, FNewtonJoint);
  2266. FNewtonJoint := nil;
  2267. end;
  2268. if FNewtonUserJoint <> nil then
  2269. begin
  2270. (* CustomDestroyJoint(FNewtonUserJoint); *) // from dJointLibrary.dll
  2271. FNewtonUserJoint := nil;
  2272. end;
  2273. end;
  2274. procedure TGLNGDJoint.KinematicControllerPick(pickpoint: TGLVector;
  2275. PickedActions: TGLNGDPickedActions);
  2276. begin
  2277. (* CustomDestroyJoint(FNewtonUserJoint); //from dJointLibrary.dll
  2278. if FJointType = nj_KinematicController then
  2279. if Assigned(FParentObject) then
  2280. begin
  2281. // Creates the joint
  2282. if PickedActions = paAttach then
  2283. begin
  2284. if not Assigned(FNewtonUserJoint) then
  2285. if Assigned(GetNGDDynamic(FParentObject).FNewtonBody) then
  2286. FNewtonUserJoint := CreateCustomKinematicController
  2287. (GetNGDDynamic(FParentObject).FNewtonBody, @pickpoint);
  2288. end;
  2289. // Change the TargetPoint
  2290. if (PickedActions = paMove) or (PickedActions = paAttach) then
  2291. begin
  2292. if Assigned(FNewtonUserJoint) then
  2293. begin
  2294. CustomKinematicControllerSetPickMode(FNewtonUserJoint,
  2295. Ord(FKinematicOptions.FPickModeLinear));
  2296. CustomKinematicControllerSetMaxLinearFriction(FNewtonUserJoint,
  2297. FKinematicOptions.FLinearFriction);
  2298. CustomKinematicControllerSetMaxAngularFriction(FNewtonUserJoint,
  2299. FKinematicOptions.FAngularFriction);
  2300. CustomKinematicControllerSetTargetPosit(FNewtonUserJoint, @pickpoint);
  2301. end;
  2302. end;
  2303. // Delete the joint
  2304. if PickedActions = paDetach then
  2305. begin
  2306. if Assigned(FNewtonUserJoint) then
  2307. begin
  2308. CustomDestroyJoint(FNewtonUserJoint);
  2309. FNewtonUserJoint := nil;
  2310. // Reset autosleep because this joint turns it off
  2311. NewtonBodySetAutoSleep(GetNGDDynamic(FParentObject).FNewtonBody,
  2312. Ord(GetNGDDynamic(FParentObject).AutoSleep));
  2313. end;
  2314. ParentObject := nil;
  2315. end;
  2316. end;
  2317. *)
  2318. end;
  2319. procedure TGLNGDJoint.Render;
  2320. procedure DrawPivot(pivot: TGLVector);
  2321. var
  2322. size: Single;
  2323. begin
  2324. size := FManager.DebugOption.DotAxisSize;
  2325. FManager.FCurrentColor := FManager.DebugOption.JointPivotColor;
  2326. FManager.AddNode(VectorAdd(pivot, VectorMake(0, 0, size)));
  2327. FManager.AddNode(VectorAdd(pivot, VectorMake(0, 0, -size)));
  2328. FManager.AddNode(VectorAdd(pivot, VectorMake(0, size, 0)));
  2329. FManager.AddNode(VectorAdd(pivot, VectorMake(0, -size, 0)));
  2330. FManager.AddNode(VectorAdd(pivot, VectorMake(size, 0, 0)));
  2331. FManager.AddNode(VectorAdd(pivot, VectorMake(-size, 0, 0)));
  2332. end;
  2333. procedure DrawPin(pin, pivot: TGLVector);
  2334. begin
  2335. FManager.FCurrentColor := FManager.DebugOption.JointAxisColor;
  2336. FManager.AddNode(VectorAdd(pivot, pin));
  2337. FManager.AddNode(VectorAdd(pivot, VectorNegate(pin)));
  2338. end;
  2339. procedure DrawJoint(pivot: TGLVector);
  2340. begin
  2341. FManager.FCurrentColor := FManager.DebugOption.CustomColor;
  2342. FManager.AddNode(FParentObject.AbsolutePosition);
  2343. FManager.AddNode(pivot);
  2344. FManager.AddNode(pivot);
  2345. FManager.AddNode(FChildObject.AbsolutePosition);
  2346. end;
  2347. procedure DrawKinematic;
  2348. var
  2349. pickedMatrix: TGLMatrix;
  2350. size: Single;
  2351. begin
  2352. size := FManager.DebugOption.DotAxisSize;
  2353. /// From dJointLibrary.dll
  2354. /// CustomKinematicControllerGetTargetMatrix(FNewtonUserJoint, @pickedMatrix);
  2355. FManager.FCurrentColor := FManager.DebugOption.JointAxisColor;
  2356. FManager.AddNode(FParentObject.AbsolutePosition);
  2357. FManager.AddNode(pickedMatrix.W);
  2358. FManager.FCurrentColor := FManager.DebugOption.JointPivotColor;
  2359. FManager.AddNode(VectorAdd(pickedMatrix.W, VectorMake(0, 0, size)));
  2360. FManager.AddNode(VectorAdd(pickedMatrix.W, VectorMake(0, 0, -size)));
  2361. FManager.AddNode(VectorAdd(pickedMatrix.W, VectorMake(0, size, 0)));
  2362. FManager.AddNode(VectorAdd(pickedMatrix.W, VectorMake(0, -size, 0)));
  2363. FManager.AddNode(VectorAdd(pickedMatrix.W, VectorMake(size, 0, 0)));
  2364. FManager.AddNode(VectorAdd(pickedMatrix.W, VectorMake(-size, 0, 0)));
  2365. end;
  2366. begin
  2367. case FJointType of
  2368. nj_BallAndSocket:
  2369. if Assigned(FParentObject) and Assigned(FChildObject) then
  2370. begin
  2371. DrawJoint(FBallAndSocketOptions.FPivotPoint.AsVector);
  2372. DrawPivot(FBallAndSocketOptions.FPivotPoint.AsVector);
  2373. end;
  2374. nj_Hinge:
  2375. if Assigned(FParentObject) and Assigned(FChildObject) then
  2376. begin
  2377. DrawJoint(FHingeOptions.FPivotPoint.AsVector);
  2378. DrawPin(FHingeOptions.FPinDirection.AsVector, FHingeOptions.FPivotPoint.AsVector);
  2379. DrawPivot(FHingeOptions.FPivotPoint.AsVector);
  2380. end;
  2381. nj_Slider:
  2382. if Assigned(FParentObject) and Assigned(FChildObject) then
  2383. begin
  2384. DrawJoint(FSliderOptions.FPivotPoint.AsVector);
  2385. DrawPin(FSliderOptions.FPinDirection.AsVector, FSliderOptions.FPivotPoint.AsVector);
  2386. DrawPivot(FSliderOptions.FPivotPoint.AsVector);
  2387. end;
  2388. nj_Corkscrew:
  2389. if Assigned(FParentObject) and Assigned(FChildObject) then
  2390. begin
  2391. DrawJoint(FCorkscrewOptions.FPivotPoint.AsVector);
  2392. DrawPin(FCorkscrewOptions.FPinDirection.AsVector, FCorkscrewOptions.FPivotPoint.AsVector);
  2393. DrawPivot(FCorkscrewOptions.FPivotPoint.AsVector);
  2394. end;
  2395. nj_Universal:
  2396. if Assigned(FParentObject) and Assigned(FChildObject) then
  2397. begin
  2398. DrawJoint(FUniversalOptions.FPivotPoint.AsVector);
  2399. DrawPin(FUniversalOptions.FPinDirection.AsVector, FUniversalOptions.FPivotPoint.AsVector);
  2400. DrawPin(FUniversalOptions.FPinDirection2.AsVector, FUniversalOptions.FPivotPoint.AsVector);
  2401. DrawPivot(FUniversalOptions.FPivotPoint.AsVector);
  2402. end;
  2403. nj_CustomBallAndSocket:
  2404. if Assigned(FParentObject) and Assigned(FChildObject) then
  2405. begin
  2406. DrawJoint(FCustomBallAndSocketOptions.FPivotPoint.AsVector);
  2407. DrawPivot(FCustomBallAndSocketOptions.FPivotPoint.AsVector);
  2408. end;
  2409. nj_CustomHinge:
  2410. if Assigned(FParentObject) and Assigned(FChildObject) then
  2411. begin
  2412. DrawJoint(FCustomHingeOptions.FPivotPoint.AsVector);
  2413. DrawPin(FCustomHingeOptions.FPinDirection.AsVector,
  2414. FCustomHingeOptions.FPivotPoint.AsVector);
  2415. DrawPivot(FCustomHingeOptions.FPivotPoint.AsVector);
  2416. end;
  2417. nj_CustomSlider:
  2418. if Assigned(FParentObject) and Assigned(FChildObject) then
  2419. begin
  2420. DrawJoint(FCustomSliderOptions.FPivotPoint.AsVector);
  2421. DrawPin(FCustomSliderOptions.FPinDirection.AsVector,
  2422. FCustomSliderOptions.FPivotPoint.AsVector);
  2423. DrawPivot(FCustomSliderOptions.FPivotPoint.AsVector);
  2424. end;
  2425. nj_UpVector:
  2426. if Assigned(FParentObject) then
  2427. begin // special
  2428. FManager.FCurrentColor := FManager.DebugOption.JointAxisColor;
  2429. FManager.AddNode(FParentObject.AbsolutePosition);
  2430. FManager.AddNode(VectorAdd(FParentObject.AbsolutePosition, FUPVectorDirection.AsVector));
  2431. end;
  2432. nj_KinematicController:
  2433. if Assigned(FParentObject) and Assigned(FNewtonUserJoint) then
  2434. begin // special
  2435. DrawKinematic;
  2436. end;
  2437. end;
  2438. end;
  2439. procedure TGLNGDJoint.SetChildObject(const Value: TGLBaseSceneObject);
  2440. begin
  2441. FChildObject := Value;
  2442. FManager.RebuildAllJoint(self);
  2443. end;
  2444. procedure TGLNGDJoint.SetCollisionState(const Value: Boolean);
  2445. begin
  2446. FCollisionState := Value;
  2447. FManager.RebuildAllJoint(self);
  2448. end;
  2449. procedure TGLNGDJoint.SetJointType(const Value: TGLNGDJoints);
  2450. begin
  2451. FJointType := Value;
  2452. FManager.RebuildAllJoint(self);
  2453. end;
  2454. procedure TGLNGDJoint.SetParentObject(const Value: TGLBaseSceneObject);
  2455. begin
  2456. FParentObject := Value;
  2457. FManager.RebuildAllJoint(self);
  2458. end;
  2459. procedure TGLNGDJoint.SetStiffness(const Value: Single);
  2460. begin
  2461. if (Value >= 0) and (Value <= 1) then
  2462. begin
  2463. FStiffness := Value;
  2464. FManager.RebuildAllJoint(self);
  2465. end;
  2466. end;
  2467. function TGLNGDJoint.StoredStiffness: Boolean;
  2468. begin
  2469. Result := not SameValue(FStiffness, 0.9, epsilon);
  2470. end;
  2471. // ------------------------
  2472. // TGLNGDJointPivot
  2473. // ------------------------
  2474. constructor TGLNGDJointPivot.Create(AOwner: TComponent; aOuter: TGLNGDJoint);
  2475. begin
  2476. FManager := AOwner as TGLNGDManager;
  2477. FOuter := aOuter;
  2478. FPivotPoint := TGLCoordinates.CreateInitialized(aOuter, NullHMGPoint, csPoint);
  2479. FPivotPoint.OnNotifyChange := FManager.RebuildAllJoint;
  2480. end;
  2481. destructor TGLNGDJointPivot.Destroy;
  2482. begin
  2483. FPivotPoint.Free;
  2484. inherited;
  2485. end;
  2486. // ------------------------
  2487. // TGLNGDJointPin
  2488. // ------------------------
  2489. constructor TGLNGDJointPin.Create(AOwner: TComponent; aOuter: TGLNGDJoint);
  2490. begin
  2491. inherited;
  2492. FPinDirection := TGLCoordinates.CreateInitialized(aOuter, NullHmgVector, csVector);
  2493. FPinDirection.OnNotifyChange := FManager.RebuildAllJoint;
  2494. end;
  2495. destructor TGLNGDJointPin.Destroy;
  2496. begin
  2497. FPinDirection.Free;
  2498. inherited;
  2499. end;
  2500. // ------------------------
  2501. // TGLNGDJointPin2
  2502. // ------------------------
  2503. constructor TGLNGDJointPin2.Create(AOwner: TComponent; aOuter: TGLNGDJoint);
  2504. begin
  2505. inherited;
  2506. FPinDirection2 := TGLCoordinates.CreateInitialized(aOuter, NullHmgVector, csVector);
  2507. FPinDirection2.OnNotifyChange := FManager.RebuildAllJoint;
  2508. end;
  2509. destructor TGLNGDJointPin2.Destroy;
  2510. begin
  2511. FPinDirection2.Free;
  2512. inherited;
  2513. end;
  2514. // ------------------------
  2515. // TGLNGDJointBallAndSocket
  2516. // ------------------------
  2517. constructor TGLNGDJointBallAndSocket.Create(AOwner: TComponent; aOuter: TGLNGDJoint);
  2518. begin
  2519. inherited;
  2520. FConeAngle := 90;
  2521. FMinTwistAngle := -90;
  2522. FMaxTwistAngle := 90;
  2523. end;
  2524. procedure TGLNGDJointBallAndSocket.SetConeAngle(const Value: Single);
  2525. begin
  2526. FConeAngle := Value;
  2527. FManager.RebuildAllJoint(FOuter);
  2528. end;
  2529. procedure TGLNGDJointBallAndSocket.SetMaxTwistAngle(const Value: Single);
  2530. begin
  2531. FMaxTwistAngle := Value;
  2532. FManager.RebuildAllJoint(FOuter);
  2533. end;
  2534. procedure TGLNGDJointBallAndSocket.SetMinTwistAngle(const Value: Single);
  2535. begin
  2536. FMinTwistAngle := Value;
  2537. FManager.RebuildAllJoint(FOuter);
  2538. end;
  2539. function TGLNGDJointBallAndSocket.StoredConeAngle: Boolean;
  2540. begin
  2541. Result := not SameValue(FConeAngle, 90, epsilon);
  2542. end;
  2543. function TGLNGDJointBallAndSocket.StoredMaxTwistAngle: Boolean;
  2544. begin
  2545. Result := not SameValue(FMaxTwistAngle, 90, epsilon);
  2546. end;
  2547. function TGLNGDJointBallAndSocket.StoredMinTwistAngle: Boolean;
  2548. begin
  2549. Result := not SameValue(FMinTwistAngle, -90, epsilon);
  2550. end;
  2551. // ------------------------
  2552. // TGLNGDJointHinge
  2553. // ------------------------
  2554. constructor TGLNGDJointHinge.Create(AOwner: TComponent; aOuter: TGLNGDJoint);
  2555. begin
  2556. inherited;
  2557. FMinAngle := -90;
  2558. FMaxAngle := 90;
  2559. end;
  2560. procedure TGLNGDJointHinge.SetMaxAngle(const Value: Single);
  2561. begin
  2562. FMaxAngle := Value;
  2563. FManager.RebuildAllJoint(FOuter);
  2564. end;
  2565. procedure TGLNGDJointHinge.SetMinAngle(const Value: Single);
  2566. begin
  2567. FMinAngle := Value;
  2568. FManager.RebuildAllJoint(FOuter);
  2569. end;
  2570. function TGLNGDJointHinge.StoredMaxAngle: Boolean;
  2571. begin
  2572. Result := not SameValue(FMaxAngle, 90, epsilon);
  2573. end;
  2574. function TGLNGDJointHinge.StoredMinAngle: Boolean;
  2575. begin
  2576. Result := not SameValue(FMinAngle, -90, epsilon);
  2577. end;
  2578. // ------------------------
  2579. // TGLNGDJointSlider
  2580. // ------------------------
  2581. constructor TGLNGDJointSlider.Create(AOwner: TComponent; aOuter: TGLNGDJoint);
  2582. begin
  2583. inherited;
  2584. FMinDistance := -10;
  2585. FMaxDistance := 10;
  2586. end;
  2587. procedure TGLNGDJointSlider.SetMaxDistance(const Value: Single);
  2588. begin
  2589. FMaxDistance := Value;
  2590. FManager.RebuildAllJoint(FOuter);
  2591. end;
  2592. procedure TGLNGDJointSlider.SetMinDistance(const Value: Single);
  2593. begin
  2594. FMinDistance := Value;
  2595. FManager.RebuildAllJoint(FOuter);
  2596. end;
  2597. function TGLNGDJointSlider.StoredMaxDistance: Boolean;
  2598. begin
  2599. Result := not SameValue(FMaxDistance, 10, epsilon);
  2600. end;
  2601. function TGLNGDJointSlider.StoredMinDistance: Boolean;
  2602. begin
  2603. Result := not SameValue(FMinDistance, -10, epsilon);
  2604. end;
  2605. // ----------------------------------
  2606. // TGLNGDJointKinematicController
  2607. // ----------------------------------
  2608. constructor TGLNGDJointKinematicController.Create;
  2609. begin
  2610. FPickModeLinear := False;
  2611. FLinearFriction := 750;
  2612. FAngularFriction := 250;
  2613. end;
  2614. function TGLNGDJointKinematicController.StoredAngularFriction: Boolean;
  2615. begin
  2616. Result := not SameValue(FAngularFriction, 250, epsilon);
  2617. end;
  2618. function TGLNGDJointKinematicController.StoredLinearFriction: Boolean;
  2619. begin
  2620. Result := not SameValue(FLinearFriction, 750, epsilon);
  2621. end;
  2622. // ------------------------
  2623. // TGLNGDBehaviourList
  2624. // ------------------------
  2625. function TGLNGDBehaviourList.GetBehav(index: Integer): TGLNGDBehaviour;
  2626. begin
  2627. Result := Items[index];
  2628. end;
  2629. procedure TGLNGDBehaviourList.PutBehav(index: Integer; Item: TGLNGDBehaviour);
  2630. begin
  2631. inherited put(index, Item);
  2632. end;
  2633. // ------------------------------------------------------------------
  2634. initialization
  2635. // ------------------------------------------------------------------
  2636. RegisterXCollectionItemClass(TGLNGDDynamic);
  2637. RegisterXCollectionItemClass(TGLNGDStatic);
  2638. // ------------------------------------------------------------------
  2639. finalization
  2640. // ------------------------------------------------------------------
  2641. UnregisterXCollectionItemClass(TGLNGDDynamic);
  2642. UnregisterXCollectionItemClass(TGLNGDStatic);
  2643. // CloseNGD;
  2644. end.