Team Fortress 2 Source Code as on 22/4/2020
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

10448 lines
246 KiB

  1. //========= Copyright Valve Corporation, All rights reserved. ============//
  2. //
  3. // Purpose:
  4. //
  5. // $NoKeywords: $
  6. //
  7. //===========================================================================//
  8. //
  9. // studiomdl.c: generates a studio .mdl file from a .qc script
  10. // models/<scriptname>.mdl.
  11. //
  12. #pragma warning( disable : 4244 )
  13. #pragma warning( disable : 4237 )
  14. #pragma warning( disable : 4305 )
  15. #include <windows.h>
  16. #undef GetCurrentDirectory
  17. #include <Shlwapi.h> // PathCanonicalize
  18. #pragma comment( lib, "shlwapi" )
  19. #include <stdio.h>
  20. #include <stdlib.h>
  21. #include <sys/stat.h>
  22. #include <math.h>
  23. #include <direct.h>
  24. #include "istudiorender.h"
  25. #include "filesystem_tools.h"
  26. #include "tier2/fileutils.h"
  27. #include "cmdlib.h"
  28. #include "scriplib.h"
  29. #include "mathlib/mathlib.h"
  30. #define EXTERN
  31. #include "studio.h"
  32. #include "studiomdl.h"
  33. #include "collisionmodel.h"
  34. #include "optimize.h"
  35. #include "byteswap.h"
  36. #include "studiobyteswap.h"
  37. #include "tier1/strtools.h"
  38. #include "bspflags.h"
  39. #include "tier0/icommandline.h"
  40. #include "utldict.h"
  41. #include "tier1/utlsortvector.h"
  42. #include "bitvec.h"
  43. #include "appframework/appframework.h"
  44. #include "datamodel/idatamodel.h"
  45. #include "materialsystem/materialsystem_config.h"
  46. #include "vstdlib/cvar.h"
  47. #include "tier1/tier1.h"
  48. #include "tier2/tier2.h"
  49. #include "tier3/tier3.h"
  50. #include "datamodel/dmelementfactoryhelper.h"
  51. #include "mdlobjects/dmeboneflexdriver.h"
  52. #include "movieobjects/dmeanimationset.h"
  53. #include "movieobjects/dmemdlmakefile.h"
  54. #include "movieobjects/dmevertexdata.h"
  55. #include "movieobjects/dmecombinationoperator.h"
  56. #include "dmserializers/idmserializers.h"
  57. #include "tier2/p4helpers.h"
  58. #include "p4lib/ip4.h"
  59. #include "mdllib/mdllib.h"
  60. #include "perfstats.h"
  61. #include "worldsize.h"
  62. bool g_collapse_bones = false;
  63. bool g_collapse_bones_aggressive = false;
  64. bool g_quiet = false;
  65. bool g_badCollide = false;
  66. bool g_IHVTest = false;
  67. bool g_bCheckLengths = false;
  68. bool g_bPrintBones = false;
  69. bool g_bPerf = false;
  70. bool g_bDumpGraph = false;
  71. bool g_bMultistageGraph = false;
  72. bool g_verbose = false;
  73. bool g_bCreateMakefile = false;
  74. bool g_bHasModelName = false;
  75. bool g_bZBrush = false;
  76. bool g_bVerifyOnly = false;
  77. bool g_bUseBoneInBBox = true;
  78. bool g_bLockBoneLengths = false;
  79. bool g_bOverridePreDefinedBones = false;
  80. int g_minLod = 0;
  81. int g_numAllowedRootLODs = 0;
  82. bool g_bNoWarnings = false;
  83. int g_maxWarnings = -1;
  84. bool g_bX360 = false;
  85. bool g_bBuildPreview = false;
  86. bool g_bCenterBonesOnVerts = false;
  87. bool g_bDumpMaterials = false;
  88. bool g_bStripLods = false;
  89. bool g_bMakeVsi = false;
  90. float g_flDefaultMotionRollback = 0.3f;
  91. int g_minSectionFrameLimit = 120;
  92. int g_sectionFrames = 30;
  93. bool g_bNoAnimblockStall = false;
  94. char g_path[MAX_PATH];
  95. Vector g_vecMinWorldspace = Vector( MIN_COORD_INTEGER, MIN_COORD_INTEGER, MIN_COORD_INTEGER );
  96. Vector g_vecMaxWorldspace = Vector( MAX_COORD_INTEGER, MAX_COORD_INTEGER, MAX_COORD_INTEGER );
  97. DmElementHandle_t g_hDmeBoneFlexDriverList = DMELEMENT_HANDLE_INVALID;
  98. enum RunMode
  99. {
  100. RUN_MODE_BUILD,
  101. RUN_MODE_STRIP_MODEL,
  102. RUN_MODE_STRIP_VHV
  103. } g_eRunMode = RUN_MODE_BUILD;
  104. bool g_bNoP4 = false;
  105. CUtlVector< s_hitboxset > g_hitboxsets;
  106. CUtlVector< char > g_KeyValueText;
  107. CUtlVector<s_flexcontrollerremap_t> g_FlexControllerRemap;
  108. CCheckUVCmd g_StudioMdlCheckUVCmd;
  109. //-----------------------------------------------------------------------------
  110. // Parsed data from a .qc or .dmx file
  111. //-----------------------------------------------------------------------------
  112. struct IKLock_t
  113. {
  114. CUtlString m_Name;
  115. float m_flPosWeight;
  116. float m_flLocalQWeight;
  117. };
  118. struct SequenceOption_t
  119. {
  120. bool m_bSnap : 1;
  121. bool m_bIsDelta : 1;
  122. bool m_bIsWorldSpace : 1;
  123. bool m_bIsPost : 1;
  124. bool m_bIsPreDelta : 1;
  125. bool m_bIsAutoplay : 1;
  126. bool m_bIsRealTime : 1;
  127. bool m_bIsHidden : 1;
  128. float m_flFadeInTime;
  129. float m_flFadeOutTime;
  130. int m_nBlendWidth;
  131. CUtlVector< CUtlString > m_AutoLayers;
  132. CUtlVector< IKLock_t > m_IKLocks;
  133. };
  134. struct CmdSequence_t
  135. {
  136. CUtlString m_Name;
  137. CUtlString m_FileName;
  138. SequenceOption_t m_Options;
  139. };
  140. //-----------------------------------------------------------------------------
  141. // Forward declarations
  142. //-----------------------------------------------------------------------------
  143. void AddBodyFlexData( s_source_t *pSource, int imodel );
  144. void AddBodyAttachments( s_source_t *pSource );
  145. void AddBodyFlexRules( s_source_t *pSource );
  146. //-----------------------------------------------------------------------------
  147. // Stuff for writing a makefile to build models incrementally.
  148. //-----------------------------------------------------------------------------
  149. CUtlVector<CUtlSymbol> m_CreateMakefileDependencies;
  150. void CreateMakefile_AddDependency( const char *pFileName )
  151. {
  152. EnsureDependencyFileCheckedIn( pFileName );
  153. if( !g_bCreateMakefile )
  154. {
  155. return;
  156. }
  157. CUtlSymbol sym( pFileName );
  158. int i;
  159. for( i = 0; i < m_CreateMakefileDependencies.Count(); i++ )
  160. {
  161. if( m_CreateMakefileDependencies[i] == sym )
  162. {
  163. return;
  164. }
  165. }
  166. m_CreateMakefileDependencies.AddToTail( sym );
  167. }
  168. void EnsureDependencyFileCheckedIn( const char *pFileName )
  169. {
  170. // Early out: if no p4
  171. if ( g_bNoP4 )
  172. return;
  173. char pFullPath[MAX_PATH];
  174. if ( !GetGlobalFilePath( pFileName, pFullPath, sizeof(pFullPath) ) )
  175. {
  176. MdlWarning( "Model dependency file '%s' is missing.\n", pFileName );
  177. return;
  178. }
  179. Q_FixSlashes( pFullPath );
  180. char bufCanonicalPath[ MAX_PATH ] = {0};
  181. PathCanonicalize( bufCanonicalPath, pFullPath );
  182. CP4AutoAddFile p4_add_dep_file( bufCanonicalPath );
  183. }
  184. void StudioMdl_ScriptLoadedCallback( char const *pFilenameLoaded, char const *pIncludedFromFileName, int nIncludeLineNumber )
  185. {
  186. EnsureDependencyFileCheckedIn( pFilenameLoaded );
  187. }
  188. void CreateMakefile_OutputMakefile( void )
  189. {
  190. if( !g_bHasModelName )
  191. {
  192. MdlError( "Can't write makefile since a target mdl hasn't been specified!" );
  193. }
  194. FILE *fp = fopen( "makefile.tmp", "a" );
  195. if( !fp )
  196. {
  197. MdlError( "can't open makefile.tmp!\n" );
  198. }
  199. char mdlname[MAX_PATH];
  200. V_strcpy_safe( mdlname, gamedir );
  201. // if( *g_pPlatformName )
  202. // {
  203. // V_strcat_safe( mdlname, "platform_" );
  204. // V_strcat_safe( mdlname, g_pPlatformName );
  205. // V_strcat_safe( mdlname, "/" );
  206. // }
  207. V_strcat_safe( mdlname, "models/" );
  208. V_strcat_safe( mdlname, outname );
  209. Q_StripExtension( mdlname, mdlname, sizeof( mdlname ) );
  210. V_strcat_safe( mdlname, ".mdl" );
  211. Q_FixSlashes( mdlname );
  212. fprintf( fp, "%s:", mdlname );
  213. int i;
  214. for( i = 0; i < m_CreateMakefileDependencies.Count(); i++ )
  215. {
  216. fprintf( fp, " %s", m_CreateMakefileDependencies[i].String() );
  217. }
  218. fprintf( fp, "\n" );
  219. char mkdirpath[MAX_PATH];
  220. V_strcpy_safe( mkdirpath, mdlname );
  221. Q_StripFilename( mkdirpath );
  222. fprintf( fp, "\tmkdir \"%s\"\n", mkdirpath );
  223. fprintf( fp, "\t%s -quiet %s\n\n", CommandLine()->GetParm( 0 ), fullpath );
  224. fclose( fp );
  225. }
  226. //-----------------------------------------------------------------------------
  227. //
  228. //-----------------------------------------------------------------------------
  229. static bool g_bFirstWarning = true;
  230. void TokenError( const char *fmt, ... )
  231. {
  232. static char output[1024];
  233. va_list args;
  234. char *pFilename;
  235. int iLineNumber;
  236. if (GetTokenizerStatus( &pFilename, &iLineNumber ))
  237. {
  238. va_start( args, fmt );
  239. vsprintf( output, fmt, args );
  240. MdlError( "%s(%d): - %s", pFilename, iLineNumber, output );
  241. }
  242. else
  243. {
  244. va_start( args, fmt );
  245. vsprintf( output, fmt, args );
  246. MdlError( "%s", output );
  247. }
  248. }
  249. void MdlError( const char *fmt, ... )
  250. {
  251. static char output[1024];
  252. static char *knownExtensions[] = {".mdl", ".ani", ".phy", ".sw.vtx", ".dx80.vtx", ".dx90.vtx", ".vvd"};
  253. char fileName[MAX_PATH];
  254. char baseName[MAX_PATH];
  255. va_list args;
  256. Assert( 0 );
  257. if (g_quiet)
  258. {
  259. if (g_bFirstWarning)
  260. {
  261. printf("%s :\n", fullpath );
  262. g_bFirstWarning = false;
  263. }
  264. printf("\t");
  265. }
  266. printf("ERROR: ");
  267. va_start( args, fmt );
  268. vprintf( fmt, args );
  269. // delete premature files
  270. // unforunately, content is built without verification
  271. // ensuring that targets are not available, prevents check-in
  272. if (g_bHasModelName)
  273. {
  274. // undescriptive errors in batch processes could be anonymous
  275. printf("ERROR: Aborted Processing on '%s'\n", outname);
  276. V_strcpy_safe( fileName, gamedir );
  277. V_strcat_safe( fileName, "models/" );
  278. V_strcat_safe( fileName, outname );
  279. Q_FixSlashes( fileName );
  280. Q_StripExtension( fileName, baseName, sizeof( baseName ) );
  281. for (int i=0; i<ARRAYSIZE(knownExtensions); i++)
  282. {
  283. V_strcpy_safe( fileName, baseName);
  284. V_strcat_safe( fileName, knownExtensions[i] );
  285. // really need filesystem concept here
  286. // g_pFileSystem->RemoveFile( fileName );
  287. unlink( fileName );
  288. }
  289. }
  290. exit( -1 );
  291. }
  292. void MdlWarning( const char *fmt, ... )
  293. {
  294. va_list args;
  295. static char output[1024];
  296. if (g_bNoWarnings || g_maxWarnings == 0)
  297. return;
  298. WORD old = SetConsoleTextColor( 1, 1, 0, 1 );
  299. if (g_quiet)
  300. {
  301. if (g_bFirstWarning)
  302. {
  303. printf("%s :\n", fullpath );
  304. g_bFirstWarning = false;
  305. }
  306. printf("\t");
  307. }
  308. Assert( 0 );
  309. printf("WARNING: ");
  310. va_start( args, fmt );
  311. vprintf( fmt, args );
  312. if (g_maxWarnings > 0)
  313. g_maxWarnings--;
  314. if (g_maxWarnings == 0)
  315. {
  316. if (g_quiet)
  317. {
  318. printf("\t");
  319. }
  320. printf("suppressing further warnings...\n");
  321. }
  322. RestoreConsoleTextColor( old );
  323. }
  324. SpewRetval_t MdlSpewOutputFunc( SpewType_t type, char const *pMsg )
  325. {
  326. if ((( type == SPEW_MESSAGE ) || (type == SPEW_LOG )) && g_quiet)
  327. {
  328. // suppress
  329. }
  330. else if (type == SPEW_WARNING)
  331. {
  332. MdlWarning( "%s", pMsg );
  333. }
  334. else
  335. {
  336. return CmdLib_SpewOutputFunc( type, pMsg );
  337. }
  338. return SPEW_CONTINUE;
  339. }
  340. #ifndef _DEBUG
  341. void MdlHandleCrash( const char *pMessage, bool bAssert )
  342. {
  343. static LONG crashHandlerCount = 0;
  344. if ( InterlockedIncrement( &crashHandlerCount ) == 1 )
  345. {
  346. MdlError( "'%s' (assert: %d)\n", pMessage, bAssert );
  347. }
  348. InterlockedDecrement( &crashHandlerCount );
  349. }
  350. // This is called if we crash inside our crash handler. It just terminates the process immediately.
  351. LONG __stdcall MdlSecondExceptionFilter( struct _EXCEPTION_POINTERS *ExceptionInfo )
  352. {
  353. TerminateProcess( GetCurrentProcess(), 2 );
  354. return EXCEPTION_EXECUTE_HANDLER; // (never gets here anyway)
  355. }
  356. void MdlExceptionFilter( unsigned long code )
  357. {
  358. // This is called if we crash inside our crash handler. It just terminates the process immediately.
  359. SetUnhandledExceptionFilter( MdlSecondExceptionFilter );
  360. //DWORD code = ExceptionInfo->ExceptionRecord->ExceptionCode;
  361. #define ERR_RECORD( name ) { name, #name }
  362. struct
  363. {
  364. int code;
  365. char *pReason;
  366. } errors[] =
  367. {
  368. ERR_RECORD( EXCEPTION_ACCESS_VIOLATION ),
  369. ERR_RECORD( EXCEPTION_ARRAY_BOUNDS_EXCEEDED ),
  370. ERR_RECORD( EXCEPTION_BREAKPOINT ),
  371. ERR_RECORD( EXCEPTION_DATATYPE_MISALIGNMENT ),
  372. ERR_RECORD( EXCEPTION_FLT_DENORMAL_OPERAND ),
  373. ERR_RECORD( EXCEPTION_FLT_DIVIDE_BY_ZERO ),
  374. ERR_RECORD( EXCEPTION_FLT_INEXACT_RESULT ),
  375. ERR_RECORD( EXCEPTION_FLT_INVALID_OPERATION ),
  376. ERR_RECORD( EXCEPTION_FLT_OVERFLOW ),
  377. ERR_RECORD( EXCEPTION_FLT_STACK_CHECK ),
  378. ERR_RECORD( EXCEPTION_FLT_UNDERFLOW ),
  379. ERR_RECORD( EXCEPTION_ILLEGAL_INSTRUCTION ),
  380. ERR_RECORD( EXCEPTION_IN_PAGE_ERROR ),
  381. ERR_RECORD( EXCEPTION_INT_DIVIDE_BY_ZERO ),
  382. ERR_RECORD( EXCEPTION_INT_OVERFLOW ),
  383. ERR_RECORD( EXCEPTION_INVALID_DISPOSITION ),
  384. ERR_RECORD( EXCEPTION_NONCONTINUABLE_EXCEPTION ),
  385. ERR_RECORD( EXCEPTION_PRIV_INSTRUCTION ),
  386. ERR_RECORD( EXCEPTION_SINGLE_STEP ),
  387. ERR_RECORD( EXCEPTION_STACK_OVERFLOW ),
  388. ERR_RECORD( EXCEPTION_ACCESS_VIOLATION ),
  389. };
  390. int nErrors = sizeof( errors ) / sizeof( errors[0] );
  391. {
  392. int i;
  393. for ( i=0; i < nErrors; i++ )
  394. {
  395. if ( errors[i].code == code )
  396. MdlHandleCrash( errors[i].pReason, true );
  397. }
  398. if ( i == nErrors )
  399. {
  400. MdlHandleCrash( "Unknown reason", true );
  401. }
  402. }
  403. TerminateProcess( GetCurrentProcess(), 1 );
  404. }
  405. #endif
  406. /*
  407. =================
  408. =================
  409. */
  410. int k_memtotal;
  411. void *kalloc( int num, int size )
  412. {
  413. // printf( "calloc( %d, %d )\n", num, size );
  414. // printf( "%d ", num * size );
  415. int nMemSize = num * size;
  416. k_memtotal += nMemSize;
  417. // ensure memory alignment on maximum of ALIGN
  418. nMemSize += 511;
  419. void *ptr = malloc( nMemSize );
  420. memset( ptr, 0, nMemSize );
  421. ptr = (byte *)((int)((byte *)ptr + 511) & ~511);
  422. return ptr;
  423. }
  424. void kmemset( void *ptr, int value, int size )
  425. {
  426. // printf( "kmemset( %x, %d, %d )\n", ptr, value, size );
  427. memset( ptr, value, size );
  428. return;
  429. }
  430. int verify_atoi( const char *token )
  431. {
  432. if (token[0] != '-' && (token[0] < '0' || token[0] > '9'))
  433. {
  434. TokenError( "expecting number, got \"%s\"\n", token );
  435. }
  436. return atoi( token );
  437. }
  438. float verify_atof( const char *token )
  439. {
  440. if (token[0] != '-' && token[0] != '.' && (token[0] < '0' || token[0] > '9'))
  441. {
  442. TokenError( "expecting number, got \"%s\"\n", token );
  443. }
  444. return atof( token );
  445. }
  446. float verify_atof_with_null( const char *token )
  447. {
  448. if (strcmp( token, ".." ) == 0)
  449. return -1;
  450. if (token[0] != '-' && token[0] != '.' && (token[0] < '0' || token[0] > '9'))
  451. {
  452. TokenError( "expecting number, got \"%s\"\n", token );
  453. }
  454. return atof( token );
  455. }
  456. //-----------------------------------------------------------------------------
  457. // Key value block
  458. //-----------------------------------------------------------------------------
  459. static void AppendKeyValueText( CUtlVector< char > *pKeyValue, const char *pString )
  460. {
  461. int nLen = strlen(pString);
  462. int nFirst = pKeyValue->AddMultipleToTail( nLen );
  463. memcpy( pKeyValue->Base() + nFirst, pString, nLen );
  464. }
  465. int KeyValueTextSize( CUtlVector< char > *pKeyValue )
  466. {
  467. return pKeyValue->Count();
  468. }
  469. const char *KeyValueText( CUtlVector< char > *pKeyValue )
  470. {
  471. return pKeyValue->Base();
  472. }
  473. void Option_KeyValues( CUtlVector< char > *pKeyValue );
  474. //-----------------------------------------------------------------------------
  475. // Read global input into common string
  476. //-----------------------------------------------------------------------------
  477. bool GetLineInput( void )
  478. {
  479. while (fgets( g_szLine, sizeof( g_szLine ), g_fpInput ) != NULL)
  480. {
  481. g_iLinecount++;
  482. // skip comments
  483. if (g_szLine[0] == '/' && g_szLine[1] == '/')
  484. continue;
  485. return true;
  486. }
  487. return false;
  488. }
  489. /*
  490. =================
  491. =================
  492. */
  493. int lookupControl( char *string )
  494. {
  495. if (stricmp(string,"X")==0) return STUDIO_X;
  496. if (stricmp(string,"Y")==0) return STUDIO_Y;
  497. if (stricmp(string,"Z")==0) return STUDIO_Z;
  498. if (stricmp(string,"XR")==0) return STUDIO_XR;
  499. if (stricmp(string,"YR")==0) return STUDIO_YR;
  500. if (stricmp(string,"ZR")==0) return STUDIO_ZR;
  501. if (stricmp(string,"LX")==0) return STUDIO_LX;
  502. if (stricmp(string,"LY")==0) return STUDIO_LY;
  503. if (stricmp(string,"LZ")==0) return STUDIO_LZ;
  504. if (stricmp(string,"LXR")==0) return STUDIO_LXR;
  505. if (stricmp(string,"LYR")==0) return STUDIO_LYR;
  506. if (stricmp(string,"LZR")==0) return STUDIO_LZR;
  507. if (stricmp(string,"LM")==0) return STUDIO_LINEAR;
  508. if (stricmp(string,"LQ")==0) return STUDIO_QUADRATIC_MOTION;
  509. return -1;
  510. }
  511. /*
  512. =================
  513. =================
  514. */
  515. int LookupPoseParameter( char *name )
  516. {
  517. int i;
  518. for ( i = 0; i < g_numposeparameters; i++)
  519. {
  520. if (!stricmp( name, g_pose[i].name))
  521. {
  522. return i;
  523. }
  524. }
  525. V_strcpy_safe( g_pose[i].name, name );
  526. g_numposeparameters = i + 1;
  527. if (g_numposeparameters > MAXSTUDIOPOSEPARAM)
  528. {
  529. TokenError( "too many pose parameters (max %d)\n", MAXSTUDIOPOSEPARAM );
  530. }
  531. return i;
  532. }
  533. //-----------------------------------------------------------------------------
  534. // Stuff for writing a makefile to build models incrementally.
  535. //-----------------------------------------------------------------------------
  536. s_sourceanim_t *FindSourceAnim( s_source_t *pSource, const char *pAnimName )
  537. {
  538. int nCount = pSource->m_Animations.Count();
  539. for ( int i = 0; i < nCount; ++i )
  540. {
  541. s_sourceanim_t *pAnim = &pSource->m_Animations[i];
  542. if ( !Q_stricmp( pAnimName, pAnim->animationname ) )
  543. return pAnim;
  544. }
  545. return NULL;
  546. }
  547. const s_sourceanim_t *FindSourceAnim( const s_source_t *pSource, const char *pAnimName )
  548. {
  549. if ( !pAnimName[0] )
  550. return NULL;
  551. int nCount = pSource->m_Animations.Count();
  552. for ( int i = 0; i < nCount; ++i )
  553. {
  554. const s_sourceanim_t *pAnim = &pSource->m_Animations[i];
  555. if ( !Q_stricmp( pAnimName, pAnim->animationname ) )
  556. return pAnim;
  557. }
  558. return NULL;
  559. }
  560. s_sourceanim_t *FindOrAddSourceAnim( s_source_t *pSource, const char *pAnimName )
  561. {
  562. if ( !pAnimName[0] )
  563. return NULL;
  564. int nCount = pSource->m_Animations.Count();
  565. for ( int i = 0; i < nCount; ++i )
  566. {
  567. s_sourceanim_t *pAnim = &pSource->m_Animations[i];
  568. if ( !Q_stricmp( pAnimName, pAnim->animationname ) )
  569. return pAnim;
  570. }
  571. int nIndex = pSource->m_Animations.AddToTail();
  572. s_sourceanim_t *pAnim = &pSource->m_Animations[nIndex];
  573. memset( pAnim, 0, sizeof(s_sourceanim_t) );
  574. Q_strncpy( pAnim->animationname, pAnimName, sizeof(pAnim->animationname) );
  575. return pAnim;
  576. }
  577. //-----------------------------------------------------------------------------
  578. // Purpose: Handle the $boneflexdriver command
  579. // QC: $boneflexdriver <bone name> <tx|ty|tz> <flex controller name> <min> <max>
  580. //-----------------------------------------------------------------------------
  581. void Cmd_BoneFlexDriver()
  582. {
  583. CDisableUndoScopeGuard undoDisable; // Turn of Dme undo
  584. // Find or create the DmeBoneFlexDriverList
  585. CDmeBoneFlexDriverList *pDmeBoneFlexDriverList = GetElement< CDmeBoneFlexDriverList >( g_hDmeBoneFlexDriverList );
  586. if ( !pDmeBoneFlexDriverList )
  587. {
  588. pDmeBoneFlexDriverList = CreateElement< CDmeBoneFlexDriverList >( "boneDriverFlexList", DMFILEID_INVALID );
  589. if ( pDmeBoneFlexDriverList )
  590. {
  591. g_hDmeBoneFlexDriverList = pDmeBoneFlexDriverList->GetHandle();
  592. }
  593. }
  594. if ( !pDmeBoneFlexDriverList )
  595. {
  596. MdlError( "%s: Couldn't find or create DmeBoneDriverFlexList\n", "$boneflexdriver" );
  597. return;
  598. }
  599. // <bone name>
  600. GetToken( false );
  601. CDmeBoneFlexDriver *pDmeBoneFlexDriver = pDmeBoneFlexDriverList->FindOrCreateBoneFlexDriver( token );
  602. if ( !pDmeBoneFlexDriver )
  603. {
  604. MdlError( "%s: Couldn't find or create DmeBoneFlexDriver for bone \"%s\"\n", "$boneflexdriver", token );
  605. return;
  606. }
  607. // <tx|ty|tz|rx|ry|rz>
  608. GetToken( false );
  609. const char *ppszComponentTypeList[] = { "tx", "ty", "tz" };
  610. int nBoneComponent = -1;
  611. for ( int i = 0; i < ARRAYSIZE( ppszComponentTypeList ); ++i )
  612. {
  613. if ( StringHasPrefix( token, ppszComponentTypeList[i] ) )
  614. {
  615. nBoneComponent = i;
  616. break;
  617. }
  618. }
  619. if ( nBoneComponent < STUDIO_BONE_FLEX_TX || nBoneComponent > STUDIO_BONE_FLEX_TZ )
  620. {
  621. TokenError( "%s: Invalid bone component, must be one of <tx|ty|tz>\n", "$boneflexdriver" );
  622. return;
  623. }
  624. // <flex controller name>
  625. GetToken( false );
  626. CDmeBoneFlexDriverControl *pDmeBoneFlexDriverControl = pDmeBoneFlexDriver->FindOrCreateControl( token );
  627. if ( !pDmeBoneFlexDriverControl )
  628. {
  629. MdlError( "%s: Couldn't find or create DmeBoneFlexDriverControl for bone \"%s\"\n", "$boneflexdriver", token );
  630. return;
  631. }
  632. pDmeBoneFlexDriverControl->m_nBoneComponent = nBoneComponent;
  633. // <min>
  634. GetToken( false );
  635. pDmeBoneFlexDriverControl->m_flMin = verify_atof( token );
  636. // <max>
  637. GetToken( false );
  638. pDmeBoneFlexDriverControl->m_flMax = verify_atof( token );
  639. }
  640. //-----------------------------------------------------------------------------
  641. // Purpose: Handle the $checkuv command
  642. // QC: $checkuv [0to1] [overlap] [inverse] [gutter <res> <min>]
  643. //-----------------------------------------------------------------------------
  644. void Cmd_CheckUV()
  645. {
  646. g_StudioMdlCheckUVCmd.ClearCheck( CCheckUVCmd::CHECK_UV_ALL_FLAGS );
  647. while ( TokenAvailable() && GetToken( false ) )
  648. {
  649. if ( !V_stricmp( token, "0to1" ) )
  650. {
  651. g_StudioMdlCheckUVCmd.SetCheck( CCheckUVCmd::CHECK_UV_FLAG_NORMALIZED );
  652. }
  653. else if ( !V_stricmp( token, "overlap" ) )
  654. {
  655. g_StudioMdlCheckUVCmd.SetCheck( CCheckUVCmd::CHECK_UV_FLAG_OVERLAP );
  656. }
  657. else if ( !V_stricmp( token, "inverse" ) )
  658. {
  659. g_StudioMdlCheckUVCmd.SetCheck( CCheckUVCmd::CHECK_UV_FLAG_INVERSE );
  660. }
  661. else if ( !V_stricmp( token, "gutter" ) )
  662. {
  663. g_StudioMdlCheckUVCmd.SetCheck( CCheckUVCmd::CHECK_UV_FLAG_GUTTER );
  664. if ( TokenAvailable() && GetToken( false ) )
  665. {
  666. if ( V_isdigit( *token ) )
  667. {
  668. const int nOptRes = V_atoi( token );
  669. if ( nOptRes <= 0 )
  670. {
  671. MdlError( "$checkuv: Invalid resolution, \"%s\", for gutter check specified, must be > 0\n", token );
  672. return;
  673. }
  674. g_StudioMdlCheckUVCmd.m_nOptGutterTexWidth = nOptRes;
  675. g_StudioMdlCheckUVCmd.m_nOptGutterTexHeight = nOptRes;
  676. if ( TokenAvailable() && GetToken( false ) )
  677. {
  678. if ( V_isdigit( *token ) )
  679. {
  680. const int nOptMin = V_atoi( token );
  681. if ( nOptMin <= 0 )
  682. {
  683. MdlError( "$checkuv: Invalid minimum, \"%s\", for gutter check specified, must be > 0\n", token );
  684. return;
  685. }
  686. g_StudioMdlCheckUVCmd.m_nOptGutterMin = nOptMin;
  687. }
  688. else
  689. {
  690. UnGetToken();
  691. }
  692. }
  693. }
  694. else
  695. {
  696. UnGetToken();
  697. }
  698. }
  699. }
  700. else
  701. {
  702. MdlError( "$checkuv: Unknown argument \"%s\", expected one of [ 0to1, overlap, inverse, gutter ]\n", token );
  703. return;
  704. }
  705. }
  706. if ( !g_StudioMdlCheckUVCmd.DoAnyCheck() )
  707. {
  708. g_StudioMdlCheckUVCmd.SetCheck( CCheckUVCmd::CHECK_UV_ALL_FLAGS );
  709. }
  710. }
  711. void Cmd_PoseParameter( )
  712. {
  713. if ( g_numposeparameters >= MAXSTUDIOPOSEPARAM )
  714. {
  715. TokenError( "too many pose parameters (max %d)\n", MAXSTUDIOPOSEPARAM );
  716. }
  717. int i = LookupPoseParameter( token );
  718. // name
  719. GetToken (false);
  720. V_strcpy_safe( g_pose[i].name, token );
  721. if ( TokenAvailable() )
  722. {
  723. // min
  724. GetToken (false);
  725. g_pose[i].min = verify_atof (token);
  726. }
  727. if ( TokenAvailable() )
  728. {
  729. // max
  730. GetToken (false);
  731. g_pose[i].max = verify_atof (token);
  732. }
  733. while ( TokenAvailable() )
  734. {
  735. GetToken (false);
  736. if ( !Q_stricmp( token, "wrap" ) )
  737. {
  738. g_pose[i].flags |= STUDIO_LOOPING;
  739. g_pose[i].loop = g_pose[i].max - g_pose[i].min;
  740. }
  741. else if ( !Q_stricmp( token, "loop" ) )
  742. {
  743. g_pose[i].flags |= STUDIO_LOOPING;
  744. GetToken (false);
  745. g_pose[i].loop = verify_atof( token );
  746. }
  747. }
  748. }
  749. /*
  750. =================
  751. =================
  752. */
  753. int LookupTexture( const char *pTextureName, bool bRelativePath )
  754. {
  755. char pTextureNoExt[MAX_PATH];
  756. char pTextureBase[MAX_PATH];
  757. char pTextureBase2[MAX_PATH];
  758. Q_StripExtension( pTextureName, pTextureNoExt, sizeof(pTextureNoExt) );
  759. Q_FileBase( pTextureName, pTextureBase, sizeof(pTextureBase) );
  760. int nFlags = bRelativePath ? RELATIVE_TEXTURE_PATH_SPECIFIED : 0;
  761. int i;
  762. for ( i = 0; i < g_numtextures; i++ )
  763. {
  764. if ( g_texture[i].flags == nFlags )
  765. {
  766. if ( !Q_stricmp( pTextureNoExt, g_texture[i].name ) )
  767. return i;
  768. continue;
  769. }
  770. // Comparing relative vs non-relative
  771. if ( bRelativePath )
  772. {
  773. if ( !Q_stricmp( pTextureBase, g_texture[i].name ) )
  774. return i;
  775. continue;
  776. }
  777. // Comparing non-relative vs relative
  778. Q_FileBase( g_texture[i].name, pTextureBase2, sizeof(pTextureBase2) );
  779. if ( !Q_stricmp( pTextureNoExt, pTextureBase2 ) )
  780. return i;
  781. }
  782. if ( i >= MAXSTUDIOSKINS )
  783. {
  784. MdlError("Too many materials used, max %d\n", ( int )MAXSTUDIOSKINS );
  785. }
  786. Q_strncpy( g_texture[i].name, pTextureNoExt, sizeof(g_texture[i].name) );
  787. g_texture[i].material = -1;
  788. g_texture[i].flags = nFlags;
  789. g_numtextures++;
  790. return i;
  791. }
  792. void Cmd_RenameMaterial( void )
  793. {
  794. char from[256];
  795. char to[256];
  796. GetToken( false );
  797. V_strcpy_safe( from, token );
  798. GetToken( false );
  799. V_strcpy_safe( to, token );
  800. int i;
  801. for (i = 0; i < g_numtextures; i++)
  802. {
  803. if (stricmp( g_texture[i].name, from ) == 0)
  804. {
  805. V_strcpy_safe( g_texture[i].name, to );
  806. return;
  807. }
  808. }
  809. MdlError( "unknown material \"%s\" in rename\n", from );
  810. }
  811. int UseTextureAsMaterial( int textureindex )
  812. {
  813. if ( g_texture[textureindex].material == -1 )
  814. {
  815. if (g_bDumpMaterials)
  816. {
  817. printf("material %d %d %s\n", textureindex, g_nummaterials, g_texture[textureindex].name );
  818. }
  819. g_material[g_nummaterials] = textureindex;
  820. g_texture[textureindex].material = g_nummaterials++;
  821. }
  822. return g_texture[textureindex].material;
  823. }
  824. int MaterialToTexture( int material )
  825. {
  826. int i;
  827. for (i = 0; i < g_numtextures; i++)
  828. {
  829. if (g_texture[i].material == material)
  830. {
  831. return i;
  832. }
  833. }
  834. return -1;
  835. }
  836. //Wrong name for the use of it.
  837. void scale_vertex( Vector &org )
  838. {
  839. org[0] = org[0] * g_currentscale;
  840. org[1] = org[1] * g_currentscale;
  841. org[2] = org[2] * g_currentscale;
  842. }
  843. void SetSkinValues( )
  844. {
  845. int i, j;
  846. int index;
  847. // Check all textures to see if we have relative paths specified
  848. for (i = 0; i < g_numtextures; i++)
  849. {
  850. if ( g_texture[i].flags & RELATIVE_TEXTURE_PATH_SPECIFIED )
  851. {
  852. // Add an empty path to prepend if anything specifies a relative path
  853. cdtextures[numcdtextures] = 0;
  854. ++numcdtextures;
  855. break;
  856. }
  857. }
  858. if ( numcdtextures == 0 )
  859. {
  860. char szName[MAX_PATH];
  861. // strip down till it finds "models"
  862. V_strcpy_safe( szName, fullpath );
  863. while (szName[0] != '\0' && strnicmp( "models", szName, 6 ) != 0)
  864. {
  865. strcpy( &szName[0], &szName[1] );
  866. }
  867. if (szName[0] != '\0')
  868. {
  869. Q_StripFilename( szName );
  870. V_strcat_safe( szName, "/" );
  871. }
  872. else
  873. {
  874. // if( *g_pPlatformName )
  875. // {
  876. // V_strcat_safe( szName, "platform_" );
  877. // V_strcat_safe( szName, g_pPlatformName );
  878. // V_strcat_safe( szName, "/" );
  879. // }
  880. V_strcpy_safe( szName, "models/" );
  881. V_strcat_safe( szName, outname );
  882. Q_StripExtension( szName, szName, sizeof( szName ) );
  883. V_strcat_safe( szName, "/" );
  884. }
  885. cdtextures[0] = strdup( szName );
  886. numcdtextures = 1;
  887. }
  888. for (i = 0; i < g_numtextures; i++)
  889. {
  890. char szName[256];
  891. Q_StripExtension( g_texture[i].name, szName, sizeof( szName ) );
  892. Q_strncpy( g_texture[i].name, szName, sizeof( g_texture[i].name ) );
  893. }
  894. // build texture groups
  895. for (i = 0; i < MAXSTUDIOSKINS; i++)
  896. {
  897. for (j = 0; j < MAXSTUDIOSKINS; j++)
  898. {
  899. g_skinref[i][j] = j;
  900. }
  901. }
  902. index = 0;
  903. for (i = 0; i < g_numtexturelayers[0]; i++)
  904. {
  905. for (j = 0; j < g_numtexturereps[0]; j++)
  906. {
  907. g_skinref[i][g_texturegroup[0][0][j]] = g_texturegroup[0][i][j];
  908. }
  909. }
  910. if (i != 0)
  911. {
  912. g_numskinfamilies = i;
  913. }
  914. else
  915. {
  916. g_numskinfamilies = 1;
  917. }
  918. g_numskinref = g_numtextures;
  919. // printf ("width: %i height: %i\n",width, height);
  920. /*
  921. printf ("adjusted width: %i height: %i top : %i left: %i\n",
  922. pmesh->skinwidth, pmesh->skinheight, pmesh->skintop, pmesh->skinleft );
  923. */
  924. }
  925. /*
  926. =================
  927. =================
  928. */
  929. int LookupXNode( char *name )
  930. {
  931. int i;
  932. for ( i = 1; i <= g_numxnodes; i++)
  933. {
  934. if (stricmp( name, g_xnodename[i] ) == 0)
  935. {
  936. return i;
  937. }
  938. }
  939. g_xnodename[i] = strdup( name );
  940. g_numxnodes = i;
  941. return i;
  942. }
  943. /*
  944. =================
  945. =================
  946. */
  947. char g_szFilename[1024];
  948. FILE *g_fpInput;
  949. char g_szLine[4096];
  950. int g_iLinecount;
  951. void Build_Reference( s_source_t *pSource, const char *pAnimName )
  952. {
  953. int i, parent;
  954. Vector angle;
  955. s_sourceanim_t *pReferenceAnim = FindSourceAnim( pSource, pAnimName );
  956. for (i = 0; i < pSource->numbones; i++)
  957. {
  958. matrix3x4_t m;
  959. if ( pReferenceAnim )
  960. {
  961. AngleMatrix( pReferenceAnim->rawanim[0][i].rot, m );
  962. m[0][3] = pReferenceAnim->rawanim[0][i].pos[0];
  963. m[1][3] = pReferenceAnim->rawanim[0][i].pos[1];
  964. m[2][3] = pReferenceAnim->rawanim[0][i].pos[2];
  965. }
  966. else
  967. {
  968. SetIdentityMatrix( m );
  969. }
  970. parent = pSource->localBone[i].parent;
  971. if (parent == -1)
  972. {
  973. // scale the done pos.
  974. // calc rotational matrices
  975. MatrixCopy( m, pSource->boneToPose[i] );
  976. }
  977. else
  978. {
  979. // calc compound rotational matrices
  980. // FIXME : Hey, it's orthogical so inv(A) == transpose(A)
  981. Assert( parent < i );
  982. ConcatTransforms( pSource->boneToPose[parent], m, pSource->boneToPose[i] );
  983. }
  984. // printf("%3d %f %f %f\n", i, psource->bonefixup[i].worldorg[0], psource->bonefixup[i].worldorg[1], psource->bonefixup[i].worldorg[2] );
  985. /*
  986. AngleMatrix( angle, m );
  987. printf("%8.4f %8.4f %8.4f\n", m[0][0], m[1][0], m[2][0] );
  988. printf("%8.4f %8.4f %8.4f\n", m[0][1], m[1][1], m[2][1] );
  989. printf("%8.4f %8.4f %8.4f\n", m[0][2], m[1][2], m[2][2] );
  990. */
  991. }
  992. }
  993. int Grab_Nodes( s_node_t *pnodes )
  994. {
  995. int index;
  996. char name[1024];
  997. int parent;
  998. int numbones = 0;
  999. for (index = 0; index < MAXSTUDIOSRCBONES; index++)
  1000. {
  1001. pnodes[index].parent = -1;
  1002. }
  1003. while (GetLineInput())
  1004. {
  1005. if (sscanf( g_szLine, "%d \"%[^\"]\" %d", &index, name, &parent ) == 3)
  1006. {
  1007. // check for duplicated bones
  1008. /*
  1009. if (strlen(pnodes[index].name) != 0)
  1010. {
  1011. MdlError( "bone \"%s\" exists more than once\n", name );
  1012. }
  1013. */
  1014. V_strcpy_safe( pnodes[index].name, name );
  1015. pnodes[index].parent = parent;
  1016. if (index > numbones)
  1017. {
  1018. numbones = index;
  1019. }
  1020. }
  1021. else
  1022. {
  1023. return numbones + 1;
  1024. }
  1025. }
  1026. MdlError( "Unexpected EOF at line %d\n", g_iLinecount );
  1027. return 0;
  1028. }
  1029. void clip_rotations( RadianEuler& rot )
  1030. {
  1031. int j;
  1032. // clip everything to : -M_PI <= x < M_PI
  1033. for (j = 0; j < 3; j++) {
  1034. while (rot[j] >= M_PI)
  1035. rot[j] -= M_PI*2;
  1036. while (rot[j] < -M_PI)
  1037. rot[j] += M_PI*2;
  1038. }
  1039. }
  1040. void clip_rotations( Vector& rot )
  1041. {
  1042. int j;
  1043. // clip everything to : -180 <= x < 180
  1044. for (j = 0; j < 3; j++) {
  1045. while (rot[j] >= 180)
  1046. rot[j] -= 180*2;
  1047. while (rot[j] < -180)
  1048. rot[j] += 180*2;
  1049. }
  1050. }
  1051. /*
  1052. =================
  1053. Cmd_Eyeposition
  1054. =================
  1055. */
  1056. void Cmd_Eyeposition (void)
  1057. {
  1058. // rotate points into frame of reference so g_model points down the positive x
  1059. // axis
  1060. // FIXME: these coords are bogus
  1061. GetToken (false);
  1062. eyeposition[1] = verify_atof (token);
  1063. GetToken (false);
  1064. eyeposition[0] = -verify_atof (token);
  1065. GetToken (false);
  1066. eyeposition[2] = verify_atof (token);
  1067. }
  1068. //-----------------------------------------------------------------------------
  1069. // Cmd_MaxEyeDeflection
  1070. //-----------------------------------------------------------------------------
  1071. void Cmd_MaxEyeDeflection()
  1072. {
  1073. GetToken( false );
  1074. g_flMaxEyeDeflection = cosf( verify_atof( token ) * M_PI / 180.0f );
  1075. }
  1076. //-----------------------------------------------------------------------------
  1077. // Cmd_Illumposition
  1078. //-----------------------------------------------------------------------------
  1079. void Cmd_Illumposition( void )
  1080. {
  1081. GetToken( false );
  1082. illumposition[0] = verify_atof( token );
  1083. GetToken( false );
  1084. illumposition[1] = verify_atof( token );
  1085. GetToken( false );
  1086. illumposition[2] = verify_atof( token );
  1087. if ( TokenAvailable() )
  1088. {
  1089. GetToken( false );
  1090. Q_strncpy( g_attachment[g_numattachments].name, "__illumPosition", sizeof(g_attachment[g_numattachments].name) );
  1091. Q_strncpy( g_attachment[g_numattachments].bonename, token, sizeof(g_attachment[g_numattachments].bonename) );
  1092. AngleMatrix( QAngle( 0, 0, 0 ), illumposition, g_attachment[g_numattachments].local );
  1093. g_attachment[g_numattachments].type |= IS_RIGID;
  1094. g_illumpositionattachment = g_numattachments + 1;
  1095. ++g_numattachments;
  1096. }
  1097. else
  1098. {
  1099. g_illumpositionattachment = 0;
  1100. // rotate points into frame of reference so
  1101. // g_model points down the positive x axis
  1102. // FIXME: these coords are bogus
  1103. float flTemp = illumposition[0];
  1104. illumposition[0] = -illumposition[1];
  1105. illumposition[1] = flTemp;
  1106. }
  1107. illumpositionset = true;
  1108. }
  1109. //-----------------------------------------------------------------------------
  1110. // Process Cmd_Modelname
  1111. //-----------------------------------------------------------------------------
  1112. void ProcessModelName( const char *pModelName )
  1113. {
  1114. // Abort early if modelname is too big
  1115. // - actually that's okay, it's just an identifier and can be truncated
  1116. g_bHasModelName = true;
  1117. Q_strncpy( outname, pModelName, sizeof( outname ) );
  1118. }
  1119. //-----------------------------------------------------------------------------
  1120. // Parse Cmd_Modelname
  1121. //-----------------------------------------------------------------------------
  1122. void Cmd_Modelname (void)
  1123. {
  1124. GetToken (false);
  1125. if ( token[0] == '/' || token[0] == '\\' )
  1126. {
  1127. MdlWarning( "$modelname key has slash as first character. Removing.\n" );
  1128. ProcessModelName( &token[1] );
  1129. }
  1130. else
  1131. {
  1132. ProcessModelName( token );
  1133. }
  1134. }
  1135. void Cmd_Autocenter()
  1136. {
  1137. g_centerstaticprop = true;
  1138. }
  1139. /*
  1140. ===============
  1141. ===============
  1142. */
  1143. //-----------------------------------------------------------------------------
  1144. // Parse the body command from a .qc file
  1145. //-----------------------------------------------------------------------------
  1146. void ProcessOptionStudio( s_model_t *pmodel, const char *pFullPath, CDmeSourceSkin *pSkin )
  1147. {
  1148. Q_strncpy( pmodel->filename, pFullPath, sizeof(pmodel->filename) );
  1149. if ( pSkin->m_flScale != 0.0f )
  1150. {
  1151. pmodel->scale = g_currentscale = pSkin->m_flScale;
  1152. }
  1153. else
  1154. {
  1155. pmodel->scale = g_currentscale = g_defaultscale;
  1156. }
  1157. // load source
  1158. pmodel->source = Load_Source( pmodel->filename, "", pSkin->m_bFlipTriangles, true );
  1159. // Reset currentscale to whatever global we currently have set
  1160. // g_defaultscale gets set in Cmd_ScaleUp everytime the $scale command is used.
  1161. g_currentscale = g_defaultscale;
  1162. }
  1163. //-----------------------------------------------------------------------------
  1164. // Parse the studio options from a .qc file
  1165. //-----------------------------------------------------------------------------
  1166. bool ParseOptionStudio( CDmeSourceSkin *pSkin )
  1167. {
  1168. if ( !GetToken( false ) )
  1169. return false;
  1170. pSkin->SetRelativeFileName( token );
  1171. while ( TokenAvailable() )
  1172. {
  1173. GetToken(false);
  1174. if ( !Q_stricmp( "reverse", token ) )
  1175. {
  1176. pSkin->m_bFlipTriangles = true;
  1177. continue;
  1178. }
  1179. if ( !Q_stricmp( "scale", token ) )
  1180. {
  1181. GetToken(false);
  1182. pSkin->m_flScale = verify_atof( token );
  1183. continue;
  1184. }
  1185. if ( !Q_stricmp( "faces", token ) )
  1186. {
  1187. GetToken( false );
  1188. GetToken( false );
  1189. continue;
  1190. }
  1191. if ( !Q_stricmp( "bias", token ) )
  1192. {
  1193. GetToken( false );
  1194. continue;
  1195. }
  1196. if ( !Q_stricmp( "{", token ) )
  1197. {
  1198. UnGetToken( );
  1199. break;
  1200. }
  1201. MdlError("unknown command \"%s\"\n", token );
  1202. return false;
  1203. }
  1204. return true;
  1205. }
  1206. //-----------------------------------------------------------------------------
  1207. // Parse + process the studio options from a .qc file
  1208. //-----------------------------------------------------------------------------
  1209. void Option_Studio( s_model_t *pmodel )
  1210. {
  1211. CDmeSourceSkin *pSourceSkin = CreateElement< CDmeSourceSkin >( "" );
  1212. // Set defaults
  1213. pSourceSkin->m_flScale = g_defaultscale;
  1214. if ( ParseOptionStudio( pSourceSkin ) )
  1215. {
  1216. ProcessOptionStudio( pmodel, pSourceSkin->GetRelativeFileName(), pSourceSkin );
  1217. }
  1218. DestroyElement( pSourceSkin );
  1219. }
  1220. int Option_Blank( )
  1221. {
  1222. g_model[g_nummodels] = (s_model_t *)kalloc( 1, sizeof( s_model_t ) );
  1223. g_source[g_numsources] = (s_source_t *)kalloc( 1, sizeof( s_source_t ) );
  1224. g_model[g_nummodels]->source = g_source[g_numsources];
  1225. g_numsources++;
  1226. g_bodypart[g_numbodyparts].pmodel[g_bodypart[g_numbodyparts].nummodels] = g_model[g_nummodels];
  1227. V_strcpy_safe( g_model[g_nummodels]->name, "blank" );
  1228. g_bodypart[g_numbodyparts].nummodels++;
  1229. g_nummodels++;
  1230. return 0;
  1231. }
  1232. void Cmd_Bodygroup( )
  1233. {
  1234. int is_started = 0;
  1235. if ( !GetToken( false ) )
  1236. return;
  1237. if (g_numbodyparts == 0)
  1238. {
  1239. g_bodypart[g_numbodyparts].base = 1;
  1240. }
  1241. else
  1242. {
  1243. g_bodypart[g_numbodyparts].base = g_bodypart[g_numbodyparts-1].base * g_bodypart[g_numbodyparts-1].nummodels;
  1244. }
  1245. V_strcpy_safe( g_bodypart[g_numbodyparts].name, token );
  1246. do
  1247. {
  1248. GetToken (true);
  1249. if (endofscript)
  1250. return;
  1251. else if (token[0] == '{')
  1252. {
  1253. is_started = 1;
  1254. }
  1255. else if (token[0] == '}')
  1256. {
  1257. break;
  1258. }
  1259. else if (stricmp("studio", token ) == 0)
  1260. {
  1261. g_model[g_nummodels] = (s_model_t *)kalloc( 1, sizeof( s_model_t ) );
  1262. g_bodypart[g_numbodyparts].pmodel[g_bodypart[g_numbodyparts].nummodels] = g_model[g_nummodels];
  1263. g_bodypart[g_numbodyparts].nummodels++;
  1264. Option_Studio( g_model[g_nummodels] );
  1265. // Body command should add any flex commands in the source loaded
  1266. if ( g_model[g_nummodels]->source )
  1267. {
  1268. AddBodyFlexData( g_model[g_nummodels]->source, g_nummodels );
  1269. AddBodyAttachments( g_model[g_nummodels]->source );
  1270. }
  1271. g_nummodels++;
  1272. }
  1273. else if (stricmp("blank", token ) == 0)
  1274. {
  1275. Option_Blank( );
  1276. }
  1277. else
  1278. {
  1279. MdlError("unknown bodygroup option: \"%s\"\n", token );
  1280. }
  1281. } while (1);
  1282. g_numbodyparts++;
  1283. return;
  1284. }
  1285. //-----------------------------------------------------------------------------
  1286. // Add A Body Flex Rule
  1287. //-----------------------------------------------------------------------------
  1288. void AddBodyFlexFetchRule(
  1289. s_source_t *pSource,
  1290. s_flexrule_t *pRule,
  1291. int rawIndex,
  1292. const CUtlVector< int > &pRawIndexToRemapSourceIndex,
  1293. const CUtlVector< int > &pRawIndexToRemapLocalIndex,
  1294. const CUtlVector< int > &pRemapSourceIndexToGlobalFlexControllerIndex )
  1295. {
  1296. // Lookup the various indices of the requested input to fetch
  1297. // Relative to the remapped controls in the current s_source_t
  1298. const int remapSourceIndex = pRawIndexToRemapSourceIndex[ rawIndex ];
  1299. // Relative to the specific remapped control
  1300. const int remapLocalIndex = pRawIndexToRemapLocalIndex[ rawIndex ];
  1301. // The global flex controller index that the user ultimately twiddles
  1302. const int globalFlexControllerIndex = pRemapSourceIndexToGlobalFlexControllerIndex[ remapSourceIndex ];
  1303. // Get the Remap record
  1304. s_flexcontrollerremap_t &remap = pSource->m_FlexControllerRemaps[ remapSourceIndex ];
  1305. switch ( remap.m_RemapType )
  1306. {
  1307. case FLEXCONTROLLER_REMAP_PASSTHRU:
  1308. // Easy As!
  1309. pRule->op[ pRule->numops ].op = STUDIO_FETCH1;
  1310. pRule->op[ pRule->numops ].d.index = globalFlexControllerIndex;
  1311. pRule->numops++;
  1312. break;
  1313. case FLEXCONTROLLER_REMAP_EYELID:
  1314. if ( remapLocalIndex == 0 )
  1315. {
  1316. pRule->op[ pRule->numops ].op = STUDIO_CONST;
  1317. pRule->op[ pRule->numops ].d.value = remap.m_EyesUpDownFlexController >= 0 ? remap.m_EyesUpDownFlexController : -1;
  1318. pRule->numops++;
  1319. pRule->op[ pRule->numops ].op = STUDIO_CONST;
  1320. pRule->op[ pRule->numops ].d.value = remap.m_BlinkController >= 0 ? remap.m_BlinkController : -1;
  1321. pRule->numops++;
  1322. pRule->op[ pRule->numops ].op = STUDIO_CONST;
  1323. pRule->op[ pRule->numops ].d.value = globalFlexControllerIndex; // CloseLid
  1324. pRule->numops++;
  1325. pRule->op[ pRule->numops ].op = STUDIO_DME_LOWER_EYELID;
  1326. pRule->op[ pRule->numops ].d.index = remap.m_MultiIndex; // CloseLidV
  1327. pRule->numops++;
  1328. }
  1329. else
  1330. {
  1331. pRule->op[ pRule->numops ].op = STUDIO_CONST;
  1332. pRule->op[ pRule->numops ].d.value = remap.m_EyesUpDownFlexController >= 0 ? remap.m_EyesUpDownFlexController : -1;
  1333. pRule->numops++;
  1334. pRule->op[ pRule->numops ].op = STUDIO_CONST;
  1335. pRule->op[ pRule->numops ].d.value = remap.m_BlinkController >= 0 ? remap.m_BlinkController : -1;
  1336. pRule->numops++;
  1337. pRule->op[ pRule->numops ].op = STUDIO_CONST;
  1338. pRule->op[ pRule->numops ].d.value = globalFlexControllerIndex; // CloseLid
  1339. pRule->numops++;
  1340. pRule->op[ pRule->numops ].op = STUDIO_DME_UPPER_EYELID;
  1341. pRule->op[ pRule->numops ].d.index = remap.m_MultiIndex; // CloseLidV
  1342. pRule->numops++;
  1343. }
  1344. break;
  1345. case FLEXCONTROLLER_REMAP_2WAY:
  1346. // A little trickier... local index 0 is on the left, local index 1 is on the right
  1347. // Left Equivalent RemapVal( -1.0, 0.0, 0.0, 1.0 )
  1348. // Right Equivalent RemapVal( 0.0, 1.0, 0.0, 1.0 )
  1349. if ( remapLocalIndex == 0 )
  1350. {
  1351. pRule->op[ pRule->numops ].op = STUDIO_2WAY_0;
  1352. pRule->op[ pRule->numops ].d.index = globalFlexControllerIndex;
  1353. pRule->numops++;
  1354. }
  1355. else
  1356. {
  1357. pRule->op[ pRule->numops ].op = STUDIO_2WAY_1;
  1358. pRule->op[ pRule->numops ].d.index = globalFlexControllerIndex;
  1359. pRule->numops++;
  1360. }
  1361. break;
  1362. case FLEXCONTROLLER_REMAP_NWAY:
  1363. {
  1364. int nRemapCount = remap.m_RawControls.Count();
  1365. float flStep = ( nRemapCount > 2 ) ? 2.0f / ( nRemapCount - 1 ) : 0.0f;
  1366. if ( remapLocalIndex == 0 )
  1367. {
  1368. pRule->op[ pRule->numops ].op = STUDIO_CONST;
  1369. pRule->op[ pRule->numops ].d.value = -11.0f;
  1370. pRule->numops++;
  1371. pRule->op[ pRule->numops ].op = STUDIO_CONST;
  1372. pRule->op[ pRule->numops ].d.value = -10.0f;
  1373. pRule->numops++;
  1374. pRule->op[ pRule->numops ].op = STUDIO_CONST;
  1375. pRule->op[ pRule->numops ].d.value = -1.0f;
  1376. pRule->numops++;
  1377. pRule->op[ pRule->numops ].op = STUDIO_CONST;
  1378. pRule->op[ pRule->numops ].d.value = -1.0f + flStep;
  1379. pRule->numops++;
  1380. }
  1381. else if ( remapLocalIndex == nRemapCount - 1 )
  1382. {
  1383. pRule->op[ pRule->numops ].op = STUDIO_CONST;
  1384. pRule->op[ pRule->numops ].d.value = 1.0f - flStep;
  1385. pRule->numops++;
  1386. pRule->op[ pRule->numops ].op = STUDIO_CONST;
  1387. pRule->op[ pRule->numops ].d.value = 1.0f;
  1388. pRule->numops++;
  1389. pRule->op[ pRule->numops ].op = STUDIO_CONST;
  1390. pRule->op[ pRule->numops ].d.value = 10.0f;
  1391. pRule->numops++;
  1392. pRule->op[ pRule->numops ].op = STUDIO_CONST;
  1393. pRule->op[ pRule->numops ].d.value = 11.0f;
  1394. pRule->numops++;
  1395. }
  1396. else
  1397. {
  1398. float flPeak = remapLocalIndex * flStep - 1.0f;
  1399. pRule->op[ pRule->numops ].op = STUDIO_CONST;
  1400. pRule->op[ pRule->numops ].d.value = flPeak - flStep;
  1401. pRule->numops++;
  1402. pRule->op[ pRule->numops ].op = STUDIO_CONST;
  1403. pRule->op[ pRule->numops ].d.value = flPeak;
  1404. pRule->numops++;
  1405. pRule->op[ pRule->numops ].op = STUDIO_CONST;
  1406. pRule->op[ pRule->numops ].d.value = flPeak;
  1407. pRule->numops++;
  1408. pRule->op[ pRule->numops ].op = STUDIO_CONST;
  1409. pRule->op[ pRule->numops ].d.value = flPeak + flStep;
  1410. pRule->numops++;
  1411. }
  1412. pRule->op[ pRule->numops ].op = STUDIO_CONST;
  1413. pRule->op[ pRule->numops ].d.value = remap.m_MultiIndex;
  1414. pRule->numops++;
  1415. pRule->op[ pRule->numops ].op = STUDIO_NWAY;
  1416. pRule->op[ pRule->numops ].d.index = globalFlexControllerIndex;
  1417. pRule->numops++;
  1418. }
  1419. break;
  1420. default:
  1421. Assert( 0 );
  1422. // This is an error condition
  1423. pRule->op[ pRule->numops ].op = STUDIO_CONST;
  1424. pRule->op[ pRule->numops ].d.value = 1.0f;
  1425. pRule->numops++;
  1426. break;
  1427. }
  1428. }
  1429. //-----------------------------------------------------------------------------
  1430. // Add A Body Flex Rule
  1431. //-----------------------------------------------------------------------------
  1432. void AddBodyFlexRule(
  1433. s_source_t *pSource,
  1434. s_combinationrule_t &rule,
  1435. int nFlexDesc,
  1436. const CUtlVector< int > &pRawIndexToRemapSourceIndex,
  1437. const CUtlVector< int > &pRawIndexToRemapLocalIndex,
  1438. const CUtlVector< int > &pRemapSourceIndexToGlobalFlexControllerIndex )
  1439. {
  1440. if ( g_numflexrules >= MAXSTUDIOFLEXRULES )
  1441. MdlError( "Line %d: Too many flex rules, max %d",
  1442. g_iLinecount, MAXSTUDIOFLEXRULES );
  1443. s_flexrule_t *pRule = &g_flexrule[g_numflexrules++];
  1444. pRule->flex = nFlexDesc;
  1445. // This will multiply the combination together
  1446. const int nCombinationCount = rule.m_Combination.Count();
  1447. if ( nCombinationCount )
  1448. {
  1449. for ( int j = 0; j < nCombinationCount; ++j )
  1450. {
  1451. // Handle any controller remapping
  1452. AddBodyFlexFetchRule( pSource, pRule, rule.m_Combination[ j ],
  1453. pRawIndexToRemapSourceIndex, pRawIndexToRemapLocalIndex,
  1454. pRemapSourceIndexToGlobalFlexControllerIndex );
  1455. }
  1456. if ( nCombinationCount > 1 )
  1457. {
  1458. pRule->op[ pRule->numops ].op = STUDIO_COMBO;
  1459. pRule->op[ pRule->numops ].d.index = nCombinationCount;
  1460. pRule->numops++;
  1461. }
  1462. }
  1463. // This will multiply in the suppressors
  1464. int nDominators = rule.m_Dominators.Count();
  1465. for ( int j = 0; j < nDominators; ++j )
  1466. {
  1467. const int nFactorCount = rule.m_Dominators[j].Count();
  1468. if ( nFactorCount )
  1469. {
  1470. for ( int k = 0; k < nFactorCount; ++k )
  1471. {
  1472. AddBodyFlexFetchRule( pSource, pRule, rule.m_Dominators[ j ][ k ],
  1473. pRawIndexToRemapSourceIndex, pRawIndexToRemapLocalIndex,
  1474. pRemapSourceIndexToGlobalFlexControllerIndex );
  1475. }
  1476. pRule->op[ pRule->numops ].op = STUDIO_DOMINATE;
  1477. pRule->op[ pRule->numops ].d.index = nFactorCount;
  1478. pRule->numops++;
  1479. }
  1480. }
  1481. }
  1482. //-----------------------------------------------------------------------------
  1483. // Adds flex controller data to a particular source
  1484. //-----------------------------------------------------------------------------
  1485. void AddFlexControllers(
  1486. s_source_t *pSource )
  1487. {
  1488. CUtlVector< int > &r2s = pSource->m_rawIndexToRemapSourceIndex;
  1489. CUtlVector< int > &r2l = pSource->m_rawIndexToRemapLocalIndex;
  1490. CUtlVector< int > &l2i = pSource->m_leftRemapIndexToGlobalFlexControllIndex;
  1491. CUtlVector< int > &r2i = pSource->m_rightRemapIndexToGlobalFlexControllIndex;
  1492. // Number of Raw controls in this source
  1493. const int nRawControlCount = pSource->m_CombinationControls.Count();
  1494. // Initialize rawToRemapIndices
  1495. r2s.SetSize( nRawControlCount );
  1496. r2l.SetSize( nRawControlCount );
  1497. for ( int i = 0; i < nRawControlCount; ++i )
  1498. {
  1499. r2s[ i ] = -1;
  1500. r2l[ i ] = -1;
  1501. }
  1502. // Number of Remapped Controls in this source
  1503. const int nRemappedControlCount = pSource->m_FlexControllerRemaps.Count();
  1504. l2i.SetSize( nRemappedControlCount );
  1505. r2i.SetSize( nRemappedControlCount );
  1506. for ( int i = 0; i < nRemappedControlCount; ++i )
  1507. {
  1508. s_flexcontrollerremap_t &remapControl = pSource->m_FlexControllerRemaps[ i ];
  1509. // Number of Raw Controls In This Remapped Control
  1510. const int nRemappedRawControlCount = remapControl.m_RawControls.Count();
  1511. // Figure out the mapping from raw to remapped
  1512. for ( int j = 0; j < nRemappedRawControlCount; ++j )
  1513. {
  1514. for ( int k = 0; k < nRawControlCount; ++k )
  1515. {
  1516. if ( remapControl.m_RawControls[ j ] == pSource->m_CombinationControls[ k ].name )
  1517. {
  1518. Assert( r2s[ k ] == -1 );
  1519. Assert( r2l[ k ] == -1 );
  1520. r2s[ k ] = i; // The index of the remapped control
  1521. r2l[ k ] = j; // The index of which control this is in the remap
  1522. break;
  1523. }
  1524. }
  1525. }
  1526. if ( remapControl.m_bIsStereo )
  1527. {
  1528. // The controls have to be named 'right_' and 'left_' and right has to be first for
  1529. // hlfaceposer to recognize them
  1530. // See if we can add two more flex controllers
  1531. if ( ( g_numflexcontrollers + 1 ) >= MAXSTUDIOFLEXCTRL)
  1532. MdlError( "Line %d: Too many flex controllers, max %d, cannot add split control %s from source %s",
  1533. g_iLinecount, MAXSTUDIOFLEXCTRL, remapControl.m_Name.Get(), pSource->filename );
  1534. s_flexcontroller_t *pController;
  1535. int nLen = remapControl.m_Name.Length();
  1536. char *pTemp = (char*)_alloca( nLen + 7 ); // 'left_' && 'right_'
  1537. memcpy( pTemp + 6, remapControl.m_Name.Get(), nLen + 1 );
  1538. memcpy( pTemp, "right_", 6 );
  1539. pTemp[nLen + 6] = '\0';
  1540. remapControl.m_RightIndex = g_numflexcontrollers;
  1541. r2i[ i ] = g_numflexcontrollers;
  1542. pController = &g_flexcontroller[g_numflexcontrollers++];
  1543. Q_strncpy( pController->name, pTemp, sizeof( pController->name ) );
  1544. Q_strncpy( pController->type, pTemp, sizeof( pController->type ) );
  1545. if ( remapControl.m_RemapType == FLEXCONTROLLER_REMAP_2WAY || remapControl.m_RemapType == FLEXCONTROLLER_REMAP_EYELID )
  1546. {
  1547. pController->min = -1.0f;
  1548. pController->max = 1.0f;
  1549. }
  1550. else
  1551. {
  1552. pController->min = 0.0f;
  1553. pController->max = 1.0f;
  1554. }
  1555. memcpy( pTemp + 5, remapControl.m_Name.Get(), nLen + 1 );
  1556. memcpy( pTemp, "left_", 5 );
  1557. pTemp[nLen + 5] = '\0';
  1558. remapControl.m_LeftIndex = g_numflexcontrollers;
  1559. l2i[ i ] = g_numflexcontrollers;
  1560. pController = &g_flexcontroller[g_numflexcontrollers++];
  1561. Q_strncpy( pController->name, pTemp, sizeof( pController->name ) );
  1562. Q_strncpy( pController->type, pTemp, sizeof( pController->type ) );
  1563. if ( remapControl.m_RemapType == FLEXCONTROLLER_REMAP_2WAY || remapControl.m_RemapType == FLEXCONTROLLER_REMAP_EYELID )
  1564. {
  1565. pController->min = -1.0f;
  1566. pController->max = 1.0f;
  1567. }
  1568. else
  1569. {
  1570. pController->min = 0.0f;
  1571. pController->max = 1.0f;
  1572. }
  1573. }
  1574. else
  1575. {
  1576. // See if we can add one more flex controller
  1577. if ( g_numflexcontrollers >= MAXSTUDIOFLEXCTRL)
  1578. MdlError( "Line %d: Too many flex controllers, max %d, cannot add control %s from source %s",
  1579. g_iLinecount, MAXSTUDIOFLEXCTRL, remapControl.m_Name.Get(), pSource->filename );
  1580. remapControl.m_Index = g_numflexcontrollers;
  1581. r2i[ i ] = g_numflexcontrollers;
  1582. l2i[ i ] = g_numflexcontrollers;
  1583. s_flexcontroller_t *pController = &g_flexcontroller[g_numflexcontrollers++];
  1584. Q_strncpy( pController->name, remapControl.m_Name.Get(), sizeof( pController->name ) );
  1585. Q_strncpy( pController->type, remapControl.m_Name.Get(), sizeof( pController->type ) );
  1586. if ( remapControl.m_RemapType == FLEXCONTROLLER_REMAP_2WAY || remapControl.m_RemapType == FLEXCONTROLLER_REMAP_EYELID )
  1587. {
  1588. pController->min = -1.0f;
  1589. pController->max = 1.0f;
  1590. }
  1591. else
  1592. {
  1593. pController->min = 0.0f;
  1594. pController->max = 1.0f;
  1595. }
  1596. }
  1597. if ( remapControl.m_RemapType == FLEXCONTROLLER_REMAP_NWAY || remapControl.m_RemapType == FLEXCONTROLLER_REMAP_EYELID )
  1598. {
  1599. if ( g_numflexcontrollers >= MAXSTUDIOFLEXCTRL)
  1600. MdlError( "Line %d: Too many flex controllers, max %d, cannot add value control for nWay %s from source %s",
  1601. g_iLinecount, MAXSTUDIOFLEXCTRL, remapControl.m_Name.Get(), pSource->filename );
  1602. remapControl.m_MultiIndex = g_numflexcontrollers;
  1603. s_flexcontroller_t *pController = &g_flexcontroller[g_numflexcontrollers++];
  1604. const int nLen = remapControl.m_Name.Length();
  1605. char *pTemp = ( char * )_alloca( nLen + 6 + 1 ); // 'multi_' + 1 for the NULL
  1606. memcpy( pTemp, "multi_", 6 );
  1607. memcpy( pTemp + 6, remapControl.m_Name.Get(), nLen + 1 );
  1608. pTemp[nLen+6] = '\0';
  1609. Q_strncpy( pController->name, pTemp, sizeof( pController->name ) );
  1610. Q_strncpy( pController->type, pTemp, sizeof( pController->type ) );
  1611. pController->min = -1.0f;
  1612. pController->max = 1.0f;
  1613. }
  1614. if ( remapControl.m_RemapType == FLEXCONTROLLER_REMAP_EYELID )
  1615. {
  1616. // Make a blink controller
  1617. if ( g_numflexcontrollers >= MAXSTUDIOFLEXCTRL)
  1618. MdlError( "Line %d: Too many flex controllers, max %d, cannot add value control for nWay %s from source %s",
  1619. g_iLinecount, MAXSTUDIOFLEXCTRL, remapControl.m_Name.Get(), pSource->filename );
  1620. remapControl.m_BlinkController = g_numflexcontrollers;
  1621. s_flexcontroller_t *pController = &g_flexcontroller[g_numflexcontrollers++];
  1622. Q_strncpy( pController->name, "blink", sizeof( pController->name ) );
  1623. Q_strncpy( pController->type, "blink", sizeof( pController->type ) );
  1624. pController->min = 0.0f;
  1625. pController->max = 1.0f;
  1626. }
  1627. }
  1628. #ifdef _DEBUG
  1629. for ( int j = 0; j != nRawControlCount; ++j )
  1630. {
  1631. Assert( r2s[ j ] != -1 );
  1632. Assert( r2l[ j ] != -1 );
  1633. }
  1634. #endif // def _DEBUG
  1635. }
  1636. //-----------------------------------------------------------------------------
  1637. // Adds flex controller remappers
  1638. //-----------------------------------------------------------------------------
  1639. void AddBodyFlexRemaps( s_source_t *pSource )
  1640. {
  1641. int nCount = pSource->m_FlexControllerRemaps.Count();
  1642. for( int i = 0; i < nCount; ++i )
  1643. {
  1644. int k = g_FlexControllerRemap.AddToTail();
  1645. s_flexcontrollerremap_t &remap = g_FlexControllerRemap[k];
  1646. remap = pSource->m_FlexControllerRemaps[i];
  1647. }
  1648. }
  1649. //-----------------------------------------------------------------------------
  1650. //
  1651. //-----------------------------------------------------------------------------
  1652. void AddBodyFlexRules( s_source_t *pSource )
  1653. {
  1654. const int nRemapCount = pSource->m_FlexControllerRemaps.Count();
  1655. for ( int i = 0; i < nRemapCount; ++i )
  1656. {
  1657. s_flexcontrollerremap_t &remap = pSource->m_FlexControllerRemaps[ i ];
  1658. if ( remap.m_RemapType == FLEXCONTROLLER_REMAP_EYELID && !remap.m_EyesUpDownFlexName.IsEmpty() )
  1659. {
  1660. for ( int j = 0; j < g_numflexcontrollers; ++j )
  1661. {
  1662. if ( !Q_strcmp( g_flexcontroller[ j ].name, remap.m_EyesUpDownFlexName.Get() ) )
  1663. {
  1664. Assert( remap.m_EyesUpDownFlexController == -1 );
  1665. remap.m_EyesUpDownFlexController = j;
  1666. break;
  1667. }
  1668. }
  1669. }
  1670. }
  1671. const int nCount = pSource->m_CombinationRules.Count();
  1672. for ( int i = 0; i < nCount; ++i )
  1673. {
  1674. s_combinationrule_t &rule = pSource->m_CombinationRules[i];
  1675. s_flexkey_t &flexKey = g_flexkey[ pSource->m_nKeyStartIndex + rule.m_nFlex ];
  1676. AddBodyFlexRule( pSource, rule, flexKey.flexdesc,
  1677. pSource->m_rawIndexToRemapSourceIndex, pSource->m_rawIndexToRemapLocalIndex, pSource->m_leftRemapIndexToGlobalFlexControllIndex );
  1678. if ( flexKey.flexpair != 0 )
  1679. {
  1680. AddBodyFlexRule( pSource, rule, flexKey.flexpair,
  1681. pSource->m_rawIndexToRemapSourceIndex, pSource->m_rawIndexToRemapLocalIndex, pSource->m_rightRemapIndexToGlobalFlexControllIndex );
  1682. }
  1683. }
  1684. }
  1685. //-----------------------------------------------------------------------------
  1686. // Process a body command
  1687. //-----------------------------------------------------------------------------
  1688. void AddBodyFlexData( s_source_t *pSource, int imodel )
  1689. {
  1690. pSource->m_nKeyStartIndex = g_numflexkeys;
  1691. // Add flex keys
  1692. int nCount = pSource->m_FlexKeys.Count();
  1693. for ( int i = 0; i < nCount; ++i )
  1694. {
  1695. s_flexkey_t &key = pSource->m_FlexKeys[i];
  1696. if ( g_numflexkeys >= MAXSTUDIOFLEXKEYS )
  1697. MdlError( "Line %d: Too many flex keys, max %d, cannot add flexKey %s from source %s",
  1698. g_iLinecount, MAXSTUDIOFLEXKEYS, key.animationname, pSource->filename );
  1699. memcpy( &g_flexkey[g_numflexkeys], &key, sizeof(s_flexkey_t) );
  1700. g_flexkey[g_numflexkeys].imodel = imodel;
  1701. // flexpair was set up in AddFlexKey
  1702. if ( key.flexpair )
  1703. {
  1704. char mod[512];
  1705. Q_snprintf( mod, sizeof(mod), "%sL", key.animationname );
  1706. g_flexkey[g_numflexkeys].flexdesc = Add_Flexdesc( mod );
  1707. Q_snprintf( mod, sizeof(mod), "%sR", key.animationname );
  1708. g_flexkey[g_numflexkeys].flexpair = Add_Flexdesc( mod );
  1709. }
  1710. else
  1711. {
  1712. g_flexkey[g_numflexkeys].flexdesc = Add_Flexdesc( key.animationname );
  1713. g_flexkey[g_numflexkeys].flexpair = 0;
  1714. }
  1715. ++g_numflexkeys;
  1716. }
  1717. AddFlexControllers( pSource );
  1718. AddBodyFlexRemaps( pSource );
  1719. }
  1720. //-----------------------------------------------------------------------------
  1721. // Comparison operator for s_attachment_t
  1722. //-----------------------------------------------------------------------------
  1723. bool s_attachment_t::operator==( const s_attachment_t &rhs ) const
  1724. {
  1725. if ( Q_strcmp( name, rhs.name ) )
  1726. return false;
  1727. if ( Q_stricmp( bonename, rhs.bonename ) ||
  1728. bone != rhs.bone ||
  1729. type != rhs.type ||
  1730. flags != rhs.flags ||
  1731. Q_memcmp( local.Base(), rhs.local.Base(), sizeof( local ) ) )
  1732. {
  1733. RadianEuler iEuler, jEuler;
  1734. Vector iPos, jPos;
  1735. MatrixAngles( local, iEuler, iPos );
  1736. MatrixAngles( rhs.local, jEuler, jPos );
  1737. MdlWarning(
  1738. "Attachments with the same name but different parameters found\n"
  1739. " %s: ParentBone: %s Type: %d Flags: 0x%08x P: %6.2f %6.2f %6.2f R: %6.2f %6.2f %6.2f\n"
  1740. " %s: ParentBone: %s Type: %d Flags: 0x%08x P: %6.2f %6.2f %6.2f R: %6.2f %6.2f %6.2f\n",
  1741. name, bonename, type, flags,
  1742. iPos.x, iPos.y, iPos.z, RAD2DEG( iEuler.x ), RAD2DEG( iEuler.y ), RAD2DEG( iEuler.z ),
  1743. rhs.name, rhs.bonename, rhs.type, rhs.flags,
  1744. jPos.x, jPos.y, jPos.z, RAD2DEG( jEuler.x ), RAD2DEG( jEuler.y ), RAD2DEG( jEuler.z ) );
  1745. return false;
  1746. }
  1747. return true;
  1748. }
  1749. //-----------------------------------------------------------------------------
  1750. // Add attachments from the s_source_t that aren't already present in the
  1751. // global attachment list. At this point, the attachments aren't linked
  1752. // to the bone, but since that is done by string matching on the bone name
  1753. // the test for an attachment being a duplicate is still valid this early.
  1754. //-----------------------------------------------------------------------------
  1755. void AddBodyAttachments( s_source_t *pSource )
  1756. {
  1757. for ( int i = 0; i < pSource->m_Attachments.Count(); ++i )
  1758. {
  1759. const s_attachment_t &sourceAtt = pSource->m_Attachments[i];
  1760. bool bDuplicate = false;
  1761. for ( int j = 0; j < g_numattachments; ++j )
  1762. {
  1763. if ( sourceAtt == g_attachment[j] )
  1764. {
  1765. bDuplicate = true;
  1766. break;
  1767. }
  1768. }
  1769. if ( bDuplicate )
  1770. continue;
  1771. if ( g_numattachments >= ARRAYSIZE( g_attachment ) )
  1772. {
  1773. MdlWarning( "Too Many Attachments (Max %d), Ignoring Attachment %s:%s\n",
  1774. ARRAYSIZE( g_attachment ), pSource->filename, pSource->m_Attachments[i].name );
  1775. continue;;
  1776. }
  1777. memcpy( &g_attachment[g_numattachments], &( pSource->m_Attachments[i] ), sizeof( s_attachment_t ) );
  1778. ++g_numattachments;
  1779. }
  1780. }
  1781. //-----------------------------------------------------------------------------
  1782. // Process a body command
  1783. //-----------------------------------------------------------------------------
  1784. void ProcessCmdBody( const char *pFullPath, CDmeSourceSkin *pSkin )
  1785. {
  1786. if ( g_numbodyparts == 0 )
  1787. {
  1788. g_bodypart[g_numbodyparts].base = 1;
  1789. }
  1790. else
  1791. {
  1792. g_bodypart[g_numbodyparts].base = g_bodypart[g_numbodyparts-1].base * g_bodypart[g_numbodyparts-1].nummodels;
  1793. }
  1794. Q_strncpy( g_bodypart[g_numbodyparts].name, pSkin->m_SkinName.Get(), sizeof(g_bodypart[g_numbodyparts].name) );
  1795. g_model[g_nummodels] = (s_model_t *)kalloc( 1, sizeof( s_model_t ) );
  1796. g_bodypart[g_numbodyparts].pmodel[g_bodypart[g_numbodyparts].nummodels] = g_model[g_nummodels];
  1797. g_bodypart[g_numbodyparts].nummodels = 1;
  1798. ProcessOptionStudio( g_model[g_nummodels], pFullPath, pSkin );
  1799. // Body command should add any flex commands in the source loaded
  1800. if ( g_model[g_nummodels]->source )
  1801. {
  1802. AddBodyFlexData( g_model[g_nummodels]->source, g_nummodels );
  1803. AddBodyAttachments( g_model[g_nummodels]->source );
  1804. AddBodyFlexRules( g_model[ g_nummodels ]->source );
  1805. }
  1806. g_nummodels++;
  1807. g_numbodyparts++;
  1808. }
  1809. //-----------------------------------------------------------------------------
  1810. // Parse the body command from a .qc file
  1811. //-----------------------------------------------------------------------------
  1812. void Cmd_Body( )
  1813. {
  1814. if ( !GetToken(false) )
  1815. return;
  1816. CDmeSourceSkin *pSourceSkin = CreateElement< CDmeSourceSkin >( "" );
  1817. // Set defaults
  1818. pSourceSkin->m_flScale = g_defaultscale;
  1819. pSourceSkin->m_SkinName = token;
  1820. if ( ParseOptionStudio( pSourceSkin ) )
  1821. {
  1822. ProcessCmdBody( pSourceSkin->GetRelativeFileName(), pSourceSkin );
  1823. }
  1824. DestroyElement( pSourceSkin );
  1825. }
  1826. /*
  1827. ===============
  1828. ===============
  1829. */
  1830. void Grab_Animation( s_source_t *pSource, const char *pAnimName )
  1831. {
  1832. Vector pos;
  1833. RadianEuler rot;
  1834. char cmd[1024];
  1835. int index;
  1836. int t = -99999999;
  1837. int size;
  1838. s_sourceanim_t *pAnim = FindOrAddSourceAnim( pSource, pAnimName );
  1839. pAnim->startframe = -1;
  1840. size = pSource->numbones * sizeof( s_bone_t );
  1841. while ( GetLineInput() )
  1842. {
  1843. if ( sscanf( g_szLine, "%d %f %f %f %f %f %f", &index, &pos[0], &pos[1], &pos[2], &rot[0], &rot[1], &rot[2] ) == 7 )
  1844. {
  1845. if ( pAnim->startframe < 0 )
  1846. {
  1847. MdlError( "Missing frame start(%d) : %s", g_iLinecount, g_szLine );
  1848. }
  1849. scale_vertex( pos );
  1850. VectorCopy( pos, pAnim->rawanim[t][index].pos );
  1851. VectorCopy( rot, pAnim->rawanim[t][index].rot );
  1852. clip_rotations( rot ); // !!!
  1853. continue;
  1854. }
  1855. if ( sscanf( g_szLine, "%1023s %d", cmd, &index ) == 0 )
  1856. {
  1857. MdlError( "MdlError(%d) : %s", g_iLinecount, g_szLine );
  1858. continue;
  1859. }
  1860. if ( !Q_stricmp( cmd, "time" ) )
  1861. {
  1862. t = index;
  1863. if ( pAnim->startframe == -1 )
  1864. {
  1865. pAnim->startframe = t;
  1866. }
  1867. if ( t < pAnim->startframe )
  1868. {
  1869. MdlError( "Frame MdlError(%d) : %s", g_iLinecount, g_szLine );
  1870. }
  1871. if ( t > pAnim->endframe )
  1872. {
  1873. pAnim->endframe = t;
  1874. }
  1875. t -= pAnim->startframe;
  1876. if ( t >= pAnim->rawanim.Count())
  1877. {
  1878. s_bone_t *ptr = NULL;
  1879. pAnim->rawanim.AddMultipleToTail( t - pAnim->rawanim.Count() + 1, &ptr );
  1880. }
  1881. if ( pAnim->rawanim[t] != NULL )
  1882. {
  1883. continue;
  1884. }
  1885. pAnim->rawanim[t] = (s_bone_t *)kalloc( 1, size );
  1886. // duplicate previous frames keys
  1887. if ( t > 0 && pAnim->rawanim[t-1] )
  1888. {
  1889. for ( int j = 0; j < pSource->numbones; j++ )
  1890. {
  1891. VectorCopy( pAnim->rawanim[t-1][j].pos, pAnim->rawanim[t][j].pos );
  1892. VectorCopy( pAnim->rawanim[t-1][j].rot, pAnim->rawanim[t][j].rot );
  1893. }
  1894. }
  1895. continue;
  1896. }
  1897. if ( !Q_stricmp( cmd, "end" ) )
  1898. {
  1899. pAnim->numframes = pAnim->endframe - pAnim->startframe + 1;
  1900. for ( t = 0; t < pAnim->numframes; t++ )
  1901. {
  1902. if ( pAnim->rawanim[t] == NULL)
  1903. {
  1904. MdlError( "%s is missing frame %d\n", pSource->filename, t + pAnim->startframe );
  1905. }
  1906. }
  1907. Build_Reference( pSource, pAnimName );
  1908. return;
  1909. }
  1910. MdlError( "MdlError(%d) : %s", g_iLinecount, g_szLine );
  1911. }
  1912. MdlError( "unexpected EOF: %s\n", pSource->filename );
  1913. }
  1914. int Option_Activity( s_sequence_t *psequence )
  1915. {
  1916. qboolean found;
  1917. found = false;
  1918. GetToken(false);
  1919. V_strcpy_safe( psequence->activityname, token );
  1920. GetToken(false);
  1921. psequence->actweight = verify_atoi(token);
  1922. if ( psequence->actweight == 0 )
  1923. {
  1924. TokenError( "Activity %s has a zero weight (weights must be integers > 0)\n", psequence->activityname );
  1925. }
  1926. return 0;
  1927. }
  1928. int Option_ActivityModifier( s_sequence_t *psequence )
  1929. {
  1930. GetToken(false);
  1931. V_strcpy_safe( psequence->activitymodifier[ psequence->numactivitymodifiers++ ].name, token );
  1932. return 0;
  1933. }
  1934. /*
  1935. ===============
  1936. ===============
  1937. */
  1938. int Option_Event ( s_sequence_t *psequence )
  1939. {
  1940. if (psequence->numevents + 1 >= MAXSTUDIOEVENTS)
  1941. {
  1942. TokenError("too many events\n");
  1943. }
  1944. GetToken (false);
  1945. V_strcpy_safe( psequence->event[psequence->numevents].eventname, token );
  1946. GetToken( false );
  1947. psequence->event[psequence->numevents].frame = verify_atoi( token );
  1948. psequence->numevents++;
  1949. // option token
  1950. if (TokenAvailable())
  1951. {
  1952. GetToken( false );
  1953. if (token[0] == '}') // opps, hit the end
  1954. return 1;
  1955. // found an option
  1956. V_strcpy_safe( psequence->event[psequence->numevents-1].options, token );
  1957. }
  1958. return 0;
  1959. }
  1960. void Option_IKRule( s_ikrule_t *pRule )
  1961. {
  1962. // chain
  1963. GetToken( false );
  1964. int i;
  1965. for ( i = 0; i < g_numikchains; i++)
  1966. {
  1967. if (stricmp( token, g_ikchain[i].name ) == 0)
  1968. {
  1969. break;
  1970. }
  1971. }
  1972. if (i >= g_numikchains)
  1973. {
  1974. TokenError( "unknown chain \"%s\" in ikrule\n", token );
  1975. }
  1976. pRule->chain = i;
  1977. // default slot
  1978. pRule->slot = i;
  1979. // type
  1980. GetToken( false );
  1981. if (stricmp( token, "touch" ) == 0)
  1982. {
  1983. pRule->type = IK_SELF;
  1984. // bone
  1985. GetToken( false );
  1986. V_strcpy_safe( pRule->bonename, token );
  1987. }
  1988. else if (stricmp( token, "footstep" ) == 0)
  1989. {
  1990. pRule->type = IK_GROUND;
  1991. pRule->height = g_ikchain[pRule->chain].height;
  1992. pRule->floor = g_ikchain[pRule->chain].floor;
  1993. pRule->radius = g_ikchain[pRule->chain].radius;
  1994. }
  1995. else if (stricmp( token, "attachment" ) == 0)
  1996. {
  1997. pRule->type = IK_ATTACHMENT;
  1998. // name of attachment
  1999. GetToken( false );
  2000. V_strcpy_safe( pRule->attachment, token );
  2001. }
  2002. else if (stricmp( token, "release" ) == 0)
  2003. {
  2004. pRule->type = IK_RELEASE;
  2005. }
  2006. else if (stricmp( token, "unlatch" ) == 0)
  2007. {
  2008. pRule->type = IK_UNLATCH;
  2009. }
  2010. pRule->contact = -1;
  2011. while (TokenAvailable())
  2012. {
  2013. GetToken( false );
  2014. if (stricmp( token, "height" ) == 0)
  2015. {
  2016. GetToken( false );
  2017. pRule->height = verify_atof( token );
  2018. }
  2019. else if (stricmp( token, "target" ) == 0)
  2020. {
  2021. // slot
  2022. GetToken( false );
  2023. pRule->slot = verify_atoi( token );
  2024. }
  2025. else if (stricmp( token, "range" ) == 0)
  2026. {
  2027. // ramp
  2028. GetToken( false );
  2029. if (token[0] == '.')
  2030. pRule->start = -1;
  2031. else
  2032. pRule->start = verify_atoi( token );
  2033. GetToken( false );
  2034. if (token[0] == '.')
  2035. pRule->peak = -1;
  2036. else
  2037. pRule->peak = verify_atoi( token );
  2038. GetToken( false );
  2039. if (token[0] == '.')
  2040. pRule->tail = -1;
  2041. else
  2042. pRule->tail = verify_atoi( token );
  2043. GetToken( false );
  2044. if (token[0] == '.')
  2045. pRule->end = -1;
  2046. else
  2047. pRule->end = verify_atoi( token );
  2048. }
  2049. else if (stricmp( token, "floor" ) == 0)
  2050. {
  2051. GetToken( false );
  2052. pRule->floor = verify_atof( token );
  2053. }
  2054. else if (stricmp( token, "pad" ) == 0)
  2055. {
  2056. GetToken( false );
  2057. pRule->radius = verify_atof( token ) / 2.0f;
  2058. }
  2059. else if (stricmp( token, "radius" ) == 0)
  2060. {
  2061. GetToken( false );
  2062. pRule->radius = verify_atof( token );
  2063. }
  2064. else if (stricmp( token, "contact" ) == 0)
  2065. {
  2066. GetToken( false );
  2067. pRule->contact = verify_atoi( token );
  2068. }
  2069. else if (stricmp( token, "usesequence" ) == 0)
  2070. {
  2071. pRule->usesequence = true;
  2072. pRule->usesource = false;
  2073. }
  2074. else if (stricmp( token, "usesource" ) == 0)
  2075. {
  2076. pRule->usesequence = false;
  2077. pRule->usesource = true;
  2078. }
  2079. else if (stricmp( token, "fakeorigin" ) == 0)
  2080. {
  2081. GetToken( false );
  2082. pRule->pos.x = verify_atof( token );
  2083. GetToken( false );
  2084. pRule->pos.y = verify_atof( token );
  2085. GetToken( false );
  2086. pRule->pos.z = verify_atof( token );
  2087. pRule->bone = -1;
  2088. }
  2089. else if (stricmp( token, "fakerotate" ) == 0)
  2090. {
  2091. QAngle ang;
  2092. GetToken( false );
  2093. ang.x = verify_atof( token );
  2094. GetToken( false );
  2095. ang.y = verify_atof( token );
  2096. GetToken( false );
  2097. ang.z = verify_atof( token );
  2098. AngleQuaternion( ang, pRule->q );
  2099. pRule->bone = -1;
  2100. }
  2101. else if (stricmp( token, "bone" ) == 0)
  2102. {
  2103. V_strcpy_safe( pRule->bonename, token );
  2104. }
  2105. else
  2106. {
  2107. UnGetToken();
  2108. return;
  2109. }
  2110. }
  2111. }
  2112. /*
  2113. =================
  2114. Cmd_Origin
  2115. =================
  2116. */
  2117. void Cmd_Origin (void)
  2118. {
  2119. GetToken (false);
  2120. g_defaultadjust.x = verify_atof (token);
  2121. GetToken (false);
  2122. g_defaultadjust.y = verify_atof (token);
  2123. GetToken (false);
  2124. g_defaultadjust.z = verify_atof (token);
  2125. if (TokenAvailable())
  2126. {
  2127. GetToken (false);
  2128. g_defaultrotation.z = DEG2RAD( verify_atof( token ) + 90);
  2129. }
  2130. }
  2131. //-----------------------------------------------------------------------------
  2132. // Purpose: Set the default root rotation so that the Y axis is up instead of the Z axis (for Maya)
  2133. //-----------------------------------------------------------------------------
  2134. void ProcessUpAxis( const RadianEuler &angles )
  2135. {
  2136. g_defaultrotation = angles;
  2137. }
  2138. //-----------------------------------------------------------------------------
  2139. // Purpose: Set the default root rotation so that the Y axis is up instead of the Z axis (for Maya)
  2140. //-----------------------------------------------------------------------------
  2141. void Cmd_UpAxis( void )
  2142. {
  2143. // We want to create a rotation that rotates from the art space
  2144. // (specified by the up direction) to a z up space
  2145. // Note: x, -x, -y are untested
  2146. RadianEuler angles( 0.0f, 0.0f, M_PI / 2.0f );
  2147. GetToken (false);
  2148. if (!Q_stricmp( token, "x" ))
  2149. {
  2150. // rotate 90 degrees around y to move x into z
  2151. angles.x = 0.0f;
  2152. angles.y = M_PI / 2.0f;
  2153. }
  2154. else if (!Q_stricmp( token, "-x" ))
  2155. {
  2156. // untested
  2157. angles.x = 0.0f;
  2158. angles.y = -M_PI / 2.0f;
  2159. }
  2160. else if (!Q_stricmp( token, "y" ))
  2161. {
  2162. // rotate 90 degrees around x to move y into z
  2163. angles.x = M_PI / 2.0f;
  2164. angles.y = 0.0f;
  2165. }
  2166. else if (!Q_stricmp( token, "-y" ))
  2167. {
  2168. // untested
  2169. angles.x = -M_PI / 2.0f;
  2170. angles.y = 0.0f;
  2171. }
  2172. else if (!Q_stricmp( token, "z" ))
  2173. {
  2174. // there's still a built in 90 degree Z rotation :(
  2175. angles.x = 0.0f;
  2176. angles.y = 0.0f;
  2177. }
  2178. else if (!Q_stricmp( token, "-z" ))
  2179. {
  2180. // there's still a built in 90 degree Z rotation :(
  2181. angles.x = 0.0f;
  2182. angles.y = 0.0f;
  2183. }
  2184. else
  2185. {
  2186. TokenError( "unknown $upaxis option: \"%s\"\n", token );
  2187. return;
  2188. }
  2189. ProcessUpAxis( angles );
  2190. }
  2191. /*
  2192. =================
  2193. =================
  2194. */
  2195. void Cmd_ScaleUp (void)
  2196. {
  2197. GetToken (false);
  2198. g_defaultscale = verify_atof (token);
  2199. g_currentscale = g_defaultscale;
  2200. }
  2201. //-----------------------------------------------------------------------------
  2202. // Purpose: Sets how what size chunks to cut the animations into
  2203. //-----------------------------------------------------------------------------
  2204. void Cmd_AnimBlockSize( void )
  2205. {
  2206. GetToken( false );
  2207. g_animblocksize = verify_atoi( token );
  2208. if (g_animblocksize < 1024)
  2209. {
  2210. g_animblocksize *= 1024;
  2211. }
  2212. while (TokenAvailable())
  2213. {
  2214. GetToken( false );
  2215. if (!Q_stricmp( token, "nostall" ))
  2216. {
  2217. g_bNoAnimblockStall = true;
  2218. }
  2219. }
  2220. }
  2221. //-----------------------------------------------------------------------------
  2222. //
  2223. //-----------------------------------------------------------------------------
  2224. static void FlipFacing( s_source_t *pSrc )
  2225. {
  2226. unsigned short tmp;
  2227. int i, j;
  2228. for( i = 0; i < pSrc->nummeshes; i++ )
  2229. {
  2230. s_mesh_t *pMesh = &pSrc->mesh[i];
  2231. for( j = 0; j < pMesh->numfaces; j++ )
  2232. {
  2233. s_face_t &f = pSrc->face[pMesh->faceoffset + j];
  2234. tmp = f.b; f.b = f.c; f.c = tmp;
  2235. }
  2236. }
  2237. }
  2238. // Processes source comment line and extracts information about the data file
  2239. void ProcessSourceComment( s_source_t *psource, const char *pCommentString )
  2240. {
  2241. if ( char const *szSceneComment = StringAfterPrefix( pCommentString, "// SCENE=" ) )
  2242. {
  2243. char szScene[1024];
  2244. Q_strncpy( szScene, szSceneComment, ARRAYSIZE( szScene ) );
  2245. Q_FixSlashes( szScene );
  2246. ProcessOriginalContentFile( psource->filename, szScene );
  2247. }
  2248. }
  2249. // Processes original content file "szOriginalContentFile" that was used to generate
  2250. // data file "szDataFile"
  2251. void ProcessOriginalContentFile( char const *szDataFile, char const *szOriginalContentFile )
  2252. {
  2253. // Early out: if no p4
  2254. if ( g_bNoP4 )
  2255. return;
  2256. char const *szContentDirRootEnd = strstr( szDataFile, "\\content\\" );
  2257. char const *szSceneName = strstr( szOriginalContentFile, "\\content\\" );
  2258. if ( szContentDirRootEnd && szSceneName )
  2259. {
  2260. char chScenePath[ MAX_PATH ] = {0};
  2261. Q_snprintf( chScenePath, sizeof( chScenePath ) - 1, "%.*s%s",
  2262. szContentDirRootEnd - szDataFile, szDataFile, szSceneName );
  2263. EnsureDependencyFileCheckedIn( chScenePath );
  2264. }
  2265. else if ( szContentDirRootEnd && !szSceneName )
  2266. {
  2267. // Assume relative path
  2268. char chScenePath[ MAX_PATH ] = {0};
  2269. Q_snprintf( chScenePath, sizeof( chScenePath ) - 1, "%.*s%s",
  2270. max( strrchr( szDataFile, '\\' ), strrchr( szDataFile, '/' ) ) + 1 - szDataFile,
  2271. szDataFile, szOriginalContentFile );
  2272. EnsureDependencyFileCheckedIn( chScenePath );
  2273. }
  2274. else
  2275. {
  2276. MdlWarning( "ProcessOriginalContentFile for '%s' cannot detect scene source file from '%s'!\n", szDataFile, szOriginalContentFile );
  2277. }
  2278. }
  2279. //-----------------------------------------------------------------------------
  2280. // Checks to see if the model source was already loaded
  2281. //-----------------------------------------------------------------------------
  2282. static s_source_t *FindCachedSource( const char* name, const char* xext )
  2283. {
  2284. int i;
  2285. if( xext[0] )
  2286. {
  2287. // we know what extension is necessary. . look for it.
  2288. Q_snprintf( g_szFilename, sizeof(g_szFilename), "%s%s.%s", cddir[numdirs], name, xext );
  2289. for (i = 0; i < g_numsources; i++)
  2290. {
  2291. if ( !Q_stricmp( g_szFilename, g_source[i]->filename ) )
  2292. return g_source[i];
  2293. }
  2294. }
  2295. else
  2296. {
  2297. // we don't know what extension to use, so look for all of 'em.
  2298. Q_snprintf( g_szFilename, sizeof(g_szFilename), "%s%s.vrm", cddir[numdirs], name );
  2299. for (i = 0; i < g_numsources; i++)
  2300. {
  2301. if ( !Q_stricmp( g_szFilename, g_source[i]->filename ) )
  2302. return g_source[i];
  2303. }
  2304. Q_snprintf (g_szFilename, sizeof(g_szFilename), "%s%s.smd", cddir[numdirs], name );
  2305. for (i = 0; i < g_numsources; i++)
  2306. {
  2307. if ( !Q_stricmp( g_szFilename, g_source[i]->filename ) )
  2308. return g_source[i];
  2309. }
  2310. Q_snprintf (g_szFilename, sizeof(g_szFilename), "%s%s.dmx", cddir[numdirs], name );
  2311. for (i = 0; i < g_numsources; i++)
  2312. {
  2313. if ( !Q_stricmp( g_szFilename, g_source[i]->filename ) )
  2314. return g_source[i];
  2315. }
  2316. Q_snprintf (g_szFilename, sizeof(g_szFilename), "%s%s.xml", cddir[numdirs], name );
  2317. for (i = 0; i < g_numsources; i++)
  2318. {
  2319. if ( !Q_stricmp( g_szFilename, g_source[i]->filename ) )
  2320. return g_source[i];
  2321. }
  2322. Q_snprintf (g_szFilename, sizeof(g_szFilename), "%s%s.obj", cddir[numdirs], name );
  2323. for (i = 0; i < g_numsources; i++)
  2324. {
  2325. if ( !Q_stricmp( g_szFilename, g_source[i]->filename ) )
  2326. return g_source[i];
  2327. }
  2328. /*
  2329. sprintf (g_szFilename, "%s%s.vta", cddir[numdirs], name );
  2330. for (i = 0; i < g_numsources; i++)
  2331. {
  2332. if (stricmp( g_szFilename, g_source[i]->filename ) == 0)
  2333. return g_source[i];
  2334. }
  2335. */
  2336. }
  2337. // Not found
  2338. return 0;
  2339. }
  2340. //-----------------------------------------------------------------------------
  2341. // Loads an animation/model source
  2342. //-----------------------------------------------------------------------------
  2343. s_source_t *Load_Source( const char *name, const char *ext, bool reverse, bool isActiveModel )
  2344. {
  2345. if ( g_numsources >= MAXSTUDIOSEQUENCES )
  2346. TokenError( "Load_Source( %s ) - overflowed g_numsources.", name );
  2347. Assert(name);
  2348. int namelen = strlen(name) + 1;
  2349. char* pTempName = (char*)_alloca( namelen );
  2350. char xext[32];
  2351. int result = false;
  2352. V_strncpy( pTempName, name, namelen );
  2353. Q_ExtractFileExtension( pTempName, xext, sizeof( xext ) );
  2354. if (xext[0] == '\0')
  2355. {
  2356. V_strcpy_safe( xext, ext );
  2357. }
  2358. else
  2359. {
  2360. Q_StripExtension( pTempName, pTempName, namelen );
  2361. }
  2362. s_source_t* pSource = FindCachedSource( pTempName, xext );
  2363. if (pSource)
  2364. {
  2365. if (isActiveModel)
  2366. pSource->isActiveModel = true;
  2367. return pSource;
  2368. }
  2369. g_source[g_numsources] = (s_source_t *)kalloc( 1, sizeof( s_source_t ) );
  2370. V_strcpy_safe( g_source[g_numsources]->filename, g_szFilename );
  2371. if (isActiveModel)
  2372. {
  2373. g_source[g_numsources]->isActiveModel = true;
  2374. }
  2375. char const * load_extensions[] = { "vrm", "smd", "sma", "phys", "vta", "obj", "dmx", "xml" };
  2376. int ( *load_procs[] )( s_source_t * ) = { Load_VRM, Load_SMD, Load_SMD, Load_SMD, Load_VTA, Load_OBJ, Load_DMX, Load_DMX };
  2377. Assert( ARRAYSIZE(load_extensions) == ARRAYSIZE(load_procs) );
  2378. for ( int kk = 0; kk < ARRAYSIZE( load_extensions ); ++ kk )
  2379. {
  2380. if ( ( !result && xext[0] == '\0' ) || Q_stricmp( xext, load_extensions[kk] ) == 0)
  2381. {
  2382. Q_snprintf( g_szFilename, sizeof(g_szFilename), "%s%s.%s", cddir[numdirs], pTempName, load_extensions[kk] );
  2383. V_strcpy_safe( g_source[g_numsources]->filename, g_szFilename );
  2384. result = (load_procs[kk])( g_source[g_numsources] );
  2385. if ( result )
  2386. EnsureDependencyFileCheckedIn( g_source[g_numsources]->filename );
  2387. }
  2388. }
  2389. if (!g_bCreateMakefile && !result)
  2390. {
  2391. if (xext[0] == '\0')
  2392. TokenError( "could not load file '%s%s'\n", cddir[numdirs], pTempName );
  2393. else
  2394. TokenError( "could not load file '%s%s.%s'\n", cddir[numdirs], pTempName, xext );
  2395. }
  2396. if ( g_source[g_numsources]->numbones == 0 )
  2397. {
  2398. TokenError( "missing all bones in file '%s'\n", g_source[g_numsources]->filename );
  2399. }
  2400. // copy over default settings of when the model was loaded (since there's no actual animation for some of the systems)
  2401. VectorCopy( g_defaultadjust, g_source[g_numsources]->adjust );
  2402. g_source[g_numsources]->scale = 1.0f;
  2403. g_source[g_numsources]->rotation = g_defaultrotation;
  2404. g_numsources++;
  2405. if( reverse )
  2406. {
  2407. FlipFacing( g_source[g_numsources-1] );
  2408. }
  2409. return g_source[g_numsources-1];
  2410. }
  2411. s_sequence_t *LookupSequence( const char *name )
  2412. {
  2413. int i;
  2414. for ( i = 0; i < g_sequence.Count(); ++i )
  2415. {
  2416. if ( !Q_stricmp( g_sequence[i].name, name ) )
  2417. return &g_sequence[i];
  2418. }
  2419. return NULL;
  2420. }
  2421. s_animation_t *LookupAnimation( const char *name )
  2422. {
  2423. int i;
  2424. for ( i = 0; i < g_numani; i++)
  2425. {
  2426. if ( !Q_stricmp( g_panimation[i]->name, name ) )
  2427. return g_panimation[i];
  2428. }
  2429. s_sequence_t *pseq = LookupSequence( name );
  2430. return pseq ? pseq->panim[0][0] : NULL;
  2431. }
  2432. //-----------------------------------------------------------------------------
  2433. // Purpose: parse order dependant s_animcmd_t token for $animations
  2434. //-----------------------------------------------------------------------------
  2435. int ParseCmdlistToken( int &numcmds, s_animcmd_t *cmds )
  2436. {
  2437. if (numcmds >= MAXSTUDIOCMDS)
  2438. {
  2439. return false;
  2440. }
  2441. s_animcmd_t *pcmd = &cmds[numcmds];
  2442. if (stricmp("fixuploop", token ) == 0)
  2443. {
  2444. pcmd->cmd = CMD_FIXUP;
  2445. GetToken( false );
  2446. pcmd->u.fixuploop.start = verify_atoi( token );
  2447. GetToken( false );
  2448. pcmd->u.fixuploop.end = verify_atoi( token );
  2449. }
  2450. else if (strnicmp("weightlist", token, 6 ) == 0)
  2451. {
  2452. GetToken( false );
  2453. int i;
  2454. for ( i = 1; i < g_numweightlist; i++)
  2455. {
  2456. if (stricmp( g_weightlist[i].name, token ) == 0)
  2457. {
  2458. break;
  2459. }
  2460. }
  2461. if (i == g_numweightlist)
  2462. {
  2463. TokenError( "unknown weightlist '%s\'\n", token );
  2464. }
  2465. pcmd->cmd = CMD_WEIGHTS;
  2466. pcmd->u.weightlist.index = i;
  2467. }
  2468. else if (stricmp("subtract", token ) == 0)
  2469. {
  2470. pcmd->cmd = CMD_SUBTRACT;
  2471. GetToken( false );
  2472. s_animation_t *extanim = LookupAnimation( token );
  2473. if (extanim == NULL)
  2474. {
  2475. TokenError( "unknown subtract animation '%s\'\n", token );
  2476. }
  2477. pcmd->u.subtract.ref = extanim;
  2478. GetToken( false );
  2479. pcmd->u.subtract.frame = verify_atoi( token );
  2480. pcmd->u.subtract.flags |= STUDIO_POST;
  2481. }
  2482. else if (stricmp("presubtract", token ) == 0) // FIXME: rename this to something better
  2483. {
  2484. pcmd->cmd = CMD_SUBTRACT;
  2485. GetToken( false );
  2486. s_animation_t *extanim = LookupAnimation( token );
  2487. if (extanim == NULL)
  2488. {
  2489. TokenError( "unknown presubtract animation '%s\'\n", token );
  2490. }
  2491. pcmd->u.subtract.ref = extanim;
  2492. GetToken( false );
  2493. pcmd->u.subtract.frame = verify_atoi( token );
  2494. }
  2495. else if (stricmp( "alignto", token ) == 0)
  2496. {
  2497. pcmd->cmd = CMD_AO;
  2498. pcmd->u.ao.pBonename = NULL;
  2499. GetToken( false );
  2500. s_animation_t *extanim = LookupAnimation( token );
  2501. if (extanim == NULL)
  2502. {
  2503. TokenError( "unknown alignto animation '%s\'\n", token );
  2504. }
  2505. pcmd->u.ao.ref = extanim;
  2506. pcmd->u.ao.motiontype = STUDIO_X | STUDIO_Y;
  2507. pcmd->u.ao.srcframe = 0;
  2508. pcmd->u.ao.destframe = 0;
  2509. }
  2510. else if (stricmp( "align", token ) == 0)
  2511. {
  2512. pcmd->cmd = CMD_AO;
  2513. pcmd->u.ao.pBonename = NULL;
  2514. GetToken( false );
  2515. s_animation_t *extanim = LookupAnimation( token );
  2516. if (extanim == NULL)
  2517. {
  2518. TokenError( "unknown align animation '%s\'\n", token );
  2519. }
  2520. pcmd->u.ao.ref = extanim;
  2521. // motion type to match
  2522. pcmd->u.ao.motiontype = 0;
  2523. GetToken( false );
  2524. int ctrl;
  2525. while ((ctrl = lookupControl( token )) != -1)
  2526. {
  2527. pcmd->u.ao.motiontype |= ctrl;
  2528. GetToken( false );
  2529. }
  2530. if (pcmd->u.ao.motiontype == 0)
  2531. {
  2532. TokenError( "missing controls on align\n" );
  2533. }
  2534. // frame of reference animation to match
  2535. pcmd->u.ao.srcframe = verify_atoi( token );
  2536. // against what frame of the current animation
  2537. GetToken( false );
  2538. pcmd->u.ao.destframe = verify_atoi( token );
  2539. }
  2540. else if (stricmp( "alignboneto", token ) == 0)
  2541. {
  2542. pcmd->cmd = CMD_AO;
  2543. GetToken( false );
  2544. pcmd->u.ao.pBonename = strdup( token );
  2545. GetToken( false );
  2546. s_animation_t *extanim = LookupAnimation( token );
  2547. if (extanim == NULL)
  2548. {
  2549. TokenError( "unknown alignboneto animation '%s\'\n", token );
  2550. }
  2551. pcmd->u.ao.ref = extanim;
  2552. pcmd->u.ao.motiontype = STUDIO_X | STUDIO_Y;
  2553. pcmd->u.ao.srcframe = 0;
  2554. pcmd->u.ao.destframe = 0;
  2555. }
  2556. else if (stricmp( "alignbone", token ) == 0)
  2557. {
  2558. pcmd->cmd = CMD_AO;
  2559. GetToken( false );
  2560. pcmd->u.ao.pBonename = strdup( token );
  2561. GetToken( false );
  2562. s_animation_t *extanim = LookupAnimation( token );
  2563. if (extanim == NULL)
  2564. {
  2565. TokenError( "unknown alignboneto animation '%s\'\n", token );
  2566. }
  2567. pcmd->u.ao.ref = extanim;
  2568. // motion type to match
  2569. pcmd->u.ao.motiontype = 0;
  2570. GetToken( false );
  2571. int ctrl;
  2572. while ((ctrl = lookupControl( token )) != -1)
  2573. {
  2574. pcmd->u.ao.motiontype |= ctrl;
  2575. GetToken( false );
  2576. }
  2577. if (pcmd->u.ao.motiontype == 0)
  2578. {
  2579. TokenError( "missing controls on align\n" );
  2580. }
  2581. // frame of reference animation to match
  2582. pcmd->u.ao.srcframe = verify_atoi( token );
  2583. // against what frame of the current animation
  2584. GetToken( false );
  2585. pcmd->u.ao.destframe = verify_atoi( token );
  2586. }
  2587. else if (stricmp( "match", token ) == 0)
  2588. {
  2589. pcmd->cmd = CMD_MATCH;
  2590. GetToken( false );
  2591. s_animation_t *extanim = LookupAnimation( token );
  2592. if (extanim == NULL)
  2593. {
  2594. TokenError( "unknown match animation '%s\'\n", token );
  2595. }
  2596. pcmd->u.match.ref = extanim;
  2597. }
  2598. else if (stricmp( "matchblend", token ) == 0)
  2599. {
  2600. pcmd->cmd = CMD_MATCHBLEND;
  2601. GetToken( false );
  2602. s_animation_t *extanim = LookupAnimation( token );
  2603. if (extanim == NULL)
  2604. {
  2605. MdlError( "unknown match animation '%s\'\n", token );
  2606. }
  2607. pcmd->u.match.ref = extanim;
  2608. // frame of reference animation to match
  2609. GetToken( false );
  2610. pcmd->u.match.srcframe = verify_atoi( token );
  2611. // against what frame of the current animation
  2612. GetToken( false );
  2613. pcmd->u.match.destframe = verify_atoi( token );
  2614. // backup and starting match in here
  2615. GetToken( false );
  2616. pcmd->u.match.destpre = verify_atoi( token );
  2617. // continue blending match till here
  2618. GetToken( false );
  2619. pcmd->u.match.destpost = verify_atoi( token );
  2620. }
  2621. else if (stricmp( "worldspaceblend", token ) == 0)
  2622. {
  2623. pcmd->cmd = CMD_WORLDSPACEBLEND;
  2624. GetToken( false );
  2625. s_animation_t *extanim = LookupAnimation( token );
  2626. if (extanim == NULL)
  2627. {
  2628. TokenError( "unknown worldspaceblend animation '%s\'\n", token );
  2629. }
  2630. pcmd->u.world.ref = extanim;
  2631. pcmd->u.world.startframe = 0;
  2632. pcmd->u.world.loops = false;
  2633. }
  2634. else if (stricmp( "worldspaceblendloop", token ) == 0)
  2635. {
  2636. pcmd->cmd = CMD_WORLDSPACEBLEND;
  2637. GetToken( false );
  2638. s_animation_t *extanim = LookupAnimation( token );
  2639. if (extanim == NULL)
  2640. {
  2641. TokenError( "unknown worldspaceblend animation '%s\'\n", token );
  2642. }
  2643. pcmd->u.world.ref = extanim;
  2644. GetToken( false );
  2645. pcmd->u.world.startframe = atoi( token );
  2646. pcmd->u.world.loops = true;
  2647. }
  2648. else if (stricmp( "rotateto", token ) == 0)
  2649. {
  2650. pcmd->cmd = CMD_ANGLE;
  2651. GetToken( false );
  2652. pcmd->u.angle.angle = verify_atof( token );
  2653. }
  2654. else if (stricmp( "ikrule", token ) == 0)
  2655. {
  2656. pcmd->cmd = CMD_IKRULE;
  2657. pcmd->u.ikrule.pRule = (s_ikrule_t *)kalloc( 1, sizeof( s_ikrule_t ) );
  2658. Option_IKRule( pcmd->u.ikrule.pRule );
  2659. }
  2660. else if (stricmp( "ikfixup", token ) == 0)
  2661. {
  2662. pcmd->cmd = CMD_IKFIXUP;
  2663. pcmd->u.ikfixup.pRule = (s_ikrule_t *)kalloc( 1, sizeof( s_ikrule_t ) );
  2664. Option_IKRule( pcmd->u.ikrule.pRule );
  2665. }
  2666. else if (stricmp( "walkframe", token ) == 0)
  2667. {
  2668. pcmd->cmd = CMD_MOTION;
  2669. // frame
  2670. GetToken( false );
  2671. pcmd->u.motion.iEndFrame = verify_atoi( token );
  2672. // motion type to match
  2673. pcmd->u.motion.motiontype = 0;
  2674. while (TokenAvailable())
  2675. {
  2676. GetToken( false );
  2677. int ctrl = lookupControl( token );
  2678. if (ctrl != -1)
  2679. {
  2680. pcmd->u.motion.motiontype |= ctrl;
  2681. }
  2682. else
  2683. {
  2684. UnGetToken();
  2685. break;
  2686. }
  2687. }
  2688. /*
  2689. GetToken( false ); // X
  2690. pcmd->u.motion.x = verify_atof( token );
  2691. GetToken( false ); // Y
  2692. pcmd->u.motion.y = verify_atof( token );
  2693. GetToken( false ); // A
  2694. pcmd->u.motion.zr = verify_atof( token );
  2695. */
  2696. }
  2697. else if (stricmp( "walkalignto", token ) == 0)
  2698. {
  2699. pcmd->cmd = CMD_REFMOTION;
  2700. GetToken( false );
  2701. pcmd->u.motion.iEndFrame = verify_atoi( token );
  2702. pcmd->u.motion.iSrcFrame = pcmd->u.motion.iEndFrame;
  2703. GetToken( false ); // reference animation
  2704. s_animation_t *extanim = LookupAnimation( token );
  2705. if (extanim == NULL)
  2706. {
  2707. TokenError( "unknown alignto animation '%s\'\n", token );
  2708. }
  2709. pcmd->u.motion.pRefAnim = extanim;
  2710. pcmd->u.motion.iRefFrame = 0;
  2711. // motion type to match
  2712. pcmd->u.motion.motiontype = 0;
  2713. while (TokenAvailable())
  2714. {
  2715. GetToken( false );
  2716. int ctrl = lookupControl( token );
  2717. if (ctrl != -1)
  2718. {
  2719. pcmd->u.motion.motiontype |= ctrl;
  2720. }
  2721. else
  2722. {
  2723. UnGetToken();
  2724. break;
  2725. }
  2726. }
  2727. /*
  2728. GetToken( false ); // X
  2729. pcmd->u.motion.x = verify_atof( token );
  2730. GetToken( false ); // Y
  2731. pcmd->u.motion.y = verify_atof( token );
  2732. GetToken( false ); // A
  2733. pcmd->u.motion.zr = verify_atof( token );
  2734. */
  2735. }
  2736. else if (stricmp( "walkalign", token ) == 0)
  2737. {
  2738. pcmd->cmd = CMD_REFMOTION;
  2739. // end frame to apply motion over
  2740. GetToken( false );
  2741. pcmd->u.motion.iEndFrame = verify_atoi( token );
  2742. // reference animation
  2743. GetToken( false );
  2744. s_animation_t *extanim = LookupAnimation( token );
  2745. if (extanim == NULL)
  2746. {
  2747. TokenError( "unknown alignto animation '%s\'\n", token );
  2748. }
  2749. pcmd->u.motion.pRefAnim = extanim;
  2750. // motion type to match
  2751. pcmd->u.motion.motiontype = 0;
  2752. while (TokenAvailable())
  2753. {
  2754. GetToken( false );
  2755. int ctrl = lookupControl( token );
  2756. if (ctrl != -1)
  2757. {
  2758. pcmd->u.motion.motiontype |= ctrl;
  2759. }
  2760. else
  2761. {
  2762. break;
  2763. }
  2764. }
  2765. if (pcmd->u.motion.motiontype == 0)
  2766. {
  2767. TokenError( "missing controls on walkalign\n" );
  2768. }
  2769. // frame of reference animation to match
  2770. pcmd->u.motion.iRefFrame = verify_atoi( token );
  2771. // against what frame of the current animation
  2772. GetToken( false );
  2773. pcmd->u.motion.iSrcFrame = verify_atoi( token );
  2774. }
  2775. else if (stricmp("derivative", token ) == 0)
  2776. {
  2777. pcmd->cmd = CMD_DERIVATIVE;
  2778. // get scale
  2779. GetToken( false );
  2780. pcmd->u.derivative.scale = verify_atof( token );
  2781. }
  2782. else if (stricmp("noanimation", token ) == 0)
  2783. {
  2784. pcmd->cmd = CMD_NOANIMATION;
  2785. }
  2786. else if (stricmp("lineardelta", token ) == 0)
  2787. {
  2788. pcmd->cmd = CMD_LINEARDELTA;
  2789. pcmd->u.linear.flags |= STUDIO_AL_POST;
  2790. }
  2791. else if (stricmp("splinedelta", token ) == 0)
  2792. {
  2793. pcmd->cmd = CMD_LINEARDELTA;
  2794. pcmd->u.linear.flags |= STUDIO_AL_POST;
  2795. pcmd->u.linear.flags |= STUDIO_AL_SPLINE;
  2796. }
  2797. else if (stricmp("compress", token ) == 0)
  2798. {
  2799. pcmd->cmd = CMD_COMPRESS;
  2800. // get frames to skip
  2801. GetToken( false );
  2802. pcmd->u.compress.frames = verify_atoi( token );
  2803. }
  2804. else if (stricmp("numframes", token ) == 0)
  2805. {
  2806. pcmd->cmd = CMD_NUMFRAMES;
  2807. // get frames to force
  2808. GetToken( false );
  2809. pcmd->u.compress.frames = verify_atoi( token );
  2810. }
  2811. else if (stricmp("counterrotate", token ) == 0)
  2812. {
  2813. pcmd->cmd = CMD_COUNTERROTATE;
  2814. // get bone name
  2815. GetToken( false );
  2816. pcmd->u.counterrotate.pBonename = strdup( token );
  2817. }
  2818. else if (stricmp("counterrotateto", token ) == 0)
  2819. {
  2820. pcmd->cmd = CMD_COUNTERROTATE;
  2821. pcmd->u.counterrotate.bHasTarget = true;
  2822. // get pitch
  2823. GetToken( false );
  2824. pcmd->u.counterrotate.targetAngle[0] = verify_atof( token );
  2825. // get yaw
  2826. GetToken( false );
  2827. pcmd->u.counterrotate.targetAngle[1] = verify_atof( token );
  2828. // get roll
  2829. GetToken( false );
  2830. pcmd->u.counterrotate.targetAngle[2] = verify_atof( token );
  2831. // get bone name
  2832. GetToken( false );
  2833. pcmd->u.counterrotate.pBonename = strdup( token );
  2834. }
  2835. else if (stricmp("localhierarchy", token ) == 0)
  2836. {
  2837. pcmd->cmd = CMD_LOCALHIERARCHY;
  2838. // get bone name
  2839. GetToken( false );
  2840. pcmd->u.localhierarchy.pBonename = strdup( token );
  2841. // get parent name
  2842. GetToken( false );
  2843. pcmd->u.localhierarchy.pParentname = strdup( token );
  2844. pcmd->u.localhierarchy.start = -1;
  2845. pcmd->u.localhierarchy.peak = -1;
  2846. pcmd->u.localhierarchy.tail = -1;
  2847. pcmd->u.localhierarchy.end = -1;
  2848. if (TokenAvailable())
  2849. {
  2850. GetToken( false );
  2851. if (stricmp( token, "range" ) == 0)
  2852. {
  2853. //
  2854. GetToken( false );
  2855. pcmd->u.localhierarchy.start = verify_atof_with_null( token );
  2856. //
  2857. GetToken( false );
  2858. pcmd->u.localhierarchy.peak = verify_atof_with_null( token );
  2859. //
  2860. GetToken( false );
  2861. pcmd->u.localhierarchy.tail = verify_atof_with_null( token );
  2862. //
  2863. GetToken( false );
  2864. pcmd->u.localhierarchy.end = verify_atof_with_null( token );
  2865. }
  2866. else
  2867. {
  2868. UnGetToken();
  2869. }
  2870. }
  2871. }
  2872. else
  2873. {
  2874. return false;
  2875. }
  2876. numcmds++;
  2877. return true;
  2878. }
  2879. //-----------------------------------------------------------------------------
  2880. // Purpose: parse order independant s_animation_t token for $animations
  2881. //-----------------------------------------------------------------------------
  2882. bool ParseAnimationToken( s_animation_t *panim )
  2883. {
  2884. if ( !Q_stricmp( "if", token ) )
  2885. {
  2886. // fixme: add expression evaluation
  2887. GetToken( false );
  2888. if (atoi( token ) == 0 && stricmp( token, "true" ) != 0)
  2889. {
  2890. GetToken(true);
  2891. if (token[0] == '{')
  2892. {
  2893. int depth = 1;
  2894. while (TokenAvailable() && depth > 0)
  2895. {
  2896. GetToken( true );
  2897. if (stricmp("{", token ) == 0)
  2898. {
  2899. depth++;
  2900. }
  2901. else if (stricmp("}", token ) == 0)
  2902. {
  2903. depth--;
  2904. }
  2905. }
  2906. }
  2907. }
  2908. return true;
  2909. }
  2910. if ( !Q_stricmp( "fps", token ) )
  2911. {
  2912. GetToken( false );
  2913. panim->fps = verify_atof( token );
  2914. if ( panim->fps <= 0.0f )
  2915. {
  2916. TokenError( "ParseAnimationToken: fps (%f from '%s') <= 0.0\n", panim->fps, token );
  2917. }
  2918. return true;
  2919. }
  2920. if ( !Q_stricmp( "origin", token ) )
  2921. {
  2922. GetToken (false);
  2923. panim->adjust.x = verify_atof (token);
  2924. GetToken (false);
  2925. panim->adjust.y = verify_atof (token);
  2926. GetToken (false);
  2927. panim->adjust.z = verify_atof (token);
  2928. return true;
  2929. }
  2930. if ( !Q_stricmp( "rotate", token ) )
  2931. {
  2932. GetToken( false );
  2933. // FIXME: broken for Maya
  2934. panim->rotation.z = DEG2RAD( verify_atof( token ) + 90 );
  2935. return true;
  2936. }
  2937. if ( !Q_stricmp( "angles", token ) )
  2938. {
  2939. GetToken( false );
  2940. panim->rotation.x = DEG2RAD( verify_atof( token ) );
  2941. GetToken( false );
  2942. panim->rotation.y = DEG2RAD( verify_atof( token ) );
  2943. GetToken( false );
  2944. panim->rotation.z = DEG2RAD( verify_atof( token ) + 90.0f);
  2945. return true;
  2946. }
  2947. if ( !Q_stricmp( "scale", token ) )
  2948. {
  2949. GetToken( false );
  2950. panim->scale = verify_atof( token );
  2951. return true;
  2952. }
  2953. if ( !Q_strnicmp( "loop", token, 4 ) )
  2954. {
  2955. panim->flags |= STUDIO_LOOPING;
  2956. return true;
  2957. }
  2958. if ( !Q_strnicmp( "startloop", token, 5 ) )
  2959. {
  2960. GetToken( false );
  2961. panim->looprestart = verify_atoi( token );
  2962. panim->flags |= STUDIO_LOOPING;
  2963. return true;
  2964. }
  2965. if ( !Q_stricmp( "fudgeloop", token ) )
  2966. {
  2967. panim->fudgeloop = true;
  2968. panim->flags |= STUDIO_LOOPING;
  2969. return true;
  2970. }
  2971. if ( !Q_strnicmp( "snap", token, 4 ) )
  2972. {
  2973. panim->flags |= STUDIO_SNAP;
  2974. return true;
  2975. }
  2976. if ( !Q_strnicmp( "frame", token, 5 ) )
  2977. {
  2978. GetToken( false );
  2979. panim->startframe = verify_atoi( token );
  2980. GetToken( false );
  2981. panim->endframe = verify_atoi( token );
  2982. // NOTE: This always affects the first source anim read in
  2983. s_sourceanim_t *pSourceAnim = FindSourceAnim( panim->source, panim->animationname );
  2984. if ( pSourceAnim )
  2985. {
  2986. if ( panim->startframe < pSourceAnim->startframe )
  2987. {
  2988. panim->startframe = pSourceAnim->startframe;
  2989. }
  2990. if ( panim->endframe > pSourceAnim->endframe )
  2991. {
  2992. panim->endframe = pSourceAnim->endframe;
  2993. }
  2994. }
  2995. if ( !g_bCreateMakefile && panim->endframe < panim->startframe )
  2996. {
  2997. TokenError( "end frame before start frame in %s", panim->name );
  2998. }
  2999. panim->numframes = panim->endframe - panim->startframe + 1;
  3000. return true;
  3001. }
  3002. if ( !Q_stricmp( "blockname", token ) )
  3003. {
  3004. GetToken( false );
  3005. s_sourceanim_t *pSourceAnim = FindSourceAnim( panim->source, token );
  3006. // NOTE: This always affects the first source anim read in
  3007. if ( pSourceAnim )
  3008. {
  3009. panim->startframe = pSourceAnim->startframe;
  3010. panim->endframe = pSourceAnim->endframe;
  3011. if ( !g_bCreateMakefile && panim->endframe < panim->startframe )
  3012. {
  3013. TokenError( "end frame before start frame in %s", panim->name );
  3014. }
  3015. panim->numframes = panim->endframe - panim->startframe + 1;
  3016. Q_strncpy( panim->animationname, token, sizeof(panim->animationname) );
  3017. }
  3018. else
  3019. {
  3020. MdlError( "Requested unknown animation block name %s\n", token );
  3021. }
  3022. return true;
  3023. }
  3024. if ( !Q_stricmp( "post", token ) )
  3025. {
  3026. panim->flags |= STUDIO_POST;
  3027. return true;
  3028. }
  3029. if ( !Q_stricmp( "noautoik", token ) )
  3030. {
  3031. panim->noAutoIK = true;
  3032. return true;
  3033. }
  3034. if ( !Q_stricmp( "autoik", token ) )
  3035. {
  3036. panim->noAutoIK = false;
  3037. return true;
  3038. }
  3039. if ( ParseCmdlistToken( panim->numcmds, panim->cmds ) )
  3040. return true;
  3041. if ( !Q_stricmp( "cmdlist", token ) )
  3042. {
  3043. GetToken( false ); // A
  3044. int i;
  3045. for ( i = 0; i < g_numcmdlists; i++)
  3046. {
  3047. if (stricmp( g_cmdlist[i].name, token) == 0)
  3048. {
  3049. break;
  3050. }
  3051. }
  3052. if (i == g_numcmdlists)
  3053. TokenError( "unknown cmdlist %s\n", token );
  3054. for (int j = 0; j < g_cmdlist[i].numcmds; j++)
  3055. {
  3056. if (panim->numcmds >= MAXSTUDIOCMDS)
  3057. {
  3058. TokenError("Too many cmds in %s\n", panim->name );
  3059. }
  3060. panim->cmds[panim->numcmds++] = g_cmdlist[i].cmds[j];
  3061. }
  3062. return true;
  3063. }
  3064. if ( !Q_stricmp( "motionrollback", token ) )
  3065. {
  3066. GetToken( false );
  3067. panim->motionrollback = atof( token );
  3068. return true;
  3069. }
  3070. if ( !Q_stricmp( "noanimblock", token ) )
  3071. {
  3072. panim->disableAnimblocks = true;
  3073. return true;
  3074. }
  3075. if ( !Q_stricmp( "noanimblockstall", token ) )
  3076. {
  3077. panim->isFirstSectionLocal = true;
  3078. return true;
  3079. }
  3080. if ( lookupControl( token ) != -1 )
  3081. {
  3082. panim->motiontype |= lookupControl( token );
  3083. return true;
  3084. }
  3085. return false;
  3086. }
  3087. //-----------------------------------------------------------------------------
  3088. // Purpose: create named order dependant s_animcmd_t blocks, used as replicated token list for $animations
  3089. //-----------------------------------------------------------------------------
  3090. void Cmd_Cmdlist( )
  3091. {
  3092. int depth = 0;
  3093. // name
  3094. GetToken(false);
  3095. V_strcpy_safe( g_cmdlist[g_numcmdlists].name, token );
  3096. while (1)
  3097. {
  3098. if (depth > 0)
  3099. {
  3100. if(!GetToken(true))
  3101. {
  3102. break;
  3103. }
  3104. }
  3105. else
  3106. {
  3107. if (!TokenAvailable())
  3108. {
  3109. break;
  3110. }
  3111. else
  3112. {
  3113. GetToken (false);
  3114. }
  3115. }
  3116. if (endofscript)
  3117. {
  3118. if (depth != 0)
  3119. {
  3120. TokenError("missing }\n" );
  3121. }
  3122. return;
  3123. }
  3124. if (stricmp("{", token ) == 0)
  3125. {
  3126. depth++;
  3127. }
  3128. else if (stricmp("}", token ) == 0)
  3129. {
  3130. depth--;
  3131. }
  3132. else if (ParseCmdlistToken( g_cmdlist[g_numcmdlists].numcmds, g_cmdlist[g_numcmdlists].cmds ))
  3133. {
  3134. }
  3135. else
  3136. {
  3137. TokenError( "unknown command: %s\n", token );
  3138. }
  3139. if (depth < 0)
  3140. {
  3141. TokenError("missing {\n");
  3142. }
  3143. };
  3144. g_numcmdlists++;
  3145. }
  3146. int ParseAnimation( s_animation_t *panim, bool isAppend );
  3147. int ParseEmpty( void );
  3148. //-----------------------------------------------------------------------------
  3149. // Purpose: allocate an entry for $animation
  3150. //-----------------------------------------------------------------------------
  3151. void Cmd_Animation( )
  3152. {
  3153. // name
  3154. GetToken(false);
  3155. s_animation_t *panim = LookupAnimation( token );
  3156. if (panim != NULL)
  3157. {
  3158. if (!panim->isOverride)
  3159. {
  3160. TokenError( "Duplicate animation name \"%s\"\n", token );
  3161. }
  3162. else
  3163. {
  3164. panim->doesOverride = true;
  3165. ParseEmpty();
  3166. return;
  3167. }
  3168. }
  3169. // allocate animation entry
  3170. g_panimation[g_numani] = (s_animation_t *)kalloc( 1, sizeof( s_animation_t ) );
  3171. g_panimation[g_numani]->index = g_numani;
  3172. panim = g_panimation[g_numani];
  3173. V_strcpy_safe( panim->name, token );
  3174. g_numani++;
  3175. // filename
  3176. GetToken(false);
  3177. V_strcpy_safe( panim->filename, token );
  3178. panim->source = Load_Source( panim->filename, "" );
  3179. if ( panim->source->m_Animations.Count() )
  3180. {
  3181. s_sourceanim_t *pSourceAnim = &panim->source->m_Animations[0];
  3182. panim->startframe = pSourceAnim->startframe;
  3183. panim->endframe = pSourceAnim->endframe;
  3184. Q_strncpy( panim->animationname, pSourceAnim->animationname, sizeof(panim->animationname) );
  3185. }
  3186. else
  3187. {
  3188. panim->startframe = 0;
  3189. panim->endframe = 0;
  3190. Q_strncpy( panim->animationname, "", sizeof(panim->animationname) );
  3191. }
  3192. VectorCopy( g_defaultadjust, panim->adjust );
  3193. panim->rotation = g_defaultrotation;
  3194. panim->scale = 1.0f;
  3195. panim->fps = 30.0;
  3196. panim->motionrollback = g_flDefaultMotionRollback;
  3197. ParseAnimation( panim, false );
  3198. panim->numframes = panim->endframe - panim->startframe + 1;
  3199. //CheckAutoShareAnimationGroup( panim->name );
  3200. }
  3201. //-----------------------------------------------------------------------------
  3202. // Purpose: wrapper for parsing $animation tokens
  3203. //-----------------------------------------------------------------------------
  3204. int ParseAnimation( s_animation_t *panim, bool isAppend )
  3205. {
  3206. int depth = 0;
  3207. while (1)
  3208. {
  3209. if (depth > 0)
  3210. {
  3211. if(!GetToken(true))
  3212. {
  3213. break;
  3214. }
  3215. }
  3216. else
  3217. {
  3218. if (!TokenAvailable())
  3219. {
  3220. break;
  3221. }
  3222. else
  3223. {
  3224. GetToken (false);
  3225. }
  3226. }
  3227. if (endofscript)
  3228. {
  3229. if (depth != 0)
  3230. {
  3231. TokenError("missing }\n" );
  3232. }
  3233. return 1;
  3234. }
  3235. if (stricmp("{", token ) == 0)
  3236. {
  3237. depth++;
  3238. }
  3239. else if (stricmp("}", token ) == 0)
  3240. {
  3241. depth--;
  3242. }
  3243. else if (ParseAnimationToken( panim ))
  3244. {
  3245. }
  3246. else
  3247. {
  3248. TokenError( "Unknown animation option\'%s\'\n", token );
  3249. }
  3250. if (depth < 0)
  3251. {
  3252. TokenError("missing {\n");
  3253. }
  3254. };
  3255. return 0;
  3256. }
  3257. //-----------------------------------------------------------------------------
  3258. // Purpose: create a virtual $animation command from a $sequence reference
  3259. //-----------------------------------------------------------------------------
  3260. s_animation_t *Cmd_ImpliedAnimation( s_sequence_t *psequence, const char *filename )
  3261. {
  3262. // allocate animation entry
  3263. g_panimation[g_numani] = (s_animation_t *)kalloc( 1, sizeof( s_animation_t ) );
  3264. g_panimation[g_numani]->index = g_numani;
  3265. s_animation_t *panim = g_panimation[g_numani];
  3266. g_numani++;
  3267. panim->isImplied = true;
  3268. panim->startframe = 0;
  3269. panim->endframe = MAXSTUDIOANIMFRAMES - 1;
  3270. V_strcpy_safe( panim->name, "@" );
  3271. V_strcat_safe( panim->name, psequence->name );
  3272. V_strcpy_safe( panim->filename, filename );
  3273. VectorCopy( g_defaultadjust, panim->adjust );
  3274. panim->scale = 1.0f;
  3275. panim->rotation = g_defaultrotation;
  3276. panim->fps = 30;
  3277. panim->motionrollback = g_flDefaultMotionRollback;
  3278. //panim->source = Load_Source( panim->filename, "smd" );
  3279. panim->source = Load_Source( panim->filename, "" );
  3280. if ( panim->source->m_Animations.Count() )
  3281. {
  3282. s_sourceanim_t *pSourceAnim = &panim->source->m_Animations[0];
  3283. Q_strncpy( panim->animationname, panim->source->m_Animations[0].animationname, sizeof(panim->animationname) );
  3284. if ( panim->startframe < pSourceAnim->startframe )
  3285. {
  3286. panim->startframe = pSourceAnim->startframe;
  3287. }
  3288. if ( panim->endframe > pSourceAnim->endframe )
  3289. {
  3290. panim->endframe = pSourceAnim->endframe;
  3291. }
  3292. }
  3293. else
  3294. {
  3295. Q_strncpy( panim->animationname, "", sizeof( panim->animationname ) );
  3296. }
  3297. if ( !g_bCreateMakefile && panim->endframe < panim->startframe )
  3298. {
  3299. TokenError( "end frame before start frame in %s", panim->name );
  3300. }
  3301. panim->numframes = panim->endframe - panim->startframe + 1;
  3302. //CheckAutoShareAnimationGroup( panim->name );
  3303. return panim;
  3304. }
  3305. //-----------------------------------------------------------------------------
  3306. // Purpose: copy globally reavent $animation options from one $animation to another
  3307. //-----------------------------------------------------------------------------
  3308. void CopyAnimationSettings( s_animation_t *pdest, s_animation_t *psrc )
  3309. {
  3310. pdest->fps = psrc->fps;
  3311. VectorCopy( psrc->adjust, pdest->adjust );
  3312. pdest->scale = psrc->scale;
  3313. pdest->rotation = psrc->rotation;
  3314. pdest->motiontype = psrc->motiontype;
  3315. //Adrian - Hey! Revisit me later.
  3316. /*if (pdest->startframe < psrc->startframe)
  3317. pdest->startframe = psrc->startframe;
  3318. if (pdest->endframe > psrc->endframe)
  3319. pdest->endframe = psrc->endframe;
  3320. if (pdest->endframe < pdest->startframe)
  3321. TokenError( "fixedup end frame before start frame in %s", pdest->name );
  3322. pdest->numframes = pdest->endframe - pdest->startframe + 1;*/
  3323. for (int i = 0; i < psrc->numcmds; i++)
  3324. {
  3325. if (pdest->numcmds >= MAXSTUDIOCMDS)
  3326. {
  3327. TokenError("Too many cmds in %s\n", pdest->name );
  3328. }
  3329. pdest->cmds[pdest->numcmds++] = psrc->cmds[i];
  3330. }
  3331. }
  3332. int ParseSequence( s_sequence_t *pseq, bool isAppend );
  3333. //-----------------------------------------------------------------------------
  3334. // Purpose: allocate an entry for $sequence
  3335. //-----------------------------------------------------------------------------
  3336. s_sequence_t *ProcessCmdSequence( const char *pSequenceName )
  3337. {
  3338. s_animation_t *panim = LookupAnimation( pSequenceName );
  3339. // allocate sequence
  3340. if ( panim != NULL )
  3341. {
  3342. if ( !panim->isOverride )
  3343. {
  3344. TokenError( "Duplicate sequence name \"%s\"\n", pSequenceName );
  3345. }
  3346. else
  3347. {
  3348. panim->doesOverride = true;
  3349. return NULL;
  3350. }
  3351. }
  3352. if ( g_sequence.Count() >= MAXSTUDIOSEQUENCES )
  3353. {
  3354. TokenError("Too many sequences (%d max)\n", MAXSTUDIOSEQUENCES );
  3355. }
  3356. s_sequence_t *pseq = &g_sequence[ g_sequence.AddToTail() ];
  3357. memset( pseq, 0, sizeof( s_sequence_t ) );
  3358. // initialize sequence
  3359. Q_strncpy( pseq->name, pSequenceName, sizeof(pseq->name) );
  3360. pseq->actweight = 0;
  3361. pseq->activityname[0] = '\0';
  3362. pseq->activity = -1; // -1 is the default for 'no activity'
  3363. pseq->paramindex[0] = -1;
  3364. pseq->paramindex[1] = -1;
  3365. pseq->groupsize[0] = 0;
  3366. pseq->groupsize[1] = 0;
  3367. pseq->fadeintime = 0.2;
  3368. pseq->fadeouttime = 0.2;
  3369. return pseq;
  3370. }
  3371. //-----------------------------------------------------------------------------
  3372. // Process the sequence command
  3373. //-----------------------------------------------------------------------------
  3374. void Cmd_Sequence( )
  3375. {
  3376. if ( !GetToken(false) )
  3377. return;
  3378. // Find existing sequences
  3379. const char *pSequenceName = token;
  3380. s_animation_t *panim = LookupAnimation( pSequenceName );
  3381. if ( panim != NULL && panim->isOverride )
  3382. {
  3383. ParseEmpty( );
  3384. }
  3385. s_sequence_t *pseq = ProcessCmdSequence( pSequenceName );
  3386. if ( pseq )
  3387. {
  3388. ParseSequence( pseq, false );
  3389. }
  3390. }
  3391. //-----------------------------------------------------------------------------
  3392. // Performs processing on a sequence
  3393. //-----------------------------------------------------------------------------
  3394. void ProcessSequence( s_sequence_t *pseq, int numblends, s_animation_t **animations, bool isAppend )
  3395. {
  3396. if (isAppend)
  3397. return;
  3398. if ( numblends == 0 )
  3399. {
  3400. TokenError("no animations found\n");
  3401. }
  3402. if ( pseq->groupsize[0] == 0 )
  3403. {
  3404. if (numblends < 4)
  3405. {
  3406. pseq->groupsize[0] = numblends;
  3407. pseq->groupsize[1] = 1;
  3408. }
  3409. else
  3410. {
  3411. int i = sqrt( (float) numblends );
  3412. if (i * i == numblends)
  3413. {
  3414. pseq->groupsize[0] = i;
  3415. pseq->groupsize[1] = i;
  3416. }
  3417. else
  3418. {
  3419. TokenError( "non-square (%d) number of blends without \"blendwidth\" set\n", numblends );
  3420. }
  3421. }
  3422. }
  3423. else
  3424. {
  3425. pseq->groupsize[1] = numblends / pseq->groupsize[0];
  3426. if (pseq->groupsize[0] * pseq->groupsize[1] != numblends)
  3427. {
  3428. TokenError( "missing animation blends. Expected %d, found %d\n",
  3429. pseq->groupsize[0] * pseq->groupsize[1], numblends );
  3430. }
  3431. }
  3432. for (int i = 0; i < numblends; i++)
  3433. {
  3434. int j = i % pseq->groupsize[0];
  3435. int k = i / pseq->groupsize[0];
  3436. pseq->panim[j][k] = animations[i];
  3437. if (i > 0 && animations[i]->isImplied)
  3438. {
  3439. CopyAnimationSettings( animations[i], animations[0] );
  3440. }
  3441. animations[i]->isImplied = false; // don't copy any more commands
  3442. pseq->flags |= animations[i]->flags;
  3443. }
  3444. pseq->numblends = numblends;
  3445. }
  3446. //-----------------------------------------------------------------------------
  3447. // Purpose: parse options unique to $sequence
  3448. //-----------------------------------------------------------------------------
  3449. int ParseSequence( s_sequence_t *pseq, bool isAppend )
  3450. {
  3451. int depth = 0;
  3452. s_animation_t *animations[64];
  3453. int i, j, n;
  3454. int numblends = 0;
  3455. if (isAppend)
  3456. {
  3457. animations[0] = pseq->panim[0][0];
  3458. }
  3459. while (1)
  3460. {
  3461. if (depth > 0)
  3462. {
  3463. if(!GetToken(true))
  3464. {
  3465. break;
  3466. }
  3467. }
  3468. else
  3469. {
  3470. if (!TokenAvailable())
  3471. {
  3472. break;
  3473. }
  3474. else
  3475. {
  3476. GetToken (false);
  3477. }
  3478. }
  3479. if (endofscript)
  3480. {
  3481. if (depth != 0)
  3482. {
  3483. TokenError("missing }\n" );
  3484. }
  3485. return 1;
  3486. }
  3487. if (stricmp("{", token ) == 0)
  3488. {
  3489. depth++;
  3490. }
  3491. else if (stricmp("}", token ) == 0)
  3492. {
  3493. depth--;
  3494. }
  3495. /*
  3496. else if (stricmp("deform", token ) == 0)
  3497. {
  3498. Option_Deform( pseq );
  3499. }
  3500. */
  3501. else if (stricmp("event", token ) == 0)
  3502. {
  3503. depth -= Option_Event( pseq );
  3504. }
  3505. else if (stricmp("activity", token ) == 0)
  3506. {
  3507. Option_Activity( pseq );
  3508. }
  3509. else if (stricmp("activitymodifier", token ) == 0)
  3510. {
  3511. Option_ActivityModifier( pseq );
  3512. }
  3513. else if (strnicmp( token, "ACT_", 4 ) == 0)
  3514. {
  3515. UnGetToken( );
  3516. Option_Activity( pseq );
  3517. }
  3518. else if (stricmp("snap", token ) == 0)
  3519. {
  3520. pseq->flags |= STUDIO_SNAP;
  3521. }
  3522. else if (stricmp("blendwidth", token ) == 0)
  3523. {
  3524. GetToken( false );
  3525. pseq->groupsize[0] = verify_atoi( token );
  3526. }
  3527. else if (stricmp("blend", token ) == 0)
  3528. {
  3529. i = 0;
  3530. if (pseq->paramindex[0] != -1)
  3531. {
  3532. i = 1;
  3533. }
  3534. GetToken( false );
  3535. j = LookupPoseParameter( token );
  3536. pseq->paramindex[i] = j;
  3537. pseq->paramattachment[i] = -1;
  3538. GetToken( false );
  3539. pseq->paramstart[i] = verify_atof( token );
  3540. GetToken( false );
  3541. pseq->paramend[i] = verify_atof( token );
  3542. g_pose[j].min = min( g_pose[j].min, pseq->paramstart[i] );
  3543. g_pose[j].min = min( g_pose[j].min, pseq->paramend[i] );
  3544. g_pose[j].max = max( g_pose[j].max, pseq->paramstart[i] );
  3545. g_pose[j].max = max( g_pose[j].max, pseq->paramend[i] );
  3546. }
  3547. else if (stricmp("calcblend", token ) == 0)
  3548. {
  3549. i = 0;
  3550. if (pseq->paramindex[0] != -1)
  3551. {
  3552. i = 1;
  3553. }
  3554. GetToken( false );
  3555. j = LookupPoseParameter( token );
  3556. pseq->paramindex[i] = j;
  3557. GetToken( false );
  3558. pseq->paramattachment[i] = LookupAttachment( token );
  3559. if (pseq->paramattachment[i] == -1)
  3560. {
  3561. TokenError( "Unknown calcblend attachment \"%s\"\n", token );
  3562. }
  3563. GetToken( false );
  3564. pseq->paramcontrol[i] = lookupControl( token );
  3565. }
  3566. else if (stricmp("blendref", token ) == 0)
  3567. {
  3568. GetToken( false );
  3569. pseq->paramanim = LookupAnimation( token );
  3570. if (pseq->paramanim == NULL)
  3571. {
  3572. TokenError( "Unknown blendref animation \"%s\"\n", token );
  3573. }
  3574. }
  3575. else if (stricmp("blendcomp", token ) == 0)
  3576. {
  3577. GetToken( false );
  3578. pseq->paramcompanim = LookupAnimation( token );
  3579. if (pseq->paramcompanim == NULL)
  3580. {
  3581. TokenError( "Unknown blendcomp animation \"%s\"\n", token );
  3582. }
  3583. }
  3584. else if (stricmp("blendcenter", token ) == 0)
  3585. {
  3586. GetToken( false );
  3587. pseq->paramcenter = LookupAnimation( token );
  3588. if (pseq->paramcenter == NULL)
  3589. {
  3590. TokenError( "Unknown blendcenter animation \"%s\"\n", token );
  3591. }
  3592. }
  3593. else if (stricmp("node", token ) == 0)
  3594. {
  3595. GetToken( false );
  3596. pseq->entrynode = pseq->exitnode = LookupXNode( token );
  3597. }
  3598. else if (stricmp("transition", token ) == 0)
  3599. {
  3600. GetToken( false );
  3601. pseq->entrynode = LookupXNode( token );
  3602. GetToken( false );
  3603. pseq->exitnode = LookupXNode( token );
  3604. }
  3605. else if (stricmp("rtransition", token ) == 0)
  3606. {
  3607. GetToken( false );
  3608. pseq->entrynode = LookupXNode( token );
  3609. GetToken( false );
  3610. pseq->exitnode = LookupXNode( token );
  3611. pseq->nodeflags |= 1;
  3612. }
  3613. else if (stricmp("exitphase", token ) == 0)
  3614. {
  3615. GetToken( false );
  3616. pseq->exitphase = verify_atof( token );
  3617. }
  3618. else if (stricmp("delta", token) == 0)
  3619. {
  3620. pseq->flags |= STUDIO_DELTA;
  3621. pseq->flags |= STUDIO_POST;
  3622. }
  3623. else if (stricmp("worldspace", token) == 0)
  3624. {
  3625. pseq->flags |= STUDIO_WORLD;
  3626. pseq->flags |= STUDIO_POST;
  3627. }
  3628. else if (stricmp("post", token) == 0) // remove
  3629. {
  3630. pseq->flags |= STUDIO_POST;
  3631. }
  3632. else if (stricmp("predelta", token) == 0)
  3633. {
  3634. pseq->flags |= STUDIO_DELTA;
  3635. }
  3636. else if (stricmp("autoplay", token) == 0)
  3637. {
  3638. pseq->flags |= STUDIO_AUTOPLAY;
  3639. }
  3640. else if (stricmp( "fadein", token ) == 0)
  3641. {
  3642. GetToken( false );
  3643. pseq->fadeintime = verify_atof( token );
  3644. }
  3645. else if (stricmp( "fadeout", token ) == 0)
  3646. {
  3647. GetToken( false );
  3648. pseq->fadeouttime = verify_atof( token );
  3649. }
  3650. else if (stricmp( "realtime", token ) == 0)
  3651. {
  3652. pseq->flags |= STUDIO_REALTIME;
  3653. }
  3654. else if (stricmp( "posecycle", token ) == 0)
  3655. {
  3656. pseq->flags |= STUDIO_CYCLEPOSE;
  3657. GetToken( false );
  3658. pseq->cycleposeindex = LookupPoseParameter( token );
  3659. }
  3660. else if (stricmp( "hidden", token ) == 0)
  3661. {
  3662. pseq->flags |= STUDIO_HIDDEN;
  3663. }
  3664. else if (stricmp( "addlayer", token ) == 0)
  3665. {
  3666. GetToken( false );
  3667. V_strcpy_safe( pseq->autolayer[pseq->numautolayers].name, token );
  3668. pseq->numautolayers++;
  3669. }
  3670. else if (stricmp( "iklock", token ) == 0)
  3671. {
  3672. GetToken(false);
  3673. V_strcpy_safe( pseq->iklock[pseq->numiklocks].name, token );
  3674. GetToken(false);
  3675. pseq->iklock[pseq->numiklocks].flPosWeight = verify_atof( token );
  3676. GetToken(false);
  3677. pseq->iklock[pseq->numiklocks].flLocalQWeight = verify_atof( token );
  3678. pseq->numiklocks++;
  3679. }
  3680. else if (stricmp( "keyvalues", token ) == 0)
  3681. {
  3682. Option_KeyValues( &pseq->KeyValue );
  3683. }
  3684. else if (stricmp( "blendlayer", token ) == 0)
  3685. {
  3686. pseq->autolayer[pseq->numautolayers].flags = 0;
  3687. GetToken( false );
  3688. V_strcpy_safe( pseq->autolayer[pseq->numautolayers].name, token );
  3689. GetToken( false );
  3690. pseq->autolayer[pseq->numautolayers].start = verify_atof( token );
  3691. GetToken( false );
  3692. pseq->autolayer[pseq->numautolayers].peak = verify_atof( token );
  3693. GetToken( false );
  3694. pseq->autolayer[pseq->numautolayers].tail = verify_atof( token );
  3695. GetToken( false );
  3696. pseq->autolayer[pseq->numautolayers].end = verify_atof( token );
  3697. while (TokenAvailable( ))
  3698. {
  3699. GetToken( false );
  3700. if (stricmp( "xfade", token ) == 0)
  3701. {
  3702. pseq->autolayer[pseq->numautolayers].flags |= STUDIO_AL_XFADE;
  3703. }
  3704. else if (stricmp( "spline", token ) == 0)
  3705. {
  3706. pseq->autolayer[pseq->numautolayers].flags |= STUDIO_AL_SPLINE;
  3707. }
  3708. else if (stricmp( "noblend", token ) == 0)
  3709. {
  3710. pseq->autolayer[pseq->numautolayers].flags |= STUDIO_AL_NOBLEND;
  3711. }
  3712. else if (stricmp( "poseparameter", token ) == 0)
  3713. {
  3714. pseq->autolayer[pseq->numautolayers].flags |= STUDIO_AL_POSE;
  3715. GetToken( false );
  3716. pseq->autolayer[pseq->numautolayers].pose = LookupPoseParameter( token );
  3717. }
  3718. else if (stricmp( "local", token ) == 0)
  3719. {
  3720. pseq->autolayer[pseq->numautolayers].flags |= STUDIO_AL_LOCAL;
  3721. pseq->flags |= STUDIO_LOCAL;
  3722. }
  3723. else
  3724. {
  3725. UnGetToken();
  3726. break;
  3727. }
  3728. }
  3729. pseq->numautolayers++;
  3730. }
  3731. else if ((numblends || isAppend) && ParseAnimationToken( animations[0] ))
  3732. {
  3733. }
  3734. else if (!isAppend)
  3735. {
  3736. // assume it's an animation reference
  3737. // first look up an existing animation
  3738. for (n = 0; n < g_numani; n++)
  3739. {
  3740. if (stricmp( token, g_panimation[n]->name ) == 0)
  3741. {
  3742. animations[numblends++] = g_panimation[n];
  3743. break;
  3744. }
  3745. }
  3746. if (n >= g_numani)
  3747. {
  3748. // assume it's an implied animation
  3749. animations[numblends++] = Cmd_ImpliedAnimation( pseq, token );
  3750. }
  3751. // hack to allow animation commands to refer to same sequence
  3752. if (numblends == 1)
  3753. {
  3754. pseq->panim[0][0] = animations[0];
  3755. }
  3756. }
  3757. else
  3758. {
  3759. TokenError( "unknown command \"%s\"\n", token );
  3760. }
  3761. if (depth < 0)
  3762. {
  3763. TokenError("missing {\n");
  3764. }
  3765. }
  3766. ProcessSequence( pseq, numblends, animations, isAppend );
  3767. return 0;
  3768. }
  3769. //-----------------------------------------------------------------------------
  3770. // Purpose: throw away all the options for a specific sequence or animation
  3771. //-----------------------------------------------------------------------------
  3772. int ParseEmpty( )
  3773. {
  3774. int depth = 0;
  3775. while (1)
  3776. {
  3777. if (depth > 0)
  3778. {
  3779. if(!GetToken(true))
  3780. {
  3781. break;
  3782. }
  3783. }
  3784. else
  3785. {
  3786. if (!TokenAvailable())
  3787. {
  3788. break;
  3789. }
  3790. else
  3791. {
  3792. GetToken (false);
  3793. }
  3794. }
  3795. if (endofscript)
  3796. {
  3797. if (depth != 0)
  3798. {
  3799. TokenError("missing }\n" );
  3800. }
  3801. return 1;
  3802. }
  3803. if (stricmp("{", token ) == 0)
  3804. {
  3805. depth++;
  3806. }
  3807. else if (stricmp("}", token ) == 0)
  3808. {
  3809. depth--;
  3810. }
  3811. if (depth < 0)
  3812. {
  3813. TokenError("missing {\n");
  3814. }
  3815. }
  3816. return 0;
  3817. }
  3818. //-----------------------------------------------------------------------------
  3819. // Purpose: append commands to either a sequence or an animation
  3820. //-----------------------------------------------------------------------------
  3821. void Cmd_Append( )
  3822. {
  3823. GetToken(false);
  3824. s_sequence_t *pseq = LookupSequence( token );
  3825. if (pseq)
  3826. {
  3827. ParseSequence( pseq, true );
  3828. return;
  3829. }
  3830. else
  3831. {
  3832. s_animation_t *panim = LookupAnimation( token );
  3833. if (panim)
  3834. {
  3835. ParseAnimation( panim, true );
  3836. return;
  3837. }
  3838. }
  3839. TokenError( "unknown append animation %s\n", token );
  3840. }
  3841. void Cmd_Prepend( )
  3842. {
  3843. GetToken(false);
  3844. s_sequence_t *pseq = LookupSequence( token );
  3845. int count = 0;
  3846. s_animation_t *panim = NULL;
  3847. int iRet = false;
  3848. if (pseq)
  3849. {
  3850. panim = pseq->panim[0][0];
  3851. count = panim->numcmds;
  3852. iRet = ParseSequence( pseq, true );
  3853. }
  3854. else
  3855. {
  3856. panim = LookupAnimation( token );
  3857. if (panim)
  3858. {
  3859. count = panim->numcmds;
  3860. iRet = ParseAnimation( panim, true );
  3861. }
  3862. }
  3863. if (panim && count != panim->numcmds)
  3864. {
  3865. s_animcmd_t tmp;
  3866. tmp = panim->cmds[panim->numcmds - 1];
  3867. int i;
  3868. for (i = panim->numcmds - 1; i > 0; i--)
  3869. {
  3870. panim->cmds[i] = panim->cmds[i-1];
  3871. }
  3872. panim->cmds[0] = tmp;
  3873. return;
  3874. }
  3875. TokenError( "unknown prepend animation \"%s\"\n", token );
  3876. }
  3877. void Cmd_Continue( )
  3878. {
  3879. GetToken(false);
  3880. s_sequence_t *pseq = LookupSequence( token );
  3881. if (pseq)
  3882. {
  3883. GetToken(true);
  3884. UnGetToken();
  3885. if (token[0] != '$')
  3886. ParseSequence( pseq, true );
  3887. return;
  3888. }
  3889. else
  3890. {
  3891. s_animation_t *panim = LookupAnimation( token );
  3892. if (panim)
  3893. {
  3894. GetToken(true);
  3895. UnGetToken();
  3896. if (token[0] != '$')
  3897. ParseAnimation( panim, true );
  3898. return;
  3899. }
  3900. }
  3901. TokenError( "unknown continue animation %s\n", token );
  3902. }
  3903. //-----------------------------------------------------------------------------
  3904. // Purpose: foward declare an empty sequence
  3905. //-----------------------------------------------------------------------------
  3906. void Cmd_DeclareSequence( void )
  3907. {
  3908. if (g_sequence.Count() >= MAXSTUDIOSEQUENCES)
  3909. {
  3910. TokenError("Too many sequences (%d max)\n", MAXSTUDIOSEQUENCES );
  3911. }
  3912. s_sequence_t *pseq = &g_sequence[ g_sequence.AddToTail() ];
  3913. memset( pseq, 0, sizeof( s_sequence_t ) );
  3914. pseq->flags = STUDIO_OVERRIDE;
  3915. // initialize sequence
  3916. GetToken( false );
  3917. V_strcpy_safe( pseq->name, token );
  3918. }
  3919. //-----------------------------------------------------------------------------
  3920. // Purpose: foward declare an empty sequence
  3921. //-----------------------------------------------------------------------------
  3922. void Cmd_DeclareAnimation( void )
  3923. {
  3924. if (g_numani >= MAXSTUDIOANIMS)
  3925. {
  3926. TokenError("Too many animations (%d max)\n", MAXSTUDIOANIMS );
  3927. }
  3928. // allocate animation entry
  3929. s_animation_t *panim = (s_animation_t *)kalloc( 1, sizeof( s_animation_t ) );
  3930. g_panimation[g_numani] = panim;
  3931. panim->index = g_numani;
  3932. panim->flags = STUDIO_OVERRIDE;
  3933. g_numani++;
  3934. // initialize animation
  3935. GetToken( false );
  3936. V_strcpy_safe( panim->name, token );
  3937. }
  3938. //-----------------------------------------------------------------------------
  3939. // Purpose: create named list of boneweights
  3940. //-----------------------------------------------------------------------------
  3941. void Option_Weightlist( s_weightlist_t *pweightlist )
  3942. {
  3943. int depth = 0;
  3944. int i;
  3945. pweightlist->numbones = 0;
  3946. while (1)
  3947. {
  3948. if (depth > 0)
  3949. {
  3950. if(!GetToken(true))
  3951. {
  3952. break;
  3953. }
  3954. }
  3955. else
  3956. {
  3957. if (!TokenAvailable())
  3958. {
  3959. break;
  3960. }
  3961. else
  3962. {
  3963. GetToken (false);
  3964. }
  3965. }
  3966. if (endofscript)
  3967. {
  3968. if (depth != 0)
  3969. {
  3970. TokenError("missing }\n" );
  3971. }
  3972. return;
  3973. }
  3974. if (stricmp("{", token ) == 0)
  3975. {
  3976. depth++;
  3977. }
  3978. else if (stricmp("}", token ) == 0)
  3979. {
  3980. depth--;
  3981. }
  3982. else if (stricmp("posweight", token ) == 0)
  3983. {
  3984. i = pweightlist->numbones - 1;
  3985. if (i < 0)
  3986. {
  3987. MdlError( "Error with specifing bone Position weight \'%s:%s\'\n", pweightlist->name, pweightlist->bonename[i] );
  3988. }
  3989. GetToken( false );
  3990. pweightlist->boneposweight[i] = verify_atof( token );
  3991. if (pweightlist->boneweight[i] == 0 && pweightlist->boneposweight[i] > 0)
  3992. {
  3993. MdlError( "Non-zero Position weight with zero Rotation weight not allowed \'%s:%s %f %f\'\n",
  3994. pweightlist->name, pweightlist->bonename[i], pweightlist->boneweight[i], pweightlist->boneposweight[i] );
  3995. }
  3996. }
  3997. else
  3998. {
  3999. i = pweightlist->numbones++;
  4000. if (i >= MAXWEIGHTSPERLIST)
  4001. {
  4002. TokenError("Too many bones (%d) in weightlist '%s'\n", i, pweightlist->name );
  4003. }
  4004. pweightlist->bonename[i] = strdup( token );
  4005. GetToken( false );
  4006. pweightlist->boneweight[i] = verify_atof( token );
  4007. pweightlist->boneposweight[i] = pweightlist->boneweight[i];
  4008. }
  4009. if (depth < 0)
  4010. {
  4011. TokenError("missing {\n");
  4012. }
  4013. };
  4014. }
  4015. void Cmd_Weightlist( )
  4016. {
  4017. int i;
  4018. if (!GetToken(false))
  4019. return;
  4020. if (g_numweightlist >= MAXWEIGHTLISTS)
  4021. {
  4022. TokenError( "Too many weightlist commands (%d)\n", MAXWEIGHTLISTS );
  4023. }
  4024. for (i = 1; i < g_numweightlist; i++)
  4025. {
  4026. if (stricmp( g_weightlist[i].name, token ) == 0)
  4027. {
  4028. TokenError( "Duplicate weightlist '%s'\n", token );
  4029. }
  4030. }
  4031. V_strcpy_safe( g_weightlist[i].name, token );
  4032. Option_Weightlist( &g_weightlist[g_numweightlist] );
  4033. g_numweightlist++;
  4034. }
  4035. void Cmd_DefaultWeightlist( )
  4036. {
  4037. Option_Weightlist( &g_weightlist[0] );
  4038. }
  4039. //-----------------------------------------------------------------------------
  4040. // Purpose:
  4041. //-----------------------------------------------------------------------------
  4042. void Option_Eyeball( s_model_t *pmodel )
  4043. {
  4044. Vector tmp;
  4045. int i, j;
  4046. int mesh_material;
  4047. char szMeshMaterial[256];
  4048. s_eyeball_t *eyeball = &(pmodel->eyeball[pmodel->numeyeballs++]);
  4049. // name
  4050. GetToken (false);
  4051. V_strcpy_safe( eyeball->name, token );
  4052. // bone name
  4053. GetToken (false);
  4054. for (i = 0; i < pmodel->source->numbones; i++)
  4055. {
  4056. if ( !Q_stricmp( pmodel->source->localBone[i].name, token ) )
  4057. {
  4058. eyeball->bone = i;
  4059. break;
  4060. }
  4061. }
  4062. if (!g_bCreateMakefile && i >= pmodel->source->numbones)
  4063. {
  4064. TokenError( "unknown eyeball bone \"%s\"\n", token );
  4065. }
  4066. // X
  4067. GetToken (false);
  4068. tmp[0] = verify_atof (token);
  4069. // Y
  4070. GetToken (false);
  4071. tmp[1] = verify_atof (token);
  4072. // Z
  4073. GetToken (false);
  4074. tmp[2] = verify_atof (token);
  4075. // mesh material
  4076. GetToken (false);
  4077. Q_strncpy( szMeshMaterial, token, sizeof(szMeshMaterial) );
  4078. mesh_material = UseTextureAsMaterial( LookupTexture( token ) );
  4079. // diameter
  4080. GetToken (false);
  4081. eyeball->radius = verify_atof (token) / 2.0;
  4082. // Z angle offset
  4083. GetToken (false);
  4084. eyeball->zoffset = tan( DEG2RAD( verify_atof (token) ) );
  4085. // iris material (no longer used, but we need to remove the token)
  4086. GetToken (false);
  4087. // pupil scale
  4088. GetToken (false);
  4089. eyeball->iris_scale = 1.0 / verify_atof( token );
  4090. VectorCopy( tmp, eyeball->org );
  4091. for (i = 0; i < pmodel->source->nummeshes; i++)
  4092. {
  4093. j = pmodel->source->meshindex[i]; // meshes are internally stored by material index
  4094. if (j == mesh_material)
  4095. {
  4096. eyeball->mesh = i; // FIXME: should this be pre-adjusted?
  4097. break;
  4098. }
  4099. }
  4100. if (!g_bCreateMakefile && i >= pmodel->source->nummeshes)
  4101. {
  4102. TokenError("can't find eyeball texture \"%s\" on model\n", szMeshMaterial );
  4103. }
  4104. // translate eyeball into bone space
  4105. VectorITransform( tmp, pmodel->source->boneToPose[eyeball->bone], eyeball->org );
  4106. matrix3x4_t vtmp;
  4107. AngleMatrix( g_defaultrotation, vtmp );
  4108. VectorIRotate( Vector( 0, 0, 1 ), vtmp, tmp );
  4109. VectorIRotate( tmp, pmodel->source->boneToPose[eyeball->bone], eyeball->up );
  4110. VectorIRotate( Vector( 1, 0, 0 ), vtmp, tmp );
  4111. VectorIRotate( tmp, pmodel->source->boneToPose[eyeball->bone], eyeball->forward );
  4112. // these get overwritten by "eyelid" data
  4113. eyeball->upperlidflexdesc = -1;
  4114. eyeball->lowerlidflexdesc = -1;
  4115. }
  4116. //-----------------------------------------------------------------------------
  4117. // Purpose:
  4118. //-----------------------------------------------------------------------------
  4119. void Option_Spherenormals( s_source_t *psource )
  4120. {
  4121. Vector pos;
  4122. int i, j;
  4123. int mesh_material;
  4124. char szMeshMaterial[256];
  4125. // mesh material
  4126. GetToken (false);
  4127. V_strcpy_safe( szMeshMaterial, token );
  4128. mesh_material = UseTextureAsMaterial( LookupTexture( token ) );
  4129. // X
  4130. GetToken (false);
  4131. pos[0] = verify_atof (token);
  4132. // Y
  4133. GetToken (false);
  4134. pos[1] = verify_atof (token);
  4135. // Z
  4136. GetToken (false);
  4137. pos[2] = verify_atof (token);
  4138. for (i = 0; i < psource->nummeshes; i++)
  4139. {
  4140. j = psource->meshindex[i]; // meshes are internally stored by material index
  4141. if (j == mesh_material)
  4142. {
  4143. s_vertexinfo_t *vertex = &psource->vertex[psource->mesh[i].vertexoffset];
  4144. for (int k = 0; k < psource->mesh[i].numvertices; k++)
  4145. {
  4146. Vector n = vertex[k].position - pos;
  4147. VectorNormalize( n );
  4148. if (DotProduct( n, vertex[k].normal ) < 0.0)
  4149. {
  4150. vertex[k].normal = -1 * n;
  4151. }
  4152. else
  4153. {
  4154. vertex[k].normal = n;
  4155. }
  4156. #if 0
  4157. vertex[k].normal[0] += 0.5f * ( 2.0f * ( ( float )rand() ) / ( float )VALVE_RAND_MAX ) - 1.0f;
  4158. vertex[k].normal[1] += 0.5f * ( 2.0f * ( ( float )rand() ) / ( float )VALVE_RAND_MAX ) - 1.0f;
  4159. vertex[k].normal[2] += 0.5f * ( 2.0f * ( ( float )rand() ) / ( float )VALVE_RAND_MAX ) - 1.0f;
  4160. VectorNormalize( vertex[k].normal );
  4161. #endif
  4162. }
  4163. break;
  4164. }
  4165. }
  4166. if (i >= psource->nummeshes)
  4167. {
  4168. TokenError("can't find spherenormal texture \"%s\" on model\n", szMeshMaterial );
  4169. }
  4170. }
  4171. //-----------------------------------------------------------------------------
  4172. // Purpose:
  4173. //-----------------------------------------------------------------------------
  4174. int Add_Flexdesc( const char *name )
  4175. {
  4176. int flexdesc;
  4177. for ( flexdesc = 0; flexdesc < g_numflexdesc; flexdesc++)
  4178. {
  4179. if (stricmp( name, g_flexdesc[flexdesc].FACS ) == 0)
  4180. {
  4181. break;
  4182. }
  4183. }
  4184. if (flexdesc >= MAXSTUDIOFLEXDESC)
  4185. {
  4186. TokenError( "Too many flex types, max %d\n", MAXSTUDIOFLEXDESC );
  4187. }
  4188. if (flexdesc == g_numflexdesc)
  4189. {
  4190. V_strcpy_safe( g_flexdesc[flexdesc].FACS, name );
  4191. g_numflexdesc++;
  4192. }
  4193. return flexdesc;
  4194. }
  4195. //-----------------------------------------------------------------------------
  4196. // Purpose:
  4197. //-----------------------------------------------------------------------------
  4198. void Option_Flex( char *name, char *vtafile, int imodel, float pairsplit )
  4199. {
  4200. if (g_numflexkeys >= MAXSTUDIOFLEXKEYS)
  4201. {
  4202. TokenError( "Too many flexes, max %d\n", MAXSTUDIOFLEXKEYS );
  4203. }
  4204. int flexdesc, flexpair;
  4205. if (pairsplit != 0)
  4206. {
  4207. char mod[256];
  4208. sprintf( mod, "%sR", name );
  4209. flexdesc = Add_Flexdesc( mod );
  4210. sprintf( mod, "%sL", name );
  4211. flexpair = Add_Flexdesc( mod );
  4212. }
  4213. else
  4214. {
  4215. flexdesc = Add_Flexdesc( name );
  4216. flexpair = 0;
  4217. }
  4218. // initialize
  4219. g_flexkey[g_numflexkeys].imodel = imodel;
  4220. g_flexkey[g_numflexkeys].flexdesc = flexdesc;
  4221. g_flexkey[g_numflexkeys].target0 = 0.0;
  4222. g_flexkey[g_numflexkeys].target1 = 1.0;
  4223. g_flexkey[g_numflexkeys].target2 = 10;
  4224. g_flexkey[g_numflexkeys].target3 = 11;
  4225. g_flexkey[g_numflexkeys].split = pairsplit;
  4226. g_flexkey[g_numflexkeys].flexpair = flexpair;
  4227. g_flexkey[g_numflexkeys].decay = 1.0;
  4228. while (TokenAvailable())
  4229. {
  4230. GetToken(false);
  4231. if (stricmp( token, "frame") == 0)
  4232. {
  4233. GetToken (false);
  4234. g_flexkey[g_numflexkeys].frame = verify_atoi( token );
  4235. }
  4236. else if (stricmp( token, "position") == 0)
  4237. {
  4238. GetToken (false);
  4239. g_flexkey[g_numflexkeys].target1 = verify_atof( token );
  4240. }
  4241. else if (stricmp( token, "split") == 0)
  4242. {
  4243. GetToken (false);
  4244. g_flexkey[g_numflexkeys].split = verify_atof( token );
  4245. }
  4246. else if (stricmp( token, "decay") == 0)
  4247. {
  4248. GetToken (false);
  4249. g_flexkey[g_numflexkeys].decay = verify_atof( token );
  4250. }
  4251. else
  4252. {
  4253. TokenError( "unknown option: %s", token );
  4254. }
  4255. }
  4256. if (g_numflexkeys > 1)
  4257. {
  4258. if (g_flexkey[g_numflexkeys-1].flexdesc == g_flexkey[g_numflexkeys].flexdesc)
  4259. {
  4260. g_flexkey[g_numflexkeys-1].target2 = g_flexkey[g_numflexkeys-1].target1;
  4261. g_flexkey[g_numflexkeys-1].target3 = g_flexkey[g_numflexkeys].target1;
  4262. g_flexkey[g_numflexkeys].target0 = g_flexkey[g_numflexkeys-1].target1;
  4263. }
  4264. }
  4265. // link to source
  4266. s_source_t *pSource = Load_Source( vtafile, "vta" );
  4267. g_flexkey[g_numflexkeys].source = pSource;
  4268. if ( pSource->m_Animations.Count() )
  4269. {
  4270. Q_strncpy( g_flexkey[g_numflexkeys].animationname, pSource->m_Animations[0].animationname, sizeof( g_flexkey[g_numflexkeys].animationname ) );
  4271. }
  4272. else
  4273. {
  4274. g_flexkey[g_numflexkeys].animationname[0] = 0;
  4275. }
  4276. g_numflexkeys++;
  4277. // this needs to be per model.
  4278. }
  4279. //-----------------------------------------------------------------------------
  4280. // Adds combination data to the source
  4281. //-----------------------------------------------------------------------------
  4282. int FindSourceFlexKey( s_source_t *pSource, const char *pName )
  4283. {
  4284. int nCount = pSource->m_FlexKeys.Count();
  4285. for ( int i = 0; i < nCount; ++i )
  4286. {
  4287. if ( !Q_stricmp( pSource->m_FlexKeys[i].animationname, pName ) )
  4288. return i;
  4289. }
  4290. return -1;
  4291. }
  4292. //-----------------------------------------------------------------------------
  4293. // Adds flexkey data to a particular source
  4294. //-----------------------------------------------------------------------------
  4295. void AddFlexKey( s_source_t *pSource, CDmeCombinationOperator *pComboOp, const char *pFlexKeyName )
  4296. {
  4297. // See if the delta state is already accounted for
  4298. if ( FindSourceFlexKey( pSource, pFlexKeyName ) >= 0 )
  4299. return;
  4300. int i = pSource->m_FlexKeys.AddToTail();
  4301. s_flexkey_t &key = pSource->m_FlexKeys[i];
  4302. memset( &key, 0, sizeof(key) );
  4303. key.target0 = 0.0f;
  4304. key.target1 = 1.0f;
  4305. key.target2 = 10.0f;
  4306. key.target3 = 11.0f;
  4307. key.decay = 1.0f;
  4308. key.source = pSource;
  4309. Q_strncpy( key.animationname, pFlexKeyName, sizeof(key.animationname) );
  4310. key.flexpair = pComboOp->IsDeltaStateStereo( pFlexKeyName ); // Signal used by AddBodyFlexData
  4311. }
  4312. //-----------------------------------------------------------------------------
  4313. // Adds combination data to the source
  4314. //-----------------------------------------------------------------------------
  4315. void AddCombination( s_source_t *pSource, CDmeCombinationOperator *pCombination )
  4316. {
  4317. // Define the remapped controls
  4318. int nControlCount = pCombination->GetRawControlCount();
  4319. for ( int i = 0; i < nControlCount; ++i )
  4320. {
  4321. int m = pSource->m_CombinationControls.AddToTail();
  4322. s_combinationcontrol_t &control = pSource->m_CombinationControls[m];
  4323. Q_strncpy( control.name, pCombination->GetRawControlName( i ), sizeof(control.name) );
  4324. }
  4325. // Define the combination + domination rules
  4326. int nTargetCount = pCombination->GetOperationTargetCount();
  4327. for ( int i = 0; i < nTargetCount; ++i )
  4328. {
  4329. int nOpCount = pCombination->GetOperationCount( i );
  4330. for ( int j = 0; j < nOpCount; ++j )
  4331. {
  4332. CDmElement *pDeltaState = pCombination->GetOperationDeltaState( i, j );
  4333. if ( !pDeltaState )
  4334. continue;
  4335. int nFlex = FindSourceFlexKey( pSource, pDeltaState->GetName() );
  4336. if ( nFlex < 0 )
  4337. continue;
  4338. int k = pSource->m_CombinationRules.AddToTail();
  4339. s_combinationrule_t &rule = pSource->m_CombinationRules[k];
  4340. rule.m_nFlex = nFlex;
  4341. rule.m_Combination = pCombination->GetOperationControls( i, j );
  4342. int nDominatorCount = pCombination->GetOperationDominatorCount( i, j );
  4343. for ( int l = 0; l < nDominatorCount; ++l )
  4344. {
  4345. int m = rule.m_Dominators.AddToTail();
  4346. rule.m_Dominators[m] = pCombination->GetOperationDominator( i, j, l );
  4347. }
  4348. }
  4349. }
  4350. // Define the remapping controls
  4351. nControlCount = pCombination->GetControlCount();
  4352. for ( int i = 0; i < nControlCount; ++i )
  4353. {
  4354. int k = pSource->m_FlexControllerRemaps.AddToTail();
  4355. s_flexcontrollerremap_t &remap = pSource->m_FlexControllerRemaps[k];
  4356. remap.m_Name = pCombination->GetControlName( i );
  4357. remap.m_bIsStereo = pCombination->IsStereoControl( i );
  4358. remap.m_Index = -1; // Don't know this right now
  4359. remap.m_LeftIndex = -1; // Don't know this right now
  4360. remap.m_RightIndex = -1; // Don't know this right now
  4361. remap.m_MultiIndex = -1; // Don't know this right now
  4362. remap.m_EyesUpDownFlexController = -1;
  4363. remap.m_BlinkController = -1;
  4364. int nRemapCount = pCombination->GetRawControlCount( i );
  4365. if ( pCombination->IsEyelidControl( i ) )
  4366. {
  4367. remap.m_RemapType = FLEXCONTROLLER_REMAP_EYELID;
  4368. // Save the eyes_updown flex for later
  4369. const char *pEyesUpDownFlexName = pCombination->GetEyesUpDownFlexName( i );
  4370. remap.m_EyesUpDownFlexName = pEyesUpDownFlexName ? pEyesUpDownFlexName : "eyes_updown";
  4371. }
  4372. else
  4373. {
  4374. switch( nRemapCount )
  4375. {
  4376. case 0:
  4377. case 1:
  4378. remap.m_RemapType = FLEXCONTROLLER_REMAP_PASSTHRU;
  4379. break;
  4380. case 2:
  4381. remap.m_RemapType = FLEXCONTROLLER_REMAP_2WAY;
  4382. break;
  4383. default:
  4384. remap.m_RemapType = FLEXCONTROLLER_REMAP_NWAY;
  4385. break;
  4386. }
  4387. }
  4388. Assert( nRemapCount != 0 );
  4389. for ( int j = 0; j < nRemapCount; ++j )
  4390. {
  4391. const char *pRemapName = pCombination->GetRawControlName( i, j );
  4392. remap.m_RawControls.AddToTail( pRemapName );
  4393. }
  4394. }
  4395. }
  4396. //-----------------------------------------------------------------------------
  4397. // Purpose:
  4398. //-----------------------------------------------------------------------------
  4399. void Option_Eyelid( int imodel )
  4400. {
  4401. char type[256];
  4402. char vtafile[256];
  4403. // type
  4404. GetToken (false);
  4405. V_strcpy_safe( type, token );
  4406. // source
  4407. GetToken (false);
  4408. V_strcpy_safe( vtafile, token );
  4409. int lowererframe = 0;
  4410. int neutralframe = 0;
  4411. int raiserframe = 0;
  4412. float lowerertarget = 0.0f;
  4413. float neutraltarget = 0.0f;
  4414. float raisertarget = 0.0f;
  4415. int lowererdesc = 0;
  4416. int neutraldesc = 0;
  4417. int raiserdesc = 0;
  4418. int basedesc;
  4419. float split = 0;
  4420. char szEyeball[64] = {""};
  4421. basedesc = g_numflexdesc;
  4422. V_strcpy_safe( g_flexdesc[g_numflexdesc++].FACS, type );
  4423. while (TokenAvailable())
  4424. {
  4425. GetToken(false);
  4426. char localdesc[256];
  4427. V_strcpy_safe( localdesc, type );
  4428. V_strcat_safe( localdesc, "_" );
  4429. V_strcat_safe( localdesc, token );
  4430. if (stricmp( token, "lowerer") == 0)
  4431. {
  4432. GetToken (false);
  4433. lowererframe = verify_atoi( token );
  4434. GetToken (false);
  4435. lowerertarget = verify_atof( token );
  4436. lowererdesc = g_numflexdesc;
  4437. V_strcpy_safe( g_flexdesc[g_numflexdesc++].FACS, localdesc );
  4438. }
  4439. else if (stricmp( token, "neutral") == 0)
  4440. {
  4441. GetToken (false);
  4442. neutralframe = verify_atoi( token );
  4443. GetToken (false);
  4444. neutraltarget = verify_atof( token );
  4445. neutraldesc = g_numflexdesc;
  4446. V_strcpy_safe( g_flexdesc[g_numflexdesc++].FACS, localdesc );
  4447. }
  4448. else if (stricmp( token, "raiser") == 0)
  4449. {
  4450. GetToken (false);
  4451. raiserframe = verify_atoi( token );
  4452. GetToken (false);
  4453. raisertarget = verify_atof( token );
  4454. raiserdesc = g_numflexdesc;
  4455. V_strcpy_safe( g_flexdesc[g_numflexdesc++].FACS, localdesc );
  4456. }
  4457. else if (stricmp( token, "split") == 0)
  4458. {
  4459. GetToken (false);
  4460. split = verify_atof( token );
  4461. }
  4462. else if (stricmp( token, "eyeball") == 0)
  4463. {
  4464. GetToken (false);
  4465. V_strcpy_safe( szEyeball, token );
  4466. }
  4467. else
  4468. {
  4469. TokenError( "unknown option: %s", token );
  4470. }
  4471. }
  4472. s_source_t *pSource = Load_Source( vtafile, "vta" );
  4473. g_flexkey[g_numflexkeys+0].source = pSource;
  4474. g_flexkey[g_numflexkeys+0].frame = lowererframe;
  4475. g_flexkey[g_numflexkeys+0].flexdesc = basedesc;
  4476. g_flexkey[g_numflexkeys+0].imodel = imodel;
  4477. g_flexkey[g_numflexkeys+0].split = split;
  4478. g_flexkey[g_numflexkeys+0].target0 = -11;
  4479. g_flexkey[g_numflexkeys+0].target1 = -10;
  4480. g_flexkey[g_numflexkeys+0].target2 = lowerertarget;
  4481. g_flexkey[g_numflexkeys+0].target3 = neutraltarget;
  4482. g_flexkey[g_numflexkeys+0].decay = 0.0;
  4483. if ( pSource->m_Animations.Count() > 0 )
  4484. {
  4485. Q_strncpy( g_flexkey[g_numflexkeys+0].animationname, pSource->m_Animations[0].animationname, sizeof(g_flexkey[g_numflexkeys+0].animationname) );
  4486. }
  4487. else
  4488. {
  4489. g_flexkey[g_numflexkeys+0].animationname[0] = 0;
  4490. }
  4491. g_flexkey[g_numflexkeys+1].source = g_flexkey[g_numflexkeys+0].source;
  4492. Q_strncpy( g_flexkey[g_numflexkeys+1].animationname, g_flexkey[g_numflexkeys+0].animationname, sizeof(g_flexkey[g_numflexkeys+1].animationname) );
  4493. g_flexkey[g_numflexkeys+1].frame = neutralframe;
  4494. g_flexkey[g_numflexkeys+1].flexdesc = basedesc;
  4495. g_flexkey[g_numflexkeys+1].imodel = imodel;
  4496. g_flexkey[g_numflexkeys+1].split = split;
  4497. g_flexkey[g_numflexkeys+1].target0 = lowerertarget;
  4498. g_flexkey[g_numflexkeys+1].target1 = neutraltarget;
  4499. g_flexkey[g_numflexkeys+1].target2 = neutraltarget;
  4500. g_flexkey[g_numflexkeys+1].target3 = raisertarget;
  4501. g_flexkey[g_numflexkeys+1].decay = 0.0;
  4502. g_flexkey[g_numflexkeys+2].source = g_flexkey[g_numflexkeys+0].source;
  4503. Q_strncpy( g_flexkey[g_numflexkeys+2].animationname, g_flexkey[g_numflexkeys+0].animationname, sizeof(g_flexkey[g_numflexkeys+2].animationname) );
  4504. g_flexkey[g_numflexkeys+2].frame = raiserframe;
  4505. g_flexkey[g_numflexkeys+2].flexdesc = basedesc;
  4506. g_flexkey[g_numflexkeys+2].imodel = imodel;
  4507. g_flexkey[g_numflexkeys+2].split = split;
  4508. g_flexkey[g_numflexkeys+2].target0 = neutraltarget;
  4509. g_flexkey[g_numflexkeys+2].target1 = raisertarget;
  4510. g_flexkey[g_numflexkeys+2].target2 = 10;
  4511. g_flexkey[g_numflexkeys+2].target3 = 11;
  4512. g_flexkey[g_numflexkeys+2].decay = 0.0;
  4513. g_numflexkeys += 3;
  4514. s_model_t *pmodel = g_model[imodel];
  4515. for (int i = 0; i < pmodel->numeyeballs; i++)
  4516. {
  4517. s_eyeball_t *peyeball = &(pmodel->eyeball[i]);
  4518. if (szEyeball[0] != '\0')
  4519. {
  4520. if (stricmp( peyeball->name, szEyeball ) != 0)
  4521. continue;
  4522. }
  4523. if (fabs( lowerertarget ) > peyeball->radius)
  4524. {
  4525. TokenError( "Eyelid \"%s\" lowerer out of range (+-%.1f)\n", type, peyeball->radius );
  4526. }
  4527. if (fabs( neutraltarget ) > peyeball->radius)
  4528. {
  4529. TokenError( "Eyelid \"%s\" neutral out of range (+-%.1f)\n", type, peyeball->radius );
  4530. }
  4531. if (fabs( raisertarget ) > peyeball->radius)
  4532. {
  4533. TokenError( "Eyelid \"%s\" raiser out of range (+-%.1f)\n", type, peyeball->radius );
  4534. }
  4535. switch( type[0] )
  4536. {
  4537. case 'u':
  4538. peyeball->upperlidflexdesc = basedesc;
  4539. peyeball->upperflexdesc[0] = lowererdesc;
  4540. peyeball->uppertarget[0] = lowerertarget;
  4541. peyeball->upperflexdesc[1] = neutraldesc;
  4542. peyeball->uppertarget[1] = neutraltarget;
  4543. peyeball->upperflexdesc[2] = raiserdesc;
  4544. peyeball->uppertarget[2] = raisertarget;
  4545. break;
  4546. case 'l':
  4547. peyeball->lowerlidflexdesc = basedesc;
  4548. peyeball->lowerflexdesc[0] = lowererdesc;
  4549. peyeball->lowertarget[0] = lowerertarget;
  4550. peyeball->lowerflexdesc[1] = neutraldesc;
  4551. peyeball->lowertarget[1] = neutraltarget;
  4552. peyeball->lowerflexdesc[2] = raiserdesc;
  4553. peyeball->lowertarget[2] = raisertarget;
  4554. break;
  4555. }
  4556. }
  4557. }
  4558. /*
  4559. =================
  4560. =================
  4561. */
  4562. int Option_Mouth( s_model_t *pmodel )
  4563. {
  4564. // index
  4565. GetToken (false);
  4566. int index = verify_atoi( token );
  4567. if (index >= g_nummouths)
  4568. g_nummouths = index + 1;
  4569. // flex controller name
  4570. GetToken (false);
  4571. g_mouth[index].flexdesc = Add_Flexdesc( token );
  4572. // bone name
  4573. GetToken (false);
  4574. V_strcpy_safe( g_mouth[index].bonename, token );
  4575. // vector
  4576. GetToken (false);
  4577. g_mouth[index].forward[0] = verify_atof( token );
  4578. GetToken (false);
  4579. g_mouth[index].forward[1] = verify_atof( token );
  4580. GetToken (false);
  4581. g_mouth[index].forward[2] = verify_atof( token );
  4582. return 0;
  4583. }
  4584. void Option_Flexcontroller( s_model_t *pmodel )
  4585. {
  4586. char type[256];
  4587. float range_min = 0.0f;
  4588. float range_max = 1.0f;
  4589. // g_flex
  4590. GetToken (false);
  4591. V_strcpy_safe( type, token );
  4592. while (TokenAvailable())
  4593. {
  4594. GetToken(false);
  4595. if (stricmp( token, "range") == 0)
  4596. {
  4597. GetToken(false);
  4598. range_min = verify_atof( token );
  4599. GetToken(false);
  4600. range_max = verify_atof( token );
  4601. }
  4602. else
  4603. {
  4604. if (g_numflexcontrollers >= MAXSTUDIOFLEXCTRL)
  4605. {
  4606. TokenError( "Too many flex controllers, max %d\n", MAXSTUDIOFLEXCTRL );
  4607. }
  4608. V_strcpy_safe( g_flexcontroller[g_numflexcontrollers].name, token );
  4609. V_strcpy_safe( g_flexcontroller[g_numflexcontrollers].type, type );
  4610. g_flexcontroller[g_numflexcontrollers].min = range_min;
  4611. g_flexcontroller[g_numflexcontrollers].max = range_max;
  4612. g_numflexcontrollers++;
  4613. }
  4614. }
  4615. // this needs to be per model.
  4616. }
  4617. void Option_Flexrule( s_model_t *pmodel, char *name )
  4618. {
  4619. int precedence[32];
  4620. precedence[ STUDIO_CONST ] = 0;
  4621. precedence[ STUDIO_FETCH1 ] = 0;
  4622. precedence[ STUDIO_FETCH2 ] = 0;
  4623. precedence[ STUDIO_ADD ] = 1;
  4624. precedence[ STUDIO_SUB ] = 1;
  4625. precedence[ STUDIO_MUL ] = 2;
  4626. precedence[ STUDIO_DIV ] = 2;
  4627. precedence[ STUDIO_NEG ] = 4;
  4628. precedence[ STUDIO_EXP ] = 3;
  4629. precedence[ STUDIO_OPEN ] = 0; // only used in token parsing
  4630. precedence[ STUDIO_CLOSE ] = 0;
  4631. precedence[ STUDIO_COMMA ] = 0;
  4632. precedence[ STUDIO_MAX ] = 5;
  4633. precedence[ STUDIO_MIN ] = 5;
  4634. s_flexop_t stream[MAX_OPS];
  4635. int i = 0;
  4636. s_flexop_t stack[MAX_OPS];
  4637. int j = 0;
  4638. int k = 0;
  4639. s_flexrule_t *pRule = &g_flexrule[g_numflexrules++];
  4640. if (g_numflexrules > MAXSTUDIOFLEXRULES)
  4641. {
  4642. TokenError( "Too many flex rules (max %d)\n", MAXSTUDIOFLEXRULES );
  4643. }
  4644. int flexdesc;
  4645. for ( flexdesc = 0; flexdesc < g_numflexdesc; flexdesc++)
  4646. {
  4647. if (stricmp( name, g_flexdesc[flexdesc].FACS ) == 0)
  4648. {
  4649. break;
  4650. }
  4651. }
  4652. if (flexdesc >= g_numflexdesc)
  4653. {
  4654. TokenError( "Rule for unknown flex %s\n", name );
  4655. }
  4656. pRule->flex = flexdesc;
  4657. pRule->numops = 0;
  4658. // =
  4659. GetToken(false);
  4660. // parse all the tokens
  4661. bool linecontinue = false;
  4662. while ( linecontinue || TokenAvailable())
  4663. {
  4664. GetExprToken(linecontinue);
  4665. linecontinue = false;
  4666. if ( token[0] == '\\' )
  4667. {
  4668. if (!GetToken(false) || token[0] != '\\')
  4669. {
  4670. TokenError( "unknown expression token '\\%s\n", token );
  4671. }
  4672. linecontinue = true;
  4673. }
  4674. else if ( token[0] == '(' )
  4675. {
  4676. stream[i++].op = STUDIO_OPEN;
  4677. }
  4678. else if ( token[0] == ')' )
  4679. {
  4680. stream[i++].op = STUDIO_CLOSE;
  4681. }
  4682. else if ( token[0] == '+' )
  4683. {
  4684. stream[i++].op = STUDIO_ADD;
  4685. }
  4686. else if ( token[0] == '-' )
  4687. {
  4688. stream[i].op = STUDIO_SUB;
  4689. if (i > 0)
  4690. {
  4691. switch( stream[i-1].op )
  4692. {
  4693. case STUDIO_OPEN:
  4694. case STUDIO_ADD:
  4695. case STUDIO_SUB:
  4696. case STUDIO_MUL:
  4697. case STUDIO_DIV:
  4698. case STUDIO_COMMA:
  4699. // it's a unary if it's preceded by a "(+-*/,"?
  4700. stream[i].op = STUDIO_NEG;
  4701. break;
  4702. }
  4703. }
  4704. i++;
  4705. }
  4706. else if ( token[0] == '*' )
  4707. {
  4708. stream[i++].op = STUDIO_MUL;
  4709. }
  4710. else if ( token[0] == '/' )
  4711. {
  4712. stream[i++].op = STUDIO_DIV;
  4713. }
  4714. else if ( V_isdigit( token[0] ))
  4715. {
  4716. stream[i].op = STUDIO_CONST;
  4717. stream[i++].d.value = verify_atof( token );
  4718. }
  4719. else if ( token[0] == ',' )
  4720. {
  4721. stream[i++].op = STUDIO_COMMA;
  4722. }
  4723. else if ( stricmp( token, "max" ) == 0)
  4724. {
  4725. stream[i++].op = STUDIO_MAX;
  4726. }
  4727. else if ( stricmp( token, "min" ) == 0)
  4728. {
  4729. stream[i++].op = STUDIO_MIN;
  4730. }
  4731. else
  4732. {
  4733. if (token[0] == '%')
  4734. {
  4735. GetExprToken(false);
  4736. for (k = 0; k < g_numflexdesc; k++)
  4737. {
  4738. if (stricmp( token, g_flexdesc[k].FACS ) == 0)
  4739. {
  4740. stream[i].op = STUDIO_FETCH2;
  4741. stream[i++].d.index = k;
  4742. break;
  4743. }
  4744. }
  4745. if (k >= g_numflexdesc)
  4746. {
  4747. TokenError( "unknown flex %s\n", token );
  4748. }
  4749. }
  4750. else
  4751. {
  4752. for (k = 0; k < g_numflexcontrollers; k++)
  4753. {
  4754. if (stricmp( token, g_flexcontroller[k].name ) == 0)
  4755. {
  4756. stream[i].op = STUDIO_FETCH1;
  4757. stream[i++].d.index = k;
  4758. break;
  4759. }
  4760. }
  4761. if (k >= g_numflexcontrollers)
  4762. {
  4763. TokenError( "unknown controller %s\n", token );
  4764. }
  4765. }
  4766. }
  4767. }
  4768. if (i > MAX_OPS)
  4769. {
  4770. TokenError("expression %s too complicated\n", g_flexdesc[pRule->flex].FACS );
  4771. }
  4772. if (0)
  4773. {
  4774. printf("%s = ", g_flexdesc[pRule->flex].FACS );
  4775. for ( k = 0; k < i; k++)
  4776. {
  4777. switch( stream[k].op )
  4778. {
  4779. case STUDIO_CONST: printf("%f ", stream[k].d.value ); break;
  4780. case STUDIO_FETCH1: printf("%s ", g_flexcontroller[stream[k].d.index].name ); break;
  4781. case STUDIO_FETCH2: printf("[%d] ", stream[k].d.index ); break;
  4782. case STUDIO_ADD: printf("+ "); break;
  4783. case STUDIO_SUB: printf("- "); break;
  4784. case STUDIO_MUL: printf("* "); break;
  4785. case STUDIO_DIV: printf("/ "); break;
  4786. case STUDIO_NEG: printf("neg "); break;
  4787. case STUDIO_MAX: printf("max "); break;
  4788. case STUDIO_MIN: printf("min "); break;
  4789. case STUDIO_COMMA: printf(", "); break; // error
  4790. case STUDIO_OPEN: printf("( " ); break; // error
  4791. case STUDIO_CLOSE: printf(") " ); break; // error
  4792. default:
  4793. printf("err%d ", stream[k].op ); break;
  4794. }
  4795. }
  4796. printf("\n");
  4797. // exit(1);
  4798. }
  4799. j = 0;
  4800. for (k = 0; k < i; k++)
  4801. {
  4802. if (j >= MAX_OPS)
  4803. {
  4804. TokenError("expression %s too complicated\n", g_flexdesc[pRule->flex].FACS );
  4805. }
  4806. switch( stream[k].op )
  4807. {
  4808. case STUDIO_CONST:
  4809. case STUDIO_FETCH1:
  4810. case STUDIO_FETCH2:
  4811. pRule->op[pRule->numops++] = stream[k];
  4812. break;
  4813. case STUDIO_OPEN:
  4814. stack[j++] = stream[k];
  4815. break;
  4816. case STUDIO_CLOSE:
  4817. // pop all operators off of the stack until an open paren
  4818. while (j > 0 && stack[j-1].op != STUDIO_OPEN)
  4819. {
  4820. pRule->op[pRule->numops++] = stack[j-1];
  4821. j--;
  4822. }
  4823. if (j == 0)
  4824. {
  4825. TokenError( "unmatched closed parentheses\n" );
  4826. }
  4827. if (j > 0)
  4828. j--;
  4829. break;
  4830. case STUDIO_COMMA:
  4831. // pop all operators off of the stack until an open paren
  4832. while (j > 0 && stack[j-1].op != STUDIO_OPEN)
  4833. {
  4834. pRule->op[pRule->numops++] = stack[j-1];
  4835. j--;
  4836. }
  4837. // push operator onto the stack
  4838. stack[j++] = stream[k];
  4839. break;
  4840. case STUDIO_ADD:
  4841. case STUDIO_SUB:
  4842. case STUDIO_MUL:
  4843. case STUDIO_DIV:
  4844. // pop all operators off of the stack that have equal or higher precedence
  4845. while (j > 0 && precedence[stream[k].op] <= precedence[stack[j-1].op])
  4846. {
  4847. pRule->op[pRule->numops++] = stack[j-1];
  4848. j--;
  4849. }
  4850. // push operator onto the stack
  4851. stack[j++] = stream[k];
  4852. break;
  4853. case STUDIO_NEG:
  4854. if (stream[k+1].op == STUDIO_CONST)
  4855. {
  4856. // change sign of constant, skip op
  4857. stream[k+1].d.value = -stream[k+1].d.value;
  4858. }
  4859. else
  4860. {
  4861. // push operator onto the stack
  4862. stack[j++] = stream[k];
  4863. }
  4864. break;
  4865. case STUDIO_MAX:
  4866. case STUDIO_MIN:
  4867. // push operator onto the stack
  4868. stack[j++] = stream[k];
  4869. break;
  4870. }
  4871. if (pRule->numops >= MAX_OPS)
  4872. TokenError("expression for \"%s\" too complicated\n", g_flexdesc[pRule->flex].FACS );
  4873. }
  4874. // pop all operators off of the stack
  4875. while (j > 0)
  4876. {
  4877. pRule->op[pRule->numops++] = stack[j-1];
  4878. j--;
  4879. if (pRule->numops >= MAX_OPS)
  4880. TokenError("expression for \"%s\" too complicated\n", g_flexdesc[pRule->flex].FACS );
  4881. }
  4882. // reprocess the operands, eating commas for all functions
  4883. int numCommas = 0;
  4884. j = 0;
  4885. for (k = 0; k < pRule->numops; k++)
  4886. {
  4887. switch( pRule->op[k].op )
  4888. {
  4889. case STUDIO_MAX:
  4890. case STUDIO_MIN:
  4891. if (pRule->op[j-1].op != STUDIO_COMMA)
  4892. {
  4893. TokenError( "missing comma\n");
  4894. }
  4895. // eat the comma operator
  4896. numCommas--;
  4897. pRule->op[j-1] = pRule->op[k];
  4898. break;
  4899. case STUDIO_COMMA:
  4900. numCommas++;
  4901. pRule->op[j++] = pRule->op[k];
  4902. break;
  4903. default:
  4904. pRule->op[j++] = pRule->op[k];
  4905. break;
  4906. }
  4907. }
  4908. pRule->numops = j;
  4909. if (numCommas != 0)
  4910. {
  4911. TokenError( "too many comma's\n" );
  4912. }
  4913. if (pRule->numops > MAX_OPS)
  4914. {
  4915. TokenError("expression %s too complicated\n", g_flexdesc[pRule->flex].FACS );
  4916. }
  4917. if (0)
  4918. {
  4919. printf("%s = ", g_flexdesc[pRule->flex].FACS );
  4920. for ( i = 0; i < pRule->numops; i++)
  4921. {
  4922. switch( pRule->op[i].op )
  4923. {
  4924. case STUDIO_CONST: printf("%f ", pRule->op[i].d.value ); break;
  4925. case STUDIO_FETCH1: printf("%s ", g_flexcontroller[pRule->op[i].d.index].name ); break;
  4926. case STUDIO_FETCH2: printf("[%d] ", pRule->op[i].d.index ); break;
  4927. case STUDIO_ADD: printf("+ "); break;
  4928. case STUDIO_SUB: printf("- "); break;
  4929. case STUDIO_MUL: printf("* "); break;
  4930. case STUDIO_DIV: printf("/ "); break;
  4931. case STUDIO_NEG: printf("neg "); break;
  4932. case STUDIO_MAX: printf("max "); break;
  4933. case STUDIO_MIN: printf("min "); break;
  4934. case STUDIO_COMMA: printf(", "); break; // error
  4935. case STUDIO_OPEN: printf("( " ); break; // error
  4936. case STUDIO_CLOSE: printf(") " ); break; // error
  4937. default:
  4938. printf("err%d ", pRule->op[i].op ); break;
  4939. }
  4940. }
  4941. printf("\n");
  4942. // exit(1);
  4943. }
  4944. }
  4945. //-----------------------------------------------------------------------------
  4946. // Purpose:
  4947. //-----------------------------------------------------------------------------
  4948. void Cmd_Model( )
  4949. {
  4950. g_model[g_nummodels] = (s_model_t *)kalloc( 1, sizeof( s_model_t ) );
  4951. // name
  4952. if (!GetToken(false))
  4953. return;
  4954. V_strcpy_safe( g_model[g_nummodels]->name, token );
  4955. // fake g_bodypart stuff
  4956. if (g_numbodyparts == 0)
  4957. {
  4958. g_bodypart[g_numbodyparts].base = 1;
  4959. }
  4960. else
  4961. {
  4962. g_bodypart[g_numbodyparts].base = g_bodypart[g_numbodyparts-1].base * g_bodypart[g_numbodyparts-1].nummodels;
  4963. }
  4964. V_strcpy_safe( g_bodypart[g_numbodyparts].name, token );
  4965. g_bodypart[g_numbodyparts].pmodel[g_bodypart[g_numbodyparts].nummodels] = g_model[g_nummodels];
  4966. g_bodypart[g_numbodyparts].nummodels = 1;
  4967. g_numbodyparts++;
  4968. Option_Studio( g_model[g_nummodels] );
  4969. if ( g_model[g_nummodels]->source )
  4970. {
  4971. // Body command should add any flex commands in the source loaded
  4972. AddBodyFlexData( g_model[g_nummodels]->source, g_nummodels );
  4973. AddBodyAttachments( g_model[g_nummodels]->source );
  4974. }
  4975. int depth = 0;
  4976. while (1)
  4977. {
  4978. char FAC[256], vtafile[256];
  4979. if (depth > 0)
  4980. {
  4981. if( !GetToken(true) )
  4982. break;
  4983. }
  4984. else
  4985. {
  4986. if ( !TokenAvailable() )
  4987. {
  4988. break;
  4989. }
  4990. else
  4991. {
  4992. GetToken (false);
  4993. }
  4994. }
  4995. if ( endofscript )
  4996. {
  4997. if (depth != 0)
  4998. {
  4999. TokenError("missing }\n" );
  5000. }
  5001. return;
  5002. }
  5003. if ( !Q_stricmp("{", token ) )
  5004. {
  5005. depth++;
  5006. }
  5007. else if ( !Q_stricmp("}", token ) )
  5008. {
  5009. depth--;
  5010. }
  5011. else if ( !Q_stricmp( "eyeball", token ) )
  5012. {
  5013. Option_Eyeball( g_model[g_nummodels] );
  5014. }
  5015. else if ( !Q_stricmp( "eyelid", token ) )
  5016. {
  5017. Option_Eyelid( g_nummodels );
  5018. }
  5019. else if ( !Q_stricmp( "flex", token ) )
  5020. {
  5021. // g_flex
  5022. GetToken (false);
  5023. V_strcpy_safe( FAC, token );
  5024. if (depth == 0)
  5025. {
  5026. // file
  5027. GetToken (false);
  5028. V_strcpy_safe( vtafile, token );
  5029. }
  5030. Option_Flex( FAC, vtafile, g_nummodels, 0.0 ); // FIXME: this needs to point to a model used, not loaded!!!
  5031. }
  5032. else if ( !Q_stricmp( "flexpair", token ) )
  5033. {
  5034. // g_flex
  5035. GetToken (false);
  5036. V_strcpy_safe( FAC, token );
  5037. GetToken( false );
  5038. float split = atof( token );
  5039. if (depth == 0)
  5040. {
  5041. // file
  5042. GetToken (false);
  5043. V_strcpy_safe( vtafile, token );
  5044. }
  5045. Option_Flex( FAC, vtafile, g_nummodels, split ); // FIXME: this needs to point to a model used, not loaded!!!
  5046. }
  5047. else if ( !Q_stricmp( "defaultflex", token ) )
  5048. {
  5049. if (depth == 0)
  5050. {
  5051. // file
  5052. GetToken (false);
  5053. V_strcpy_safe( vtafile, token );
  5054. }
  5055. // g_flex
  5056. Option_Flex( "default", vtafile, g_nummodels, 0.0 ); // FIXME: this needs to point to a model used, not loaded!!!
  5057. g_defaultflexkey = &g_flexkey[g_numflexkeys-1];
  5058. }
  5059. else if ( !Q_stricmp( "flexfile", token ) )
  5060. {
  5061. // file
  5062. GetToken (false);
  5063. V_strcpy_safe( vtafile, token );
  5064. }
  5065. else if ( !Q_stricmp( "localvar", token ) )
  5066. {
  5067. while (TokenAvailable())
  5068. {
  5069. GetToken( false );
  5070. Add_Flexdesc( token );
  5071. }
  5072. }
  5073. else if ( !Q_stricmp( "mouth", token ) )
  5074. {
  5075. Option_Mouth( g_model[g_nummodels] );
  5076. }
  5077. else if ( !Q_stricmp( "flexcontroller", token ) )
  5078. {
  5079. Option_Flexcontroller( g_model[g_nummodels] );
  5080. }
  5081. else if ( token[0] == '%' )
  5082. {
  5083. Option_Flexrule( g_model[g_nummodels], &token[1] );
  5084. }
  5085. else if ( !Q_stricmp("attachment", token ) )
  5086. {
  5087. // Option_Attachment( g_model[g_nummodels] );
  5088. }
  5089. else if ( !Q_stricmp( token, "spherenormals" ) )
  5090. {
  5091. Option_Spherenormals( g_model[g_nummodels]->source );
  5092. }
  5093. else
  5094. {
  5095. TokenError( "unknown model option \"%s\"\n", token );
  5096. }
  5097. if (depth < 0)
  5098. {
  5099. TokenError("missing {\n");
  5100. }
  5101. };
  5102. // Actually connect up the expressions between the Dme Flex Controllers & Flex Descriptors
  5103. // In case there was data added by some other eyeball command (like eyelid)
  5104. AddBodyFlexRules( g_model[ g_nummodels ]->source );
  5105. g_nummodels++;
  5106. }
  5107. void Cmd_FakeVTA( void )
  5108. {
  5109. int depth = 0;
  5110. GetToken( false );
  5111. s_source_t *psource = (s_source_t *)kalloc( 1, sizeof( s_source_t ) );
  5112. g_source[g_numsources] = psource;
  5113. V_strcpy_safe( g_source[g_numsources]->filename, token );
  5114. g_numsources++;
  5115. while (1)
  5116. {
  5117. if (depth > 0)
  5118. {
  5119. if(!GetToken(true))
  5120. {
  5121. break;
  5122. }
  5123. }
  5124. else
  5125. {
  5126. if (!TokenAvailable())
  5127. {
  5128. break;
  5129. }
  5130. else
  5131. {
  5132. GetToken (false);
  5133. }
  5134. }
  5135. if (endofscript)
  5136. {
  5137. if (depth != 0)
  5138. {
  5139. TokenError("missing }\n" );
  5140. }
  5141. return;
  5142. }
  5143. if (stricmp("{", token ) == 0)
  5144. {
  5145. depth++;
  5146. }
  5147. else if (stricmp("}", token ) == 0)
  5148. {
  5149. depth--;
  5150. }
  5151. else if (stricmp("appendvta", token ) == 0)
  5152. {
  5153. char filename[256];
  5154. // file
  5155. GetToken (false);
  5156. V_strcpy_safe( filename, token );
  5157. GetToken( false );
  5158. int frame = verify_atoi( token );
  5159. AppendVTAtoOBJ( psource, filename, frame );
  5160. }
  5161. }
  5162. }
  5163. //-----------------------------------------------------------------------------
  5164. // Purpose:
  5165. //-----------------------------------------------------------------------------
  5166. void Cmd_IKChain( )
  5167. {
  5168. if (!GetToken(false))
  5169. return;
  5170. int i;
  5171. for ( i = 0; i < g_numikchains; i++)
  5172. {
  5173. if (stricmp( token, g_ikchain[i].name ) == 0)
  5174. {
  5175. break;
  5176. }
  5177. }
  5178. if (i < g_numikchains)
  5179. {
  5180. if (!g_quiet)
  5181. {
  5182. printf("duplicate ikchain \"%s\" ignored\n", token );
  5183. }
  5184. while (TokenAvailable())
  5185. {
  5186. GetToken(false);
  5187. }
  5188. return;
  5189. }
  5190. V_strcpy_safe( g_ikchain[g_numikchains].name, token );
  5191. GetToken(false);
  5192. V_strcpy_safe( g_ikchain[g_numikchains].bonename, token );
  5193. g_ikchain[g_numikchains].axis = STUDIO_Z;
  5194. g_ikchain[g_numikchains].value = 0.0;
  5195. g_ikchain[g_numikchains].height = 18.0;
  5196. g_ikchain[g_numikchains].floor = 0.0;
  5197. g_ikchain[g_numikchains].radius = 0.0;
  5198. while (TokenAvailable())
  5199. {
  5200. GetToken(false);
  5201. if (lookupControl( token ) != -1)
  5202. {
  5203. g_ikchain[g_numikchains].axis = lookupControl( token );
  5204. GetToken(false);
  5205. g_ikchain[g_numikchains].value = verify_atof( token );
  5206. }
  5207. else if (stricmp( "height", token ) == 0)
  5208. {
  5209. GetToken(false);
  5210. g_ikchain[g_numikchains].height = verify_atof( token );
  5211. }
  5212. else if (stricmp( "pad", token ) == 0)
  5213. {
  5214. GetToken(false);
  5215. g_ikchain[g_numikchains].radius = verify_atof( token ) / 2.0;
  5216. }
  5217. else if (stricmp( "floor", token ) == 0)
  5218. {
  5219. GetToken(false);
  5220. g_ikchain[g_numikchains].floor = verify_atof( token );
  5221. }
  5222. else if (stricmp( "knee", token ) == 0)
  5223. {
  5224. GetToken(false);
  5225. g_ikchain[g_numikchains].link[0].kneeDir.x = verify_atof( token );
  5226. GetToken(false);
  5227. g_ikchain[g_numikchains].link[0].kneeDir.y = verify_atof( token );
  5228. GetToken(false);
  5229. g_ikchain[g_numikchains].link[0].kneeDir.z = verify_atof( token );
  5230. }
  5231. else if (stricmp( "center", token ) == 0)
  5232. {
  5233. GetToken(false);
  5234. g_ikchain[g_numikchains].center.x = verify_atof( token );
  5235. GetToken(false);
  5236. g_ikchain[g_numikchains].center.y = verify_atof( token );
  5237. GetToken(false);
  5238. g_ikchain[g_numikchains].center.z = verify_atof( token );
  5239. }
  5240. }
  5241. g_numikchains++;
  5242. }
  5243. //-----------------------------------------------------------------------------
  5244. // Purpose:
  5245. //-----------------------------------------------------------------------------
  5246. void Cmd_IKAutoplayLock( )
  5247. {
  5248. GetToken(false);
  5249. V_strcpy_safe( g_ikautoplaylock[g_numikautoplaylocks].name, token );
  5250. GetToken(false);
  5251. g_ikautoplaylock[g_numikautoplaylocks].flPosWeight = verify_atof( token );
  5252. GetToken(false);
  5253. g_ikautoplaylock[g_numikautoplaylocks].flLocalQWeight = verify_atof( token );
  5254. g_numikautoplaylocks++;
  5255. }
  5256. //-----------------------------------------------------------------------------
  5257. // Purpose:
  5258. //-----------------------------------------------------------------------------
  5259. void Cmd_Root ()
  5260. {
  5261. if (GetToken (false))
  5262. {
  5263. V_strcpy_safe( rootname, token );
  5264. }
  5265. }
  5266. //-----------------------------------------------------------------------------
  5267. // Purpose:
  5268. //-----------------------------------------------------------------------------
  5269. void Cmd_Controller (void)
  5270. {
  5271. if (GetToken (false))
  5272. {
  5273. if (!stricmp("mouth",token))
  5274. {
  5275. g_bonecontroller[g_numbonecontrollers].inputfield = 4;
  5276. }
  5277. else
  5278. {
  5279. g_bonecontroller[g_numbonecontrollers].inputfield = verify_atoi(token);
  5280. }
  5281. if (GetToken(false))
  5282. {
  5283. V_strcpy_safe( g_bonecontroller[g_numbonecontrollers].name, token );
  5284. GetToken(false);
  5285. if ((g_bonecontroller[g_numbonecontrollers].type = lookupControl(token)) == -1)
  5286. {
  5287. MdlWarning("unknown g_bonecontroller type '%s'\n", token );
  5288. return;
  5289. }
  5290. GetToken(false);
  5291. g_bonecontroller[g_numbonecontrollers].start = verify_atof( token );
  5292. GetToken(false);
  5293. g_bonecontroller[g_numbonecontrollers].end = verify_atof( token );
  5294. if (g_bonecontroller[g_numbonecontrollers].type & (STUDIO_XR | STUDIO_YR | STUDIO_ZR))
  5295. {
  5296. if (((int)(g_bonecontroller[g_numbonecontrollers].start + 360) % 360) == ((int)(g_bonecontroller[g_numbonecontrollers].end + 360) % 360))
  5297. {
  5298. g_bonecontroller[g_numbonecontrollers].type |= STUDIO_RLOOP;
  5299. }
  5300. }
  5301. g_numbonecontrollers++;
  5302. }
  5303. }
  5304. }
  5305. //-----------------------------------------------------------------------------
  5306. // Purpose:
  5307. //-----------------------------------------------------------------------------
  5308. // Debugging function that enumerate all a models bones to stdout.
  5309. static void SpewBones()
  5310. {
  5311. MdlWarning("g_numbones %i\n",g_numbones);
  5312. for ( int i = g_numbones; --i >= 0; )
  5313. {
  5314. printf("%s\n",g_bonetable[i].name);
  5315. }
  5316. }
  5317. //-----------------------------------------------------------------------------
  5318. // Purpose:
  5319. //-----------------------------------------------------------------------------
  5320. void Cmd_ScreenAlign ( void )
  5321. {
  5322. if (GetToken (false))
  5323. {
  5324. Assert( g_numscreenalignedbones < MAXSTUDIOSRCBONES );
  5325. V_strcpy_safe( g_screenalignedbone[g_numscreenalignedbones].name, token );
  5326. g_screenalignedbone[g_numscreenalignedbones].flags = BONE_SCREEN_ALIGN_SPHERE;
  5327. if( GetToken( false ) )
  5328. {
  5329. if( !stricmp( "sphere", token ) )
  5330. {
  5331. g_screenalignedbone[g_numscreenalignedbones].flags = BONE_SCREEN_ALIGN_SPHERE;
  5332. }
  5333. else if( !stricmp( "cylinder", token ) )
  5334. {
  5335. g_screenalignedbone[g_numscreenalignedbones].flags = BONE_SCREEN_ALIGN_CYLINDER;
  5336. }
  5337. }
  5338. g_numscreenalignedbones++;
  5339. } else
  5340. {
  5341. TokenError( "$screenalign: expected bone name\n" );
  5342. }
  5343. }
  5344. //-----------------------------------------------------------------------------
  5345. // Purpose:
  5346. //-----------------------------------------------------------------------------
  5347. void Cmd_BBox (void)
  5348. {
  5349. GetToken (false);
  5350. bbox[0][0] = verify_atof( token );
  5351. GetToken (false);
  5352. bbox[0][1] = verify_atof( token );
  5353. GetToken (false);
  5354. bbox[0][2] = verify_atof( token );
  5355. GetToken (false);
  5356. bbox[1][0] = verify_atof( token );
  5357. GetToken (false);
  5358. bbox[1][1] = verify_atof( token );
  5359. GetToken (false);
  5360. bbox[1][2] = verify_atof( token );
  5361. g_wrotebbox = true;
  5362. }
  5363. //-----------------------------------------------------------------------------
  5364. // Purpose:
  5365. //-----------------------------------------------------------------------------
  5366. void Cmd_CBox (void)
  5367. {
  5368. GetToken (false);
  5369. cbox[0][0] = verify_atof( token );
  5370. GetToken (false);
  5371. cbox[0][1] = verify_atof( token );
  5372. GetToken (false);
  5373. cbox[0][2] = verify_atof( token );
  5374. GetToken (false);
  5375. cbox[1][0] = verify_atof( token );
  5376. GetToken (false);
  5377. cbox[1][1] = verify_atof( token );
  5378. GetToken (false);
  5379. cbox[1][2] = verify_atof( token );
  5380. g_wrotecbox = true;
  5381. }
  5382. //-----------------------------------------------------------------------------
  5383. // Purpose:
  5384. //-----------------------------------------------------------------------------
  5385. void Cmd_Gamma (void)
  5386. {
  5387. GetToken (false);
  5388. g_gamma = verify_atof( token );
  5389. }
  5390. //-----------------------------------------------------------------------------
  5391. // Purpose:
  5392. //-----------------------------------------------------------------------------
  5393. void Cmd_TextureGroup( )
  5394. {
  5395. if( g_bCreateMakefile )
  5396. {
  5397. return;
  5398. }
  5399. int i;
  5400. int depth = 0;
  5401. int index = 0;
  5402. int group = 0;
  5403. if (!GetToken(false))
  5404. return;
  5405. if (g_numskinref == 0)
  5406. g_numskinref = g_numtextures;
  5407. while (1)
  5408. {
  5409. if(!GetToken(true))
  5410. {
  5411. break;
  5412. }
  5413. if (endofscript)
  5414. {
  5415. if (depth != 0)
  5416. {
  5417. TokenError("missing }\n" );
  5418. }
  5419. return;
  5420. }
  5421. if (token[0] == '{')
  5422. {
  5423. depth++;
  5424. }
  5425. else if (token[0] == '}')
  5426. {
  5427. depth--;
  5428. if (depth == 0)
  5429. break;
  5430. group++;
  5431. index = 0;
  5432. }
  5433. else if (depth == 2)
  5434. {
  5435. i = UseTextureAsMaterial( LookupTexture( token ) );
  5436. g_texturegroup[g_numtexturegroups][group][index] = i;
  5437. if (group != 0)
  5438. g_texture[i].parent = g_texturegroup[g_numtexturegroups][0][index];
  5439. index++;
  5440. g_numtexturereps[g_numtexturegroups] = index;
  5441. g_numtexturelayers[g_numtexturegroups] = group + 1;
  5442. }
  5443. }
  5444. g_numtexturegroups++;
  5445. }
  5446. //-----------------------------------------------------------------------------
  5447. // Purpose:
  5448. //-----------------------------------------------------------------------------
  5449. void Cmd_Hitgroup( )
  5450. {
  5451. GetToken (false);
  5452. g_hitgroup[g_numhitgroups].group = verify_atoi( token );
  5453. GetToken (false);
  5454. V_strcpy_safe( g_hitgroup[g_numhitgroups].name, token );
  5455. g_numhitgroups++;
  5456. }
  5457. //-----------------------------------------------------------------------------
  5458. // Purpose:
  5459. //-----------------------------------------------------------------------------
  5460. void Cmd_Hitbox( )
  5461. {
  5462. bool autogenerated = false;
  5463. if ( g_hitboxsets.Size() == 0 )
  5464. {
  5465. g_hitboxsets.AddToTail();
  5466. autogenerated = true;
  5467. }
  5468. // Last one
  5469. s_hitboxset *set = &g_hitboxsets[ g_hitboxsets.Size() - 1 ];
  5470. if ( autogenerated )
  5471. {
  5472. memset( set, 0, sizeof( *set ) );
  5473. // fill in name if it wasn't specified in the .qc
  5474. V_strcpy_safe( set->hitboxsetname, "default" );
  5475. }
  5476. GetToken (false);
  5477. set->hitbox[set->numhitboxes].group = verify_atoi( token );
  5478. // Grab the bone name:
  5479. GetToken (false);
  5480. V_strcpy_safe( set->hitbox[set->numhitboxes].name, token );
  5481. GetToken (false);
  5482. set->hitbox[set->numhitboxes].bmin[0] = verify_atof( token );
  5483. GetToken (false);
  5484. set->hitbox[set->numhitboxes].bmin[1] = verify_atof( token );
  5485. GetToken (false);
  5486. set->hitbox[set->numhitboxes].bmin[2] = verify_atof( token );
  5487. GetToken (false);
  5488. set->hitbox[set->numhitboxes].bmax[0] = verify_atof( token );
  5489. GetToken (false);
  5490. set->hitbox[set->numhitboxes].bmax[1] = verify_atof( token );
  5491. GetToken (false);
  5492. set->hitbox[set->numhitboxes].bmax[2] = verify_atof( token );
  5493. //Scale hitboxes
  5494. scale_vertex( set->hitbox[set->numhitboxes].bmin );
  5495. scale_vertex( set->hitbox[set->numhitboxes].bmax );
  5496. // clear out the hitboxname:
  5497. memset( set->hitbox[set->numhitboxes].hitboxname, 0, sizeof( set->hitbox[set->numhitboxes].hitboxname ) );
  5498. // Grab the hit box name if present:
  5499. if( TokenAvailable() )
  5500. {
  5501. GetToken (false);
  5502. V_strcpy_safe( set->hitbox[set->numhitboxes].hitboxname, token );
  5503. }
  5504. set->numhitboxes++;
  5505. }
  5506. //-----------------------------------------------------------------------------
  5507. // Purpose:
  5508. //-----------------------------------------------------------------------------
  5509. void Cmd_HitboxSet( void )
  5510. {
  5511. // Add a new hitboxset
  5512. s_hitboxset *set = &g_hitboxsets[ g_hitboxsets.AddToTail() ];
  5513. GetToken( false );
  5514. memset( set, 0, sizeof( *set ) );
  5515. V_strcpy_safe( set->hitboxsetname, token );
  5516. }
  5517. //-----------------------------------------------------------------------------
  5518. // Assigns a default surface property to the entire model
  5519. //-----------------------------------------------------------------------------
  5520. struct SurfacePropName_t
  5521. {
  5522. char m_pJointName[128];
  5523. char m_pSurfaceProp[128];
  5524. };
  5525. static char s_pDefaultSurfaceProp[128] = {"default"};
  5526. static CUtlVector<SurfacePropName_t> s_JointSurfaceProp;
  5527. //-----------------------------------------------------------------------------
  5528. // Assigns a default surface property to the entire model
  5529. //-----------------------------------------------------------------------------
  5530. void Cmd_SurfaceProp ()
  5531. {
  5532. GetToken (false);
  5533. V_strcpy_safe( s_pDefaultSurfaceProp, token );
  5534. }
  5535. //-----------------------------------------------------------------------------
  5536. // Assigns a surface property to a particular joint
  5537. //-----------------------------------------------------------------------------
  5538. void Cmd_JointSurfaceProp ()
  5539. {
  5540. // Get joint name...
  5541. GetToken (false);
  5542. // Search for the name in our list
  5543. int i;
  5544. for ( i = s_JointSurfaceProp.Count(); --i >= 0; )
  5545. {
  5546. if (!stricmp(s_JointSurfaceProp[i].m_pJointName, token))
  5547. {
  5548. break;
  5549. }
  5550. }
  5551. // Add new entry if we haven't seen this name before
  5552. if (i < 0)
  5553. {
  5554. i = s_JointSurfaceProp.AddToTail();
  5555. V_strcpy_safe( s_JointSurfaceProp[i].m_pJointName, token );
  5556. }
  5557. // surface property name
  5558. GetToken(false);
  5559. V_strcpy_safe( s_JointSurfaceProp[i].m_pSurfaceProp, token );
  5560. }
  5561. //-----------------------------------------------------------------------------
  5562. // Returns the default surface prop name
  5563. //-----------------------------------------------------------------------------
  5564. char* GetDefaultSurfaceProp ( )
  5565. {
  5566. return s_pDefaultSurfaceProp;
  5567. }
  5568. //-----------------------------------------------------------------------------
  5569. // Returns surface property for a given joint
  5570. //-----------------------------------------------------------------------------
  5571. static char* FindSurfaceProp ( const char* pJointName )
  5572. {
  5573. for ( int i = s_JointSurfaceProp.Count(); --i >= 0; )
  5574. {
  5575. if (!stricmp(s_JointSurfaceProp[i].m_pJointName, pJointName))
  5576. {
  5577. return s_JointSurfaceProp[i].m_pSurfaceProp;
  5578. }
  5579. }
  5580. return 0;
  5581. }
  5582. //-----------------------------------------------------------------------------
  5583. // Returns surface property for a given joint
  5584. //-----------------------------------------------------------------------------
  5585. char* GetSurfaceProp ( const char* pJointName )
  5586. {
  5587. while( pJointName )
  5588. {
  5589. // First try to find this joint
  5590. char* pSurfaceProp = FindSurfaceProp( pJointName );
  5591. if (pSurfaceProp)
  5592. return pSurfaceProp;
  5593. // If we can't find the joint, then find it's parent...
  5594. if (!g_numbones)
  5595. return s_pDefaultSurfaceProp;
  5596. int i = findGlobalBone( pJointName );
  5597. if ((i >= 0) && (g_bonetable[i].parent >= 0))
  5598. {
  5599. pJointName = g_bonetable[g_bonetable[i].parent].name;
  5600. }
  5601. else
  5602. {
  5603. pJointName = 0;
  5604. }
  5605. }
  5606. // No match, return the default one
  5607. return s_pDefaultSurfaceProp;
  5608. }
  5609. //-----------------------------------------------------------------------------
  5610. // Returns surface property for a given joint
  5611. //-----------------------------------------------------------------------------
  5612. void ConsistencyCheckSurfaceProp ( )
  5613. {
  5614. for ( int i = s_JointSurfaceProp.Count(); --i >= 0; )
  5615. {
  5616. int j = findGlobalBone( s_JointSurfaceProp[i].m_pJointName );
  5617. if (j < 0)
  5618. {
  5619. MdlWarning("You specified a joint surface property for joint\n"
  5620. " \"%s\" which either doesn't exist or was optimized out.\n", s_JointSurfaceProp[i].m_pJointName );
  5621. }
  5622. }
  5623. }
  5624. //-----------------------------------------------------------------------------
  5625. // Assigns a default contents to the entire model
  5626. //-----------------------------------------------------------------------------
  5627. struct ContentsName_t
  5628. {
  5629. char m_pJointName[128];
  5630. int m_nContents;
  5631. };
  5632. static int s_nDefaultContents = CONTENTS_SOLID;
  5633. static CUtlVector<ContentsName_t> s_JointContents;
  5634. //-----------------------------------------------------------------------------
  5635. // Parse contents flags
  5636. //-----------------------------------------------------------------------------
  5637. static void ParseContents( int *pAddFlags, int *pRemoveFlags )
  5638. {
  5639. *pAddFlags = 0;
  5640. *pRemoveFlags = 0;
  5641. do
  5642. {
  5643. GetToken (false);
  5644. if ( !stricmp( token, "grate" ) )
  5645. {
  5646. *pAddFlags |= CONTENTS_GRATE;
  5647. *pRemoveFlags |= CONTENTS_SOLID;
  5648. }
  5649. else if ( !stricmp( token, "ladder" ) )
  5650. {
  5651. *pAddFlags |= CONTENTS_LADDER;
  5652. }
  5653. else if ( !stricmp( token, "solid" ) )
  5654. {
  5655. *pAddFlags |= CONTENTS_SOLID;
  5656. }
  5657. else if ( !stricmp( token, "monster" ) )
  5658. {
  5659. *pAddFlags |= CONTENTS_MONSTER;
  5660. }
  5661. else if ( !stricmp( token, "notsolid" ) )
  5662. {
  5663. *pRemoveFlags |= CONTENTS_SOLID;
  5664. }
  5665. } while (TokenAvailable());
  5666. }
  5667. //-----------------------------------------------------------------------------
  5668. // Assigns a default contents to the entire model
  5669. //-----------------------------------------------------------------------------
  5670. void Cmd_Contents()
  5671. {
  5672. int nAddFlags, nRemoveFlags;
  5673. ParseContents( &nAddFlags, &nRemoveFlags );
  5674. s_nDefaultContents |= nAddFlags;
  5675. s_nDefaultContents &= ~nRemoveFlags;
  5676. }
  5677. //-----------------------------------------------------------------------------
  5678. // Assigns contents to a particular joint
  5679. //-----------------------------------------------------------------------------
  5680. void Cmd_JointContents ()
  5681. {
  5682. // Get joint name...
  5683. GetToken (false);
  5684. // Search for the name in our list
  5685. int i;
  5686. for ( i = s_JointContents.Count(); --i >= 0; )
  5687. {
  5688. if (!stricmp(s_JointContents[i].m_pJointName, token))
  5689. {
  5690. break;
  5691. }
  5692. }
  5693. // Add new entry if we haven't seen this name before
  5694. if (i < 0)
  5695. {
  5696. i = s_JointContents.AddToTail();
  5697. V_strcpy_safe( s_JointContents[i].m_pJointName, token );
  5698. }
  5699. int nAddFlags, nRemoveFlags;
  5700. ParseContents( &nAddFlags, &nRemoveFlags );
  5701. s_JointContents[i].m_nContents = CONTENTS_SOLID;
  5702. s_JointContents[i].m_nContents |= nAddFlags;
  5703. s_JointContents[i].m_nContents &= ~nRemoveFlags;
  5704. }
  5705. //-----------------------------------------------------------------------------
  5706. // Returns the default contents
  5707. //-----------------------------------------------------------------------------
  5708. int GetDefaultContents( )
  5709. {
  5710. return s_nDefaultContents;
  5711. }
  5712. //-----------------------------------------------------------------------------
  5713. // Returns contents for a given joint
  5714. //-----------------------------------------------------------------------------
  5715. static int FindContents( const char* pJointName )
  5716. {
  5717. for ( int i = s_JointContents.Count(); --i >= 0; )
  5718. {
  5719. if (!stricmp(s_JointContents[i].m_pJointName, pJointName))
  5720. {
  5721. return s_JointContents[i].m_nContents;
  5722. }
  5723. }
  5724. return -1;
  5725. }
  5726. //-----------------------------------------------------------------------------
  5727. // Returns contents for a given joint
  5728. //-----------------------------------------------------------------------------
  5729. int GetContents( const char* pJointName )
  5730. {
  5731. while( pJointName )
  5732. {
  5733. // First try to find this joint
  5734. int nContents = FindContents( pJointName );
  5735. if (nContents != -1)
  5736. return nContents;
  5737. // If we can't find the joint, then find it's parent...
  5738. if (!g_numbones)
  5739. return s_nDefaultContents;
  5740. int i = findGlobalBone( pJointName );
  5741. if ((i >= 0) && (g_bonetable[i].parent >= 0))
  5742. {
  5743. pJointName = g_bonetable[g_bonetable[i].parent].name;
  5744. }
  5745. else
  5746. {
  5747. pJointName = 0;
  5748. }
  5749. }
  5750. // No match, return the default one
  5751. return s_nDefaultContents;
  5752. }
  5753. //-----------------------------------------------------------------------------
  5754. // Checks specified contents
  5755. //-----------------------------------------------------------------------------
  5756. void ConsistencyCheckContents( )
  5757. {
  5758. for ( int i = s_JointContents.Count(); --i >= 0; )
  5759. {
  5760. int j = findGlobalBone( s_JointContents[i].m_pJointName );
  5761. if (j < 0)
  5762. {
  5763. MdlWarning("You specified a joint contents for joint\n"
  5764. " \"%s\" which either doesn't exist or was optimized out.\n", s_JointSurfaceProp[i].m_pJointName );
  5765. }
  5766. }
  5767. }
  5768. //-----------------------------------------------------------------------------
  5769. // Purpose:
  5770. //-----------------------------------------------------------------------------
  5771. void Cmd_BoneMerge( )
  5772. {
  5773. if( g_bCreateMakefile )
  5774. return;
  5775. int nIndex = g_BoneMerge.AddToTail();
  5776. // bone name
  5777. GetToken (false);
  5778. V_strcpy_safe( g_BoneMerge[nIndex].bonename, token );
  5779. }
  5780. //-----------------------------------------------------------------------------
  5781. // Purpose:
  5782. //-----------------------------------------------------------------------------
  5783. void Cmd_Attachment( )
  5784. {
  5785. if( g_bCreateMakefile )
  5786. return;
  5787. // name
  5788. GetToken (false);
  5789. V_strcpy_safe( g_attachment[g_numattachments].name, token );
  5790. // bone name
  5791. GetToken (false);
  5792. V_strcpy_safe( g_attachment[g_numattachments].bonename, token );
  5793. Vector tmp;
  5794. // position
  5795. GetToken (false);
  5796. tmp.x = verify_atof( token );
  5797. GetToken (false);
  5798. tmp.y = verify_atof( token );
  5799. GetToken (false);
  5800. tmp.z = verify_atof( token );
  5801. scale_vertex( tmp );
  5802. // identity matrix
  5803. AngleMatrix( QAngle( 0, 0, 0 ), g_attachment[g_numattachments].local );
  5804. while (TokenAvailable())
  5805. {
  5806. GetToken (false);
  5807. if (stricmp(token,"absolute") == 0)
  5808. {
  5809. g_attachment[g_numattachments].type |= IS_ABSOLUTE;
  5810. AngleIMatrix( g_defaultrotation, g_attachment[g_numattachments].local );
  5811. // AngleIMatrix( Vector( 0, 0, 0 ), g_attachment[g_numattachments].local );
  5812. }
  5813. else if (stricmp(token,"rigid") == 0)
  5814. {
  5815. g_attachment[g_numattachments].type |= IS_RIGID;
  5816. }
  5817. else if (stricmp(token,"world_align") == 0)
  5818. {
  5819. g_attachment[g_numattachments].flags |= ATTACHMENT_FLAG_WORLD_ALIGN;
  5820. }
  5821. else if (stricmp(token,"rotate") == 0)
  5822. {
  5823. QAngle angles;
  5824. for (int i = 0; i < 3; ++i)
  5825. {
  5826. if (!TokenAvailable())
  5827. break;
  5828. GetToken(false);
  5829. angles[i] = verify_atof( token );
  5830. }
  5831. AngleMatrix( angles, g_attachment[g_numattachments].local );
  5832. }
  5833. else if (stricmp(token,"x_and_z_axes") == 0)
  5834. {
  5835. int i;
  5836. Vector xaxis, yaxis, zaxis;
  5837. for (i = 0; i < 3; ++i)
  5838. {
  5839. if (!TokenAvailable())
  5840. break;
  5841. GetToken(false);
  5842. xaxis[i] = verify_atof( token );
  5843. }
  5844. for (i = 0; i < 3; ++i)
  5845. {
  5846. if (!TokenAvailable())
  5847. break;
  5848. GetToken(false);
  5849. zaxis[i] = verify_atof( token );
  5850. }
  5851. VectorNormalize( xaxis );
  5852. VectorMA( zaxis, -DotProduct( zaxis, xaxis ), xaxis, zaxis );
  5853. VectorNormalize( zaxis );
  5854. CrossProduct( zaxis, xaxis, yaxis );
  5855. MatrixSetColumn( xaxis, 0, g_attachment[g_numattachments].local );
  5856. MatrixSetColumn( yaxis, 1, g_attachment[g_numattachments].local );
  5857. MatrixSetColumn( zaxis, 2, g_attachment[g_numattachments].local );
  5858. MatrixSetColumn( vec3_origin, 3, g_attachment[g_numattachments].local );
  5859. }
  5860. else
  5861. {
  5862. TokenError("unknown attachment (%s) option: ", g_attachment[g_numattachments].name, token );
  5863. }
  5864. }
  5865. g_attachment[g_numattachments].local[0][3] = tmp.x;
  5866. g_attachment[g_numattachments].local[1][3] = tmp.y;
  5867. g_attachment[g_numattachments].local[2][3] = tmp.z;
  5868. g_numattachments++;
  5869. }
  5870. //-----------------------------------------------------------------------------
  5871. // Purpose:
  5872. //-----------------------------------------------------------------------------
  5873. int LookupAttachment( char *name )
  5874. {
  5875. int i;
  5876. for (i = 0; i < g_numattachments; i++)
  5877. {
  5878. if (stricmp( g_attachment[i].name, name ) == 0)
  5879. {
  5880. return i;
  5881. }
  5882. }
  5883. return -1;
  5884. }
  5885. //-----------------------------------------------------------------------------
  5886. // Purpose:
  5887. //-----------------------------------------------------------------------------
  5888. void Cmd_Renamebone( )
  5889. {
  5890. // from
  5891. GetToken (false);
  5892. V_strcpy_safe( g_renamedbone[g_numrenamedbones].from, token );
  5893. // to
  5894. GetToken (false);
  5895. V_strcpy_safe( g_renamedbone[g_numrenamedbones].to, token );
  5896. g_numrenamedbones++;
  5897. }
  5898. //-----------------------------------------------------------------------------
  5899. // Purpose:
  5900. //-----------------------------------------------------------------------------
  5901. void Cmd_Skiptransition( )
  5902. {
  5903. int nskips = 0;
  5904. int list[10];
  5905. while (TokenAvailable())
  5906. {
  5907. GetToken (false);
  5908. list[nskips++] = LookupXNode( token );
  5909. }
  5910. for (int i = 0; i < nskips; i++)
  5911. {
  5912. for (int j = 0; j < nskips; j++)
  5913. {
  5914. if (list[i] != list[j])
  5915. {
  5916. g_xnodeskip[g_numxnodeskips][0] = list[i];
  5917. g_xnodeskip[g_numxnodeskips][1] = list[j];
  5918. g_numxnodeskips++;
  5919. }
  5920. }
  5921. }
  5922. }
  5923. //-----------------------------------------------------------------------------
  5924. //
  5925. // The following code is all related to LODs
  5926. //
  5927. //-----------------------------------------------------------------------------
  5928. //-----------------------------------------------------------------------------
  5929. // Parse replacemodel command, causes an LOD to use a new model
  5930. //-----------------------------------------------------------------------------
  5931. static void Cmd_ReplaceModel( LodScriptData_t& lodData )
  5932. {
  5933. int i = lodData.modelReplacements.AddToTail();
  5934. CLodScriptReplacement_t& newReplacement = lodData.modelReplacements[i];
  5935. // from
  5936. GetToken( false );
  5937. // Strip off extensions for the source...
  5938. char* pDot = strrchr( token, '.' );
  5939. if (pDot)
  5940. {
  5941. *pDot = 0;
  5942. }
  5943. if (!FindCachedSource( token, "" ))
  5944. {
  5945. // must have prior knowledge of the from
  5946. TokenError( "Unknown replace model '%s'\n", token );
  5947. }
  5948. newReplacement.SetSrcName( token );
  5949. // to
  5950. GetToken( false );
  5951. newReplacement.SetDstName( token );
  5952. // check for "reverse"
  5953. bool reverse = false;
  5954. if( TokenAvailable() && GetToken( false ) )
  5955. {
  5956. if( stricmp( "reverse", token ) == 0 )
  5957. {
  5958. reverse = true;
  5959. }
  5960. else
  5961. {
  5962. TokenError( "\"%s\" unexpected\n", token );
  5963. }
  5964. }
  5965. // If the LOD system tells us to replace "blank", let's forget
  5966. // we ever read this. Have to do it here so parsing works
  5967. if( !stricmp( newReplacement.GetSrcName(), "blank" ) )
  5968. {
  5969. lodData.modelReplacements.FastRemove( i );
  5970. return;
  5971. }
  5972. // Load the source right here baby! That way its bones will get converted
  5973. if ( !lodData.IsStrippedFromModel() )
  5974. {
  5975. newReplacement.m_pSource = Load_Source( newReplacement.GetDstName(), "smd", reverse, false );
  5976. }
  5977. else if ( !g_quiet )
  5978. {
  5979. printf( "Stripped lod \"%s\" @ %.1f\n", newReplacement.GetDstName(), lodData.switchValue );
  5980. }
  5981. }
  5982. //-----------------------------------------------------------------------------
  5983. // Parse removemodel command, causes an LOD to stop using a model
  5984. //-----------------------------------------------------------------------------
  5985. static void Cmd_RemoveModel( LodScriptData_t& lodData )
  5986. {
  5987. int i = lodData.modelReplacements.AddToTail();
  5988. CLodScriptReplacement_t& newReplacement = lodData.modelReplacements[i];
  5989. // from
  5990. GetToken( false );
  5991. // Strip off extensions...
  5992. char* pDot = strrchr( token, '.' );
  5993. if (pDot)
  5994. *pDot = 0;
  5995. newReplacement.SetSrcName( token );
  5996. // to
  5997. newReplacement.SetDstName( "" );
  5998. // If the LOD system tells us to replace "blank", let's forget
  5999. // we ever read this. Have to do it here so parsing works
  6000. if( !stricmp( newReplacement.GetSrcName(), "blank" ) )
  6001. {
  6002. lodData.modelReplacements.FastRemove( i );
  6003. }
  6004. }
  6005. //-----------------------------------------------------------------------------
  6006. // Parse replacebone command, causes a part of an LOD model to use a different bone
  6007. //-----------------------------------------------------------------------------
  6008. static void Cmd_ReplaceBone( LodScriptData_t& lodData )
  6009. {
  6010. int i = lodData.boneReplacements.AddToTail();
  6011. CLodScriptReplacement_t& newReplacement = lodData.boneReplacements[i];
  6012. // from
  6013. GetToken( false );
  6014. newReplacement.SetSrcName( token );
  6015. // to
  6016. GetToken( false );
  6017. newReplacement.SetDstName( token );
  6018. }
  6019. //-----------------------------------------------------------------------------
  6020. // Parse bonetreecollapse command, causes the entire subtree to use the same bone as the node
  6021. //-----------------------------------------------------------------------------
  6022. static void Cmd_BoneTreeCollapse( LodScriptData_t& lodData )
  6023. {
  6024. int i = lodData.boneTreeCollapses.AddToTail();
  6025. CLodScriptReplacement_t& newCollapse = lodData.boneTreeCollapses[i];
  6026. // from
  6027. GetToken( false );
  6028. newCollapse.SetSrcName( token );
  6029. }
  6030. //-----------------------------------------------------------------------------
  6031. // Parse replacematerial command, causes a material to be used in place of another
  6032. //-----------------------------------------------------------------------------
  6033. static void Cmd_ReplaceMaterial( LodScriptData_t& lodData )
  6034. {
  6035. int i = lodData.materialReplacements.AddToTail();
  6036. CLodScriptReplacement_t& newReplacement = lodData.materialReplacements[i];
  6037. // from
  6038. GetToken( false );
  6039. newReplacement.SetSrcName( token );
  6040. // to
  6041. GetToken( false );
  6042. newReplacement.SetDstName( token );
  6043. if ( !lodData.IsStrippedFromModel() )
  6044. {
  6045. // make sure it goes into the master list
  6046. UseTextureAsMaterial( LookupTexture( token ) );
  6047. }
  6048. }
  6049. //-----------------------------------------------------------------------------
  6050. // Parse removemesh command, causes a mesh to not be used anymore
  6051. //-----------------------------------------------------------------------------
  6052. static void Cmd_RemoveMesh( LodScriptData_t& lodData )
  6053. {
  6054. int i = lodData.meshRemovals.AddToTail();
  6055. CLodScriptReplacement_t& newReplacement = lodData.meshRemovals[i];
  6056. // from
  6057. GetToken( false );
  6058. Q_FixSlashes( token );
  6059. newReplacement.SetSrcName( token );
  6060. }
  6061. void Cmd_LOD( const char *cmdname )
  6062. {
  6063. if ( gflags & STUDIOHDR_FLAGS_HASSHADOWLOD )
  6064. {
  6065. MdlError( "Model can only have one $shadowlod and it must be the last lod in the .qc (%d) : %s\n", g_iLinecount, g_szLine );
  6066. }
  6067. int i = g_ScriptLODs.AddToTail();
  6068. LodScriptData_t& newLOD = g_ScriptLODs[i];
  6069. if( g_ScriptLODs.Count() > MAX_NUM_LODS )
  6070. {
  6071. MdlError( "Too many LODs (MAX_NUM_LODS==%d)\n", ( int )MAX_NUM_LODS );
  6072. }
  6073. // Shadow lod reserves -1 as switch value
  6074. // which uniquely identifies a shadow lod
  6075. newLOD.switchValue = -1.0f;
  6076. bool isShadowCall = ( !stricmp( cmdname, "$shadowlod" ) ) ? true : false;
  6077. if ( isShadowCall )
  6078. {
  6079. if ( TokenAvailable() )
  6080. {
  6081. GetToken( false );
  6082. MdlWarning( "(%d) : %s: Ignoring switch value on %s command line\n", g_iLinecount, cmdname, g_szLine );
  6083. }
  6084. // Disable facial animation by default
  6085. newLOD.EnableFacialAnimation( false );
  6086. }
  6087. else
  6088. {
  6089. if ( TokenAvailable() )
  6090. {
  6091. GetToken( false );
  6092. newLOD.switchValue = verify_atof( token );
  6093. if ( newLOD.switchValue < 0.0f )
  6094. {
  6095. MdlError( "Negative switch value reserved for $shadowlod (%d) : %s\n", g_iLinecount, g_szLine );
  6096. }
  6097. }
  6098. else
  6099. {
  6100. MdlError( "Expected LOD switch value (%d) : %s\n", g_iLinecount, g_szLine );
  6101. }
  6102. }
  6103. GetToken( true );
  6104. if( stricmp( "{", token ) != 0 )
  6105. {
  6106. MdlError( "\"{\" expected while processing %s (%d) : %s", cmdname, g_iLinecount, g_szLine );
  6107. }
  6108. // In case we are stripping all lods and it's not Lod0, strip it
  6109. if ( i && g_bStripLods )
  6110. newLOD.StripFromModel( true );
  6111. while( 1 )
  6112. {
  6113. GetToken( true );
  6114. if( stricmp( "replacemodel", token ) == 0 )
  6115. {
  6116. Cmd_ReplaceModel(newLOD);
  6117. }
  6118. else if( stricmp( "removemodel", token ) == 0 )
  6119. {
  6120. Cmd_RemoveModel(newLOD);
  6121. }
  6122. else if( stricmp( "replacebone", token ) == 0 )
  6123. {
  6124. Cmd_ReplaceBone( newLOD );
  6125. }
  6126. else if( stricmp( "bonetreecollapse", token ) == 0 )
  6127. {
  6128. Cmd_BoneTreeCollapse( newLOD );
  6129. }
  6130. else if( stricmp( "replacematerial", token ) == 0 )
  6131. {
  6132. Cmd_ReplaceMaterial( newLOD );
  6133. }
  6134. else if( stricmp( "removemesh", token ) == 0 )
  6135. {
  6136. Cmd_RemoveMesh( newLOD );
  6137. }
  6138. else if( stricmp( "nofacial", token ) == 0 )
  6139. {
  6140. newLOD.EnableFacialAnimation( false );
  6141. }
  6142. else if( stricmp( "facial", token ) == 0 )
  6143. {
  6144. if (isShadowCall)
  6145. {
  6146. // facial animation has no reasonable purpose on a shadow lod
  6147. TokenError( "Facial animation is not allowed for $shadowlod\n" );
  6148. }
  6149. newLOD.EnableFacialAnimation( true );
  6150. }
  6151. else if ( stricmp( "use_shadowlod_materials", token ) == 0 )
  6152. {
  6153. if (isShadowCall)
  6154. {
  6155. gflags |= STUDIOHDR_FLAGS_USE_SHADOWLOD_MATERIALS;
  6156. }
  6157. }
  6158. else if( stricmp( "}", token ) == 0 )
  6159. {
  6160. break;
  6161. }
  6162. else
  6163. {
  6164. MdlError( "invalid input while processing %s (%d) : %s", cmdname, g_iLinecount, g_szLine );
  6165. }
  6166. }
  6167. // If the LOD is stripped, then forget we saw it
  6168. if ( newLOD.IsStrippedFromModel() )
  6169. {
  6170. g_ScriptLODs.FastRemove( i );
  6171. }
  6172. }
  6173. void Cmd_ShadowLOD( void )
  6174. {
  6175. if (!g_quiet)
  6176. {
  6177. printf( "Processing $shadowlod\n" );
  6178. }
  6179. // Act like it's a regular lod entry
  6180. Cmd_LOD( "$shadowlod" );
  6181. // Mark .mdl as having shadow lod (we also check above that we have only one of these
  6182. // and that it's the last entered lod )
  6183. gflags |= STUDIOHDR_FLAGS_HASSHADOWLOD;
  6184. }
  6185. //-----------------------------------------------------------------------------
  6186. // A couple commands related to translucency sorting
  6187. //-----------------------------------------------------------------------------
  6188. void Cmd_Opaque( )
  6189. {
  6190. // Force Opaque has precedence
  6191. gflags |= STUDIOHDR_FLAGS_FORCE_OPAQUE;
  6192. gflags &= ~STUDIOHDR_FLAGS_TRANSLUCENT_TWOPASS;
  6193. }
  6194. void Cmd_TranslucentTwoPass( )
  6195. {
  6196. // Force Opaque has precedence
  6197. if ((gflags & STUDIOHDR_FLAGS_FORCE_OPAQUE) == 0)
  6198. {
  6199. gflags |= STUDIOHDR_FLAGS_TRANSLUCENT_TWOPASS;
  6200. }
  6201. }
  6202. //-----------------------------------------------------------------------------
  6203. // Indicates the model be rendered with ambient boost heuristic (first used on Alyx in Episode 1)
  6204. //-----------------------------------------------------------------------------
  6205. void Cmd_AmbientBoost()
  6206. {
  6207. gflags |= STUDIOHDR_FLAGS_AMBIENT_BOOST;
  6208. }
  6209. //-----------------------------------------------------------------------------
  6210. // Indicates the model should not cast shadows (useful for first-person models as used in L4D)
  6211. //-----------------------------------------------------------------------------
  6212. void Cmd_DoNotCastShadows()
  6213. {
  6214. gflags |= STUDIOHDR_FLAGS_DO_NOT_CAST_SHADOWS;
  6215. }
  6216. //-----------------------------------------------------------------------------
  6217. // Indicates the model should cast texutre-based shadows in vrad (NOTE: only applicable to prop_static)
  6218. //-----------------------------------------------------------------------------
  6219. void Cmd_CastTextureShadows()
  6220. {
  6221. gflags |= STUDIOHDR_FLAGS_CAST_TEXTURE_SHADOWS;
  6222. }
  6223. //-----------------------------------------------------------------------------
  6224. // Indicates the model should not fade out even if the level or fallback settings say to
  6225. //-----------------------------------------------------------------------------
  6226. void Cmd_NoForcedFade()
  6227. {
  6228. gflags |= STUDIOHDR_FLAGS_NO_FORCED_FADE;
  6229. }
  6230. //-----------------------------------------------------------------------------
  6231. // Indicates the model should not use the bone origin when calculating bboxes, sequence boxes, etc.
  6232. //-----------------------------------------------------------------------------
  6233. void Cmd_SkipBoneInBBox()
  6234. {
  6235. g_bUseBoneInBBox = false;
  6236. }
  6237. //-----------------------------------------------------------------------------
  6238. // Indicates the model will lengthen the viseme check to always include two phonemes
  6239. //-----------------------------------------------------------------------------
  6240. void Cmd_ForcePhonemeCrossfade()
  6241. {
  6242. gflags |= STUDIOHDR_FLAGS_FORCE_PHONEME_CROSSFADE;
  6243. }
  6244. //-----------------------------------------------------------------------------
  6245. // Indicates the model should keep pre-defined bone lengths regardless of animation changes
  6246. //-----------------------------------------------------------------------------
  6247. void Cmd_LockBoneLengths()
  6248. {
  6249. g_bLockBoneLengths = true;
  6250. }
  6251. //-----------------------------------------------------------------------------
  6252. // Indicates the model should replace pre-defined bone lengths and default orientations
  6253. //-----------------------------------------------------------------------------
  6254. void Cmd_UnlockDefineBones()
  6255. {
  6256. g_bOverridePreDefinedBones = true;
  6257. }
  6258. //-----------------------------------------------------------------------------
  6259. // Mark this model as obsolete so that it'll show the obsolete material in game.
  6260. //-----------------------------------------------------------------------------
  6261. void Cmd_Obsolete( )
  6262. {
  6263. // Force Opaque has precedence
  6264. gflags |= STUDIOHDR_FLAGS_OBSOLETE;
  6265. }
  6266. //-----------------------------------------------------------------------------
  6267. // The bones should be moved so that they center themselves on the verts they own.
  6268. //-----------------------------------------------------------------------------
  6269. void Cmd_CenterBonesOnVerts( )
  6270. {
  6271. // force centering on bones
  6272. g_bCenterBonesOnVerts = true;
  6273. }
  6274. //-----------------------------------------------------------------------------
  6275. // How far back should simple motion extract pull back from the last frame
  6276. //-----------------------------------------------------------------------------
  6277. void Cmd_MotionExtractionRollBack( )
  6278. {
  6279. GetToken( false );
  6280. g_flDefaultMotionRollback = atof( token );
  6281. }
  6282. //-----------------------------------------------------------------------------
  6283. // rules for breaking up long animations into multiple sub anims
  6284. //-----------------------------------------------------------------------------
  6285. void Cmd_SectionFrames( )
  6286. {
  6287. GetToken( false );
  6288. g_sectionFrames = atof( token );
  6289. GetToken( false );
  6290. g_minSectionFrameLimit = atoi( token );
  6291. }
  6292. //-----------------------------------------------------------------------------
  6293. // world space clamping boundaries for animations
  6294. //-----------------------------------------------------------------------------
  6295. void Cmd_ClampWorldspace( )
  6296. {
  6297. GetToken (false);
  6298. g_vecMinWorldspace[0] = verify_atof( token );
  6299. GetToken (false);
  6300. g_vecMinWorldspace[1] = verify_atof( token );
  6301. GetToken (false);
  6302. g_vecMinWorldspace[2] = verify_atof( token );
  6303. GetToken (false);
  6304. g_vecMaxWorldspace[0] = verify_atof( token );
  6305. GetToken (false);
  6306. g_vecMaxWorldspace[1] = verify_atof( token );
  6307. GetToken (false);
  6308. g_vecMaxWorldspace[2] = verify_atof( token );
  6309. }
  6310. //-----------------------------------------------------------------------------
  6311. // Key value block!
  6312. //-----------------------------------------------------------------------------
  6313. void Option_KeyValues( CUtlVector< char > *pKeyValue )
  6314. {
  6315. // Simply read in the block between { }s as text
  6316. // and plop it out unchanged into the .mdl file.
  6317. // Make sure to respect the fact that we may have nested {}s
  6318. int nLevel = 1;
  6319. if ( !GetToken( true ) )
  6320. return;
  6321. if ( token[0] != '{' )
  6322. return;
  6323. AppendKeyValueText( pKeyValue, "mdlkeyvalue\n{\n" );
  6324. while ( GetToken(true) )
  6325. {
  6326. if ( !stricmp( token, "}" ) )
  6327. {
  6328. nLevel--;
  6329. if ( nLevel <= 0 )
  6330. break;
  6331. AppendKeyValueText( pKeyValue, " }\n" );
  6332. }
  6333. else if ( !stricmp( token, "{" ) )
  6334. {
  6335. AppendKeyValueText( pKeyValue, "{\n" );
  6336. nLevel++;
  6337. }
  6338. else
  6339. {
  6340. // tokens inside braces are quoted
  6341. if ( nLevel > 1 )
  6342. {
  6343. AppendKeyValueText( pKeyValue, "\"" );
  6344. AppendKeyValueText( pKeyValue, token );
  6345. AppendKeyValueText( pKeyValue, "\" " );
  6346. }
  6347. else
  6348. {
  6349. AppendKeyValueText( pKeyValue, token );
  6350. AppendKeyValueText( pKeyValue, " " );
  6351. }
  6352. }
  6353. }
  6354. if ( nLevel >= 1 )
  6355. {
  6356. TokenError( "Keyvalue block missing matching braces.\n" );
  6357. }
  6358. AppendKeyValueText( pKeyValue, "}\n" );
  6359. }
  6360. //-----------------------------------------------------------------------------
  6361. // Purpose: force a specific parent child relationship
  6362. //-----------------------------------------------------------------------------
  6363. void Cmd_ForcedHierarchy( )
  6364. {
  6365. // child name
  6366. GetToken (false);
  6367. V_strcpy_safe( g_forcedhierarchy[g_numforcedhierarchy].childname, token );
  6368. // parent name
  6369. GetToken (false);
  6370. V_strcpy_safe( g_forcedhierarchy[g_numforcedhierarchy].parentname, token );
  6371. g_numforcedhierarchy++;
  6372. }
  6373. //-----------------------------------------------------------------------------
  6374. // Purpose: insert a virtual bone between a child and parent (currently unsupported)
  6375. //-----------------------------------------------------------------------------
  6376. void Cmd_InsertHierarchy( )
  6377. {
  6378. // child name
  6379. GetToken (false);
  6380. V_strcpy_safe( g_forcedhierarchy[g_numforcedhierarchy].childname, token );
  6381. // subparent name
  6382. GetToken (false);
  6383. V_strcpy_safe( g_forcedhierarchy[g_numforcedhierarchy].subparentname, token );
  6384. // parent name
  6385. GetToken (false);
  6386. V_strcpy_safe( g_forcedhierarchy[g_numforcedhierarchy].parentname, token );
  6387. g_numforcedhierarchy++;
  6388. }
  6389. //-----------------------------------------------------------------------------
  6390. // Purpose: rotate a specific bone
  6391. //-----------------------------------------------------------------------------
  6392. void Cmd_ForceRealign( )
  6393. {
  6394. // bone name
  6395. GetToken (false);
  6396. V_strcpy_safe( g_forcedrealign[g_numforcedrealign].name, token );
  6397. // skip
  6398. GetToken (false);
  6399. // X axis
  6400. GetToken (false);
  6401. g_forcedrealign[g_numforcedrealign].rot.x = DEG2RAD( verify_atof( token ) );
  6402. // Y axis
  6403. GetToken (false);
  6404. g_forcedrealign[g_numforcedrealign].rot.y = DEG2RAD( verify_atof( token ) );
  6405. // Z axis
  6406. GetToken (false);
  6407. g_forcedrealign[g_numforcedrealign].rot.z = DEG2RAD( verify_atof( token ) );
  6408. g_numforcedrealign++;
  6409. }
  6410. //-----------------------------------------------------------------------------
  6411. // Purpose: specify a bone to allow > 180 but < 360 rotation (forces a calculated "mid point" to rotation)
  6412. //-----------------------------------------------------------------------------
  6413. void Cmd_LimitRotation( )
  6414. {
  6415. // bone name
  6416. GetToken (false);
  6417. V_strcpy_safe( g_limitrotation[g_numlimitrotation].name, token );
  6418. while (TokenAvailable())
  6419. {
  6420. // sequence name
  6421. GetToken (false);
  6422. // This was a call to strcpyn but since sequencename is an array of char*
  6423. // it was passing sizeof(char*) as the number of characters to copy, which
  6424. // makes no sense. Commenting out until a better idea comes along.
  6425. Assert( 0 );
  6426. //V_strcpy_safe( g_limitrotation[g_numlimitrotation].sequencename[g_limitrotation[g_numlimitrotation].numseq++], token );
  6427. }
  6428. g_numlimitrotation++;
  6429. }
  6430. //-----------------------------------------------------------------------------
  6431. // Purpose: specify bones to store, even if nothing references them
  6432. //-----------------------------------------------------------------------------
  6433. void Cmd_DefineBone( )
  6434. {
  6435. // bone name
  6436. GetToken (false);
  6437. V_strcpy_safe( g_importbone[g_numimportbones].name, token );
  6438. // parent name
  6439. GetToken (false);
  6440. V_strcpy_safe( g_importbone[g_numimportbones].parent, token );
  6441. Vector pos;
  6442. QAngle angles;
  6443. // default pos
  6444. GetToken (false);
  6445. pos.x = verify_atof( token );
  6446. GetToken (false);
  6447. pos.y = verify_atof( token );
  6448. GetToken (false);
  6449. pos.z = verify_atof( token );
  6450. GetToken (false);
  6451. angles.x = verify_atof( token );
  6452. GetToken (false);
  6453. angles.y = verify_atof( token );
  6454. GetToken (false);
  6455. angles.z = verify_atof( token );
  6456. AngleMatrix( angles, pos, g_importbone[g_numimportbones].rawLocal );
  6457. if (TokenAvailable())
  6458. {
  6459. g_importbone[g_numimportbones].bPreAligned = true;
  6460. // realign pos
  6461. GetToken (false);
  6462. pos.x = verify_atof( token );
  6463. GetToken (false);
  6464. pos.y = verify_atof( token );
  6465. GetToken (false);
  6466. pos.z = verify_atof( token );
  6467. GetToken (false);
  6468. angles.x = verify_atof( token );
  6469. GetToken (false);
  6470. angles.y = verify_atof( token );
  6471. GetToken (false);
  6472. angles.z = verify_atof( token );
  6473. AngleMatrix( angles, pos, g_importbone[g_numimportbones].srcRealign );
  6474. }
  6475. else
  6476. {
  6477. SetIdentityMatrix( g_importbone[g_numimportbones].srcRealign );
  6478. }
  6479. g_numimportbones++;
  6480. }
  6481. //----------------------------------------------------------------------------------------------
  6482. float ParseJiggleStiffness( void )
  6483. {
  6484. if ( !GetToken( false ) )
  6485. {
  6486. MdlError( "$jigglebone: expecting stiffness value\n" );
  6487. return 0.0f;
  6488. }
  6489. float stiffness = verify_atof( token );
  6490. const float minStiffness = 0.0f;
  6491. const float maxStiffness = 1000.0f;
  6492. return clamp( stiffness, minStiffness, maxStiffness );
  6493. }
  6494. //----------------------------------------------------------------------------------------------
  6495. float ParseJiggleDamping( void )
  6496. {
  6497. if ( !GetToken( false ) )
  6498. {
  6499. MdlError( "$jigglebone: expecting damping value\n" );
  6500. return 0.0f;
  6501. }
  6502. float damping = verify_atof( token );
  6503. const float minDamping = 0.0f;
  6504. const float maxDamping = 10.0f;
  6505. return clamp( damping, minDamping, maxDamping );
  6506. }
  6507. //----------------------------------------------------------------------------------------------
  6508. bool ParseJiggleAngleConstraint( s_jigglebone_t *jiggleInfo )
  6509. {
  6510. jiggleInfo->data.flags |= JIGGLE_HAS_ANGLE_CONSTRAINT;
  6511. if ( !GetToken( false ) )
  6512. {
  6513. MdlError( "$jigglebone: expecting angle value\n" );
  6514. return false;
  6515. }
  6516. jiggleInfo->data.angleLimit = verify_atof( token ) * M_PI / 180.0f;
  6517. return true;
  6518. }
  6519. //----------------------------------------------------------------------------------------------
  6520. bool ParseJiggleYawConstraint( s_jigglebone_t *jiggleInfo )
  6521. {
  6522. jiggleInfo->data.flags |= JIGGLE_HAS_YAW_CONSTRAINT;
  6523. if ( !GetToken( false ) )
  6524. {
  6525. MdlError( "$jigglebone: expecting minimum yaw value\n" );
  6526. return false;
  6527. }
  6528. jiggleInfo->data.minYaw = verify_atof( token ) * M_PI / 180.0f;
  6529. if ( !GetToken( false ) )
  6530. {
  6531. MdlError( "$jigglebone: expecting maximum yaw value\n" );
  6532. return false;
  6533. }
  6534. jiggleInfo->data.maxYaw = verify_atof( token ) * M_PI / 180.0f;
  6535. return true;
  6536. }
  6537. //----------------------------------------------------------------------------------------------
  6538. bool ParseJigglePitchConstraint( s_jigglebone_t *jiggleInfo )
  6539. {
  6540. jiggleInfo->data.flags |= JIGGLE_HAS_PITCH_CONSTRAINT;
  6541. if ( !GetToken( false ) )
  6542. {
  6543. MdlError( "$jigglebone: expecting minimum pitch value\n" );
  6544. return false;
  6545. }
  6546. jiggleInfo->data.minPitch = verify_atof( token ) * M_PI / 180.0f;
  6547. if ( !GetToken( false ) )
  6548. {
  6549. MdlError( "$jigglebone: expecting maximum pitch value\n" );
  6550. return false;
  6551. }
  6552. jiggleInfo->data.maxPitch = verify_atof( token ) * M_PI / 180.0f;
  6553. return true;
  6554. }
  6555. //----------------------------------------------------------------------------------------------
  6556. /**
  6557. * Parse common parameters.
  6558. * This assumes a token has already been read, and returns true if
  6559. * the token is recognized and parsed.
  6560. */
  6561. bool ParseCommonJiggle( s_jigglebone_t *jiggleInfo )
  6562. {
  6563. if (!stricmp( token, "tip_mass" ))
  6564. {
  6565. if ( !GetToken( false ) )
  6566. {
  6567. return false;
  6568. }
  6569. jiggleInfo->data.tipMass = verify_atof( token );
  6570. }
  6571. else if (!stricmp( token, "length" ))
  6572. {
  6573. if ( !GetToken( false ) )
  6574. {
  6575. return false;
  6576. }
  6577. jiggleInfo->data.length = verify_atof( token );
  6578. }
  6579. else if (!stricmp( token, "angle_constraint" ))
  6580. {
  6581. if (ParseJiggleAngleConstraint( jiggleInfo ) == false)
  6582. {
  6583. return false;
  6584. }
  6585. }
  6586. else if (!stricmp( token, "yaw_constraint" ))
  6587. {
  6588. if (ParseJiggleYawConstraint( jiggleInfo ) == false)
  6589. {
  6590. return false;
  6591. }
  6592. }
  6593. else if (!stricmp( token, "yaw_friction" ))
  6594. {
  6595. if ( !GetToken( false ) )
  6596. {
  6597. return false;
  6598. }
  6599. jiggleInfo->data.yawFriction = verify_atof( token );
  6600. }
  6601. else if (!stricmp( token, "yaw_bounce" ))
  6602. {
  6603. if ( !GetToken( false ) )
  6604. {
  6605. return false;
  6606. }
  6607. jiggleInfo->data.yawBounce = verify_atof( token );
  6608. }
  6609. else if (!stricmp( token, "pitch_constraint" ))
  6610. {
  6611. if (ParseJigglePitchConstraint( jiggleInfo ) == false)
  6612. {
  6613. return false;
  6614. }
  6615. }
  6616. else if (!stricmp( token, "pitch_friction" ))
  6617. {
  6618. if ( !GetToken( false ) )
  6619. {
  6620. return false;
  6621. }
  6622. jiggleInfo->data.pitchFriction = verify_atof( token );
  6623. }
  6624. else if (!stricmp( token, "pitch_bounce" ))
  6625. {
  6626. if ( !GetToken( false ) )
  6627. {
  6628. return false;
  6629. }
  6630. jiggleInfo->data.pitchBounce = verify_atof( token );
  6631. }
  6632. else
  6633. {
  6634. // unknown token
  6635. MdlError( "$jigglebone: invalid syntax '%s'\n", token );
  6636. return false;
  6637. }
  6638. return true;
  6639. }
  6640. //----------------------------------------------------------------------------------------------
  6641. /**
  6642. * Parse parameters for is_flexible subsection
  6643. */
  6644. bool ParseFlexibleJiggle( s_jigglebone_t *jiggleInfo )
  6645. {
  6646. jiggleInfo->data.flags |= (JIGGLE_IS_FLEXIBLE | JIGGLE_HAS_LENGTH_CONSTRAINT);
  6647. bool gotOpenBracket = false;
  6648. while (true)
  6649. {
  6650. if (GetToken( true ) == false)
  6651. {
  6652. MdlError( "$jigglebone:is_flexible: parse error\n" );
  6653. return false;
  6654. }
  6655. if (!stricmp( token, "{" ))
  6656. {
  6657. gotOpenBracket = true;
  6658. }
  6659. else if (!gotOpenBracket)
  6660. {
  6661. MdlError( "$jigglebone:is_flexible: missing '{'\n" );
  6662. return false;
  6663. }
  6664. else if (!stricmp( token, "}" ))
  6665. {
  6666. // definition complete
  6667. break;
  6668. }
  6669. else if (!stricmp( token, "yaw_stiffness" ))
  6670. {
  6671. jiggleInfo->data.yawStiffness = ParseJiggleStiffness();
  6672. }
  6673. else if (!stricmp( token, "yaw_damping" ))
  6674. {
  6675. jiggleInfo->data.yawDamping = ParseJiggleStiffness();
  6676. }
  6677. else if (!stricmp( token, "pitch_stiffness" ))
  6678. {
  6679. jiggleInfo->data.pitchStiffness = ParseJiggleStiffness();
  6680. }
  6681. else if (!stricmp( token, "pitch_damping" ))
  6682. {
  6683. jiggleInfo->data.pitchDamping = ParseJiggleStiffness();
  6684. }
  6685. else if (!stricmp( token, "along_stiffness" ))
  6686. {
  6687. jiggleInfo->data.alongStiffness = ParseJiggleStiffness();
  6688. }
  6689. else if (!stricmp( token, "along_damping" ))
  6690. {
  6691. jiggleInfo->data.alongDamping = ParseJiggleStiffness();
  6692. }
  6693. else if (!stricmp( token, "allow_length_flex" ))
  6694. {
  6695. jiggleInfo->data.flags &= ~JIGGLE_HAS_LENGTH_CONSTRAINT;
  6696. }
  6697. else if (ParseCommonJiggle( jiggleInfo ) == false)
  6698. {
  6699. MdlError( "$jigglebone:is_flexible: invalid syntax '%s'\n", token );
  6700. return false;
  6701. }
  6702. }
  6703. return true;
  6704. }
  6705. //----------------------------------------------------------------------------------------------
  6706. /**
  6707. * Parse parameters for is_rigid subsection
  6708. */
  6709. bool ParseRigidJiggle( s_jigglebone_t *jiggleInfo )
  6710. {
  6711. jiggleInfo->data.flags |= (JIGGLE_IS_RIGID | JIGGLE_HAS_LENGTH_CONSTRAINT);
  6712. bool gotOpenBracket = false;
  6713. while (true)
  6714. {
  6715. if (GetToken( true ) == false)
  6716. {
  6717. MdlError( "$jigglebone:is_rigid: parse error\n" );
  6718. return false;
  6719. }
  6720. if (!stricmp( token, "{" ))
  6721. {
  6722. gotOpenBracket = true;
  6723. }
  6724. else if (!gotOpenBracket)
  6725. {
  6726. MdlError( "$jigglebone:is_rigid: missing '{'\n" );
  6727. return false;
  6728. }
  6729. else if (!stricmp( token, "}" ))
  6730. {
  6731. // definition complete
  6732. break;
  6733. }
  6734. else if (ParseCommonJiggle( jiggleInfo ) == false)
  6735. {
  6736. MdlError( "$jigglebone:is_rigid: invalid syntax '%s'\n", token );
  6737. return false;
  6738. }
  6739. }
  6740. return true;
  6741. }
  6742. //----------------------------------------------------------------------------------------------
  6743. /**
  6744. * Parse parameters for has_base_spring subsection
  6745. */
  6746. bool ParseBaseSpringJiggle( s_jigglebone_t *jiggleInfo )
  6747. {
  6748. jiggleInfo->data.flags |= JIGGLE_HAS_BASE_SPRING;
  6749. bool gotOpenBracket = false;
  6750. while (true)
  6751. {
  6752. if (GetToken( true ) == false)
  6753. {
  6754. MdlError( "$jigglebone:has_base_spring: parse error\n" );
  6755. return false;
  6756. }
  6757. if (!stricmp( token, "{" ))
  6758. {
  6759. gotOpenBracket = true;
  6760. }
  6761. else if (!gotOpenBracket)
  6762. {
  6763. MdlError( "$jigglebone:has_base_spring: missing '{'\n" );
  6764. return false;
  6765. }
  6766. else if (!stricmp( token, "}" ))
  6767. {
  6768. // definition complete
  6769. break;
  6770. }
  6771. else if (!stricmp( token, "stiffness" ))
  6772. {
  6773. jiggleInfo->data.baseStiffness = ParseJiggleStiffness();
  6774. }
  6775. else if (!stricmp( token, "damping" ))
  6776. {
  6777. jiggleInfo->data.baseDamping = ParseJiggleStiffness();
  6778. }
  6779. else if (!stricmp( token, "left_constraint" ))
  6780. {
  6781. if ( !GetToken( false ) )
  6782. {
  6783. return false;
  6784. }
  6785. jiggleInfo->data.baseMinLeft = verify_atof( token );
  6786. if ( !GetToken( false ) )
  6787. {
  6788. return false;
  6789. }
  6790. jiggleInfo->data.baseMaxLeft = verify_atof( token );
  6791. }
  6792. else if (!stricmp( token, "left_friction" ))
  6793. {
  6794. if ( !GetToken( false ) )
  6795. {
  6796. return false;
  6797. }
  6798. jiggleInfo->data.baseLeftFriction = verify_atof( token );
  6799. }
  6800. else if (!stricmp( token, "up_constraint" ))
  6801. {
  6802. if ( !GetToken( false ) )
  6803. {
  6804. return false;
  6805. }
  6806. jiggleInfo->data.baseMinUp = verify_atof( token );
  6807. if ( !GetToken( false ) )
  6808. {
  6809. return false;
  6810. }
  6811. jiggleInfo->data.baseMaxUp = verify_atof( token );
  6812. }
  6813. else if (!stricmp( token, "up_friction" ))
  6814. {
  6815. if ( !GetToken( false ) )
  6816. {
  6817. return false;
  6818. }
  6819. jiggleInfo->data.baseUpFriction = verify_atof( token );
  6820. }
  6821. else if (!stricmp( token, "forward_constraint" ))
  6822. {
  6823. if ( !GetToken( false ) )
  6824. {
  6825. return false;
  6826. }
  6827. jiggleInfo->data.baseMinForward = verify_atof( token );
  6828. if ( !GetToken( false ) )
  6829. {
  6830. return false;
  6831. }
  6832. jiggleInfo->data.baseMaxForward = verify_atof( token );
  6833. }
  6834. else if (!stricmp( token, "forward_friction" ))
  6835. {
  6836. if ( !GetToken( false ) )
  6837. {
  6838. return false;
  6839. }
  6840. jiggleInfo->data.baseForwardFriction = verify_atof( token );
  6841. }
  6842. else if (!stricmp( token, "base_mass" ))
  6843. {
  6844. if ( !GetToken( false ) )
  6845. {
  6846. return false;
  6847. }
  6848. jiggleInfo->data.baseMass = verify_atof( token );
  6849. }
  6850. else if (ParseCommonJiggle( jiggleInfo ) == false)
  6851. {
  6852. MdlError( "$jigglebone:has_base_spring: invalid syntax '%s'\n", token );
  6853. return false;
  6854. }
  6855. }
  6856. return true;
  6857. }
  6858. //----------------------------------------------------------------------------------------------
  6859. /**
  6860. * Parse parameters for is_boing subsection
  6861. */
  6862. bool ParseBoing( s_jigglebone_t *jiggleInfo )
  6863. {
  6864. jiggleInfo->data.flags |= JIGGLE_IS_BOING;
  6865. // default values
  6866. jiggleInfo->data.boingImpactSpeed = 100.0f;
  6867. jiggleInfo->data.boingImpactAngle = 0.7071f;
  6868. jiggleInfo->data.boingDampingRate = 0.25f;
  6869. jiggleInfo->data.boingFrequency = 30.0f;
  6870. jiggleInfo->data.boingAmplitude = 0.35f;
  6871. bool gotOpenBracket = false;
  6872. while ( true )
  6873. {
  6874. if ( GetToken( true ) == false )
  6875. {
  6876. MdlError( "$jigglebone:is_boing: parse error\n" );
  6877. return false;
  6878. }
  6879. if ( !stricmp( token, "{" ) )
  6880. {
  6881. gotOpenBracket = true;
  6882. }
  6883. else if ( !gotOpenBracket )
  6884. {
  6885. MdlError( "$jigglebone:is_boing: missing '{'\n" );
  6886. return false;
  6887. }
  6888. else if ( !stricmp( token, "}" ) )
  6889. {
  6890. // definition complete
  6891. break;
  6892. }
  6893. else if ( !stricmp( token, "impact_speed" ) )
  6894. {
  6895. if ( !GetToken( false ) )
  6896. {
  6897. return false;
  6898. }
  6899. jiggleInfo->data.boingImpactSpeed = verify_atof( token );
  6900. }
  6901. else if ( !stricmp( token, "impact_angle" ) )
  6902. {
  6903. if ( !GetToken( false ) )
  6904. {
  6905. return false;
  6906. }
  6907. jiggleInfo->data.boingImpactAngle = cos( DEG2RAD( verify_atof( token ) ) );
  6908. }
  6909. else if ( !stricmp( token, "damping_rate" ) )
  6910. {
  6911. if ( !GetToken( false ) )
  6912. {
  6913. return false;
  6914. }
  6915. jiggleInfo->data.boingDampingRate = verify_atof( token );
  6916. }
  6917. else if ( !stricmp( token, "frequency" ) )
  6918. {
  6919. if ( !GetToken( false ) )
  6920. {
  6921. return false;
  6922. }
  6923. jiggleInfo->data.boingFrequency = verify_atof( token );
  6924. }
  6925. else if ( !stricmp( token, "amplitude" ) )
  6926. {
  6927. if ( !GetToken( false ) )
  6928. {
  6929. return false;
  6930. }
  6931. jiggleInfo->data.boingAmplitude = verify_atof( token );
  6932. }
  6933. }
  6934. return true;
  6935. }
  6936. //----------------------------------------------------------------------------------------------
  6937. /**
  6938. * Parse $jigglebone parameters
  6939. */
  6940. void Cmd_JiggleBone( void )
  6941. {
  6942. struct s_jigglebone_t *jiggleInfo = &g_jigglebones[ g_numjigglebones ];
  6943. // bone name
  6944. GetToken( false );
  6945. V_strcpy_safe( jiggleInfo->bonename, token );
  6946. // default values
  6947. memset( &jiggleInfo->data, 0, sizeof( mstudiojigglebone_t ) );
  6948. jiggleInfo->data.length = 10.0f;
  6949. jiggleInfo->data.yawStiffness = 100.0f;
  6950. jiggleInfo->data.pitchStiffness = 100.0f;
  6951. jiggleInfo->data.alongStiffness = 100.0f;
  6952. jiggleInfo->data.baseStiffness = 100.0f;
  6953. jiggleInfo->data.baseMinUp = -100.0f;
  6954. jiggleInfo->data.baseMaxUp = 100.0f;
  6955. jiggleInfo->data.baseMinLeft = -100.0f;
  6956. jiggleInfo->data.baseMaxLeft = 100.0f;
  6957. jiggleInfo->data.baseMinForward = -100.0f;
  6958. jiggleInfo->data.baseMaxForward = 100.0f;
  6959. bool gotOpenBracket = false;
  6960. while (true)
  6961. {
  6962. if (GetToken( true ) == false)
  6963. {
  6964. MdlError( "$jigglebone: parse error\n" );
  6965. return;
  6966. }
  6967. if (!stricmp( token, "{" ))
  6968. {
  6969. gotOpenBracket = true;
  6970. }
  6971. else if (!gotOpenBracket)
  6972. {
  6973. MdlError( "$jigglebone: missing '{'\n" );
  6974. return;
  6975. }
  6976. else if (!stricmp( token, "}" ))
  6977. {
  6978. // definition complete
  6979. break;
  6980. }
  6981. else if (!stricmp( token, "is_flexible" ))
  6982. {
  6983. if (ParseFlexibleJiggle( jiggleInfo ) == false)
  6984. {
  6985. return;
  6986. }
  6987. }
  6988. else if (!stricmp( token, "is_rigid" ))
  6989. {
  6990. if (ParseRigidJiggle( jiggleInfo ) == false)
  6991. {
  6992. return;
  6993. }
  6994. }
  6995. else if (!stricmp( token, "has_base_spring" ))
  6996. {
  6997. if (ParseBaseSpringJiggle( jiggleInfo ) == false)
  6998. {
  6999. return;
  7000. }
  7001. }
  7002. else if ( !stricmp( token, "is_boing" ) )
  7003. {
  7004. if ( ParseBoing( jiggleInfo ) == false )
  7005. {
  7006. return;
  7007. }
  7008. }
  7009. else
  7010. {
  7011. MdlError( "$jigglebone: invalid syntax '%s'\n", token );
  7012. return;
  7013. }
  7014. }
  7015. if (!g_quiet)
  7016. Msg( "Marking bone %s as a jiggle bone\n", jiggleInfo->bonename );
  7017. g_numjigglebones++;
  7018. }
  7019. //-----------------------------------------------------------------------------
  7020. // Purpose: specify bones to store, even if nothing references them
  7021. //-----------------------------------------------------------------------------
  7022. void Cmd_IncludeModel( )
  7023. {
  7024. GetToken( false );
  7025. V_strcpy_safe( g_includemodel[g_numincludemodels].name, "models/" );
  7026. V_strcat_safe( g_includemodel[g_numincludemodels].name, token );
  7027. g_numincludemodels++;
  7028. }
  7029. /*
  7030. =================
  7031. =================
  7032. */
  7033. void Grab_Vertexanimation( s_source_t *psource, const char *pAnimName )
  7034. {
  7035. char cmd[1024];
  7036. int index;
  7037. Vector pos;
  7038. Vector normal;
  7039. int t = -1;
  7040. int count = 0;
  7041. static s_vertanim_t tmpvanim[MAXSTUDIOVERTS*4];
  7042. s_sourceanim_t *pAnim = FindSourceAnim( psource, pAnimName );
  7043. if ( !pAnim )
  7044. {
  7045. MdlError( "Unknown animation %s(%d) : %s\n", pAnimName, g_iLinecount, g_szLine );
  7046. }
  7047. while (GetLineInput())
  7048. {
  7049. if (sscanf( g_szLine, "%d %f %f %f %f %f %f", &index, &pos[0], &pos[1], &pos[2], &normal[0], &normal[1], &normal[2] ) == 7)
  7050. {
  7051. if ( pAnim->startframe < 0 )
  7052. {
  7053. MdlError( "Missing frame start(%d) : %s", g_iLinecount, g_szLine );
  7054. }
  7055. if (t < 0)
  7056. {
  7057. MdlError( "VTA Frame Sync (%d) : %s", g_iLinecount, g_szLine );
  7058. }
  7059. tmpvanim[count].vertex = index;
  7060. VectorCopy( pos, tmpvanim[count].pos );
  7061. VectorCopy( normal, tmpvanim[count].normal );
  7062. count++;
  7063. if ( index >= psource->numvertices )
  7064. {
  7065. psource->numvertices = index + 1;
  7066. }
  7067. }
  7068. else
  7069. {
  7070. // flush data
  7071. if (count)
  7072. {
  7073. pAnim->numvanims[t] = count;
  7074. pAnim->vanim[t] = (s_vertanim_t *)kalloc( count, sizeof( s_vertanim_t ) );
  7075. memcpy( pAnim->vanim[t], tmpvanim, count * sizeof( s_vertanim_t ) );
  7076. }
  7077. else if (t > 0)
  7078. {
  7079. pAnim->numvanims[t] = 0;
  7080. }
  7081. // next command
  7082. if (sscanf( g_szLine, "%1023s %d", cmd, &index ))
  7083. {
  7084. if (stricmp( cmd, "time" ) == 0)
  7085. {
  7086. t = index;
  7087. count = 0;
  7088. if ( t < pAnim->startframe )
  7089. {
  7090. MdlError( "Frame MdlError(%d) : %s", g_iLinecount, g_szLine );
  7091. }
  7092. if ( t > pAnim->endframe )
  7093. {
  7094. MdlError( "Frame MdlError(%d) : %s", g_iLinecount, g_szLine );
  7095. }
  7096. t -= pAnim->startframe;
  7097. }
  7098. else if ( !Q_stricmp( cmd, "end" ) )
  7099. {
  7100. pAnim->numframes = pAnim->endframe - pAnim->startframe + 1;
  7101. return;
  7102. }
  7103. else
  7104. {
  7105. MdlError( "MdlError(%d) : %s", g_iLinecount, g_szLine );
  7106. }
  7107. }
  7108. else
  7109. {
  7110. MdlError( "MdlError(%d) : %s", g_iLinecount, g_szLine );
  7111. }
  7112. }
  7113. }
  7114. MdlError( "unexpected EOF: %s\n", psource->filename );
  7115. }
  7116. bool GetGlobalFilePath( const char *pSrc, char *pFullPath, int nMaxLen )
  7117. {
  7118. char pFileName[1024];
  7119. Q_strncpy( pFileName, ExpandPath( (char*)pSrc ), sizeof(pFileName) );
  7120. // This is kinda gross. . . doing the same work in cmdlib on SafeOpenRead.
  7121. int nPathLength;
  7122. if( CmdLib_HasBasePath( pFileName, nPathLength ) )
  7123. {
  7124. char tmp[1024];
  7125. int i;
  7126. int nNumBasePaths = CmdLib_GetNumBasePaths();
  7127. for( i = 0; i < nNumBasePaths; i++ )
  7128. {
  7129. V_strcpy_safe( tmp, CmdLib_GetBasePath( i ) );
  7130. V_strcat_safe( tmp, pFileName + nPathLength );
  7131. struct _stat buf;
  7132. int rt = _stat( tmp, &buf );
  7133. if ( rt != -1 && ( buf.st_size > 0 ) && ( ( buf.st_mode & _S_IFDIR ) == 0 ) )
  7134. {
  7135. Q_strncpy( pFullPath, tmp, nMaxLen );
  7136. return true;
  7137. }
  7138. }
  7139. return false;
  7140. }
  7141. struct _stat buf;
  7142. int rt = _stat( pFileName, &buf );
  7143. if ( rt != -1 && ( buf.st_size > 0 ) && ( ( buf.st_mode & _S_IFDIR ) == 0 ) )
  7144. {
  7145. Q_strncpy( pFullPath, pFileName, nMaxLen );
  7146. return true;
  7147. }
  7148. return false;
  7149. }
  7150. int OpenGlobalFile( char *src )
  7151. {
  7152. int time1;
  7153. char filename[1024];
  7154. V_strcpy_safe( filename, ExpandPath( src ) );
  7155. int pathLength;
  7156. int numBasePaths = CmdLib_GetNumBasePaths();
  7157. // This is kinda gross. . . doing the same work in cmdlib on SafeOpenRead.
  7158. if( CmdLib_HasBasePath( filename, pathLength ) )
  7159. {
  7160. char tmp[1024];
  7161. int i;
  7162. for( i = 0; i < numBasePaths; i++ )
  7163. {
  7164. V_strcpy_safe( tmp, CmdLib_GetBasePath( i ) );
  7165. V_strcat_safe( tmp, filename + pathLength );
  7166. if( g_bCreateMakefile )
  7167. {
  7168. CreateMakefile_AddDependency( tmp );
  7169. return 0;
  7170. }
  7171. time1 = FileTime( tmp );
  7172. if( time1 != -1 )
  7173. {
  7174. if ((g_fpInput = fopen(tmp, "r" ) ) == 0)
  7175. {
  7176. MdlWarning( "reader: could not open file '%s'\n", src );
  7177. return 0;
  7178. }
  7179. else
  7180. {
  7181. return 1;
  7182. }
  7183. }
  7184. }
  7185. return 0;
  7186. }
  7187. else
  7188. {
  7189. time1 = FileTime (filename);
  7190. if (time1 == -1)
  7191. return 0;
  7192. if( g_bCreateMakefile )
  7193. {
  7194. CreateMakefile_AddDependency( filename );
  7195. return 0;
  7196. }
  7197. if ((g_fpInput = fopen(filename, "r" ) ) == 0)
  7198. {
  7199. MdlWarning( "reader: could not open file '%s'\n", src );
  7200. return 0;
  7201. }
  7202. return 1;
  7203. }
  7204. }
  7205. int Load_VTA( s_source_t *psource )
  7206. {
  7207. char cmd[1024];
  7208. int option;
  7209. if (!OpenGlobalFile( psource->filename ))
  7210. return 0;
  7211. if (!g_quiet)
  7212. printf ("VTA MODEL %s\n", psource->filename);
  7213. g_iLinecount = 0;
  7214. while (GetLineInput())
  7215. {
  7216. g_iLinecount++;
  7217. sscanf( g_szLine, "%s %d", cmd, &option );
  7218. if (stricmp( cmd, "version" ) == 0)
  7219. {
  7220. if (option != 1)
  7221. {
  7222. MdlError("bad version\n");
  7223. }
  7224. }
  7225. else if (stricmp( cmd, "nodes" ) == 0)
  7226. {
  7227. psource->numbones = Grab_Nodes( psource->localBone );
  7228. }
  7229. else if (stricmp( cmd, "skeleton" ) == 0)
  7230. {
  7231. Grab_Animation( psource, "VertexAnimation" );
  7232. }
  7233. else if (stricmp( cmd, "vertexanimation" ) == 0)
  7234. {
  7235. Grab_Vertexanimation( psource, "VertexAnimation" );
  7236. }
  7237. else
  7238. {
  7239. MdlWarning("unknown studio command \"%s\"\n", cmd );
  7240. }
  7241. }
  7242. fclose( g_fpInput );
  7243. return 1;
  7244. }
  7245. void Grab_AxisInterpBones( )
  7246. {
  7247. char cmd[1024], tmp[1025];
  7248. Vector basepos;
  7249. s_axisinterpbone_t *pAxis = NULL;
  7250. s_axisinterpbone_t *pBone = &g_axisinterpbones[g_numaxisinterpbones];
  7251. while (GetLineInput())
  7252. {
  7253. if (IsEnd( g_szLine ))
  7254. {
  7255. return;
  7256. }
  7257. int i = sscanf( g_szLine, "%1023s \"%[^\"]\" \"%[^\"]\" \"%[^\"]\" \"%[^\"]\" %d", cmd, pBone->bonename, tmp, pBone->controlname, tmp, &pBone->axis );
  7258. if (i == 6 && stricmp( cmd, "bone") == 0)
  7259. {
  7260. // printf( "\"%s\" \"%s\" \"%s\" \"%s\"\n", cmd, pBone->bonename, tmp, pBone->controlname );
  7261. pAxis = pBone;
  7262. pBone->axis = pBone->axis - 1; // MAX uses 1..3, engine 0..2
  7263. g_numaxisinterpbones++;
  7264. pBone = &g_axisinterpbones[g_numaxisinterpbones];
  7265. }
  7266. else if (stricmp( cmd, "display" ) == 0)
  7267. {
  7268. // skip all display info
  7269. }
  7270. else if (stricmp( cmd, "type" ) == 0)
  7271. {
  7272. // skip all type info
  7273. }
  7274. else if (stricmp( cmd, "basepos" ) == 0)
  7275. {
  7276. i = sscanf( g_szLine, "basepos %f %f %f", &basepos.x, &basepos.y, &basepos.z );
  7277. // skip all type info
  7278. }
  7279. else if (stricmp( cmd, "axis" ) == 0)
  7280. {
  7281. Vector pos;
  7282. QAngle rot;
  7283. int j;
  7284. i = sscanf( g_szLine, "axis %d %f %f %f %f %f %f", &j, &pos[0], &pos[1], &pos[2], &rot[2], &rot[0], &rot[1] );
  7285. if (i == 7)
  7286. {
  7287. VectorAdd( basepos, pos, pAxis->pos[j] );
  7288. AngleQuaternion( rot, pAxis->quat[j] );
  7289. }
  7290. }
  7291. }
  7292. }
  7293. bool Grab_AimAtBones( )
  7294. {
  7295. s_aimatbone_t *pAimAtBone( &g_aimatbones[g_numaimatbones] );
  7296. // Already know it's <aimconstraint> in the first string, otherwise wouldn't be here
  7297. if ( sscanf( g_szLine, "%*s %127s %127s %127s", pAimAtBone->bonename, pAimAtBone->parentname, pAimAtBone->aimname ) == 3 )
  7298. {
  7299. g_numaimatbones++;
  7300. char cmd[1024];
  7301. Vector vector;
  7302. while ( GetLineInput() )
  7303. {
  7304. g_iLinecount++;
  7305. if (IsEnd( g_szLine ))
  7306. {
  7307. return false;
  7308. }
  7309. if ( sscanf( g_szLine, "%1024s %f %f %f", cmd, &vector[0], &vector[1], &vector[2] ) != 4 )
  7310. {
  7311. // Allow blank lines to be skipped without error
  7312. bool allSpace( true );
  7313. for ( const char *pC( g_szLine ); *pC != '\0' && pC < ( g_szLine + 4096 ); ++pC )
  7314. {
  7315. if ( !V_isspace( *pC ) )
  7316. {
  7317. allSpace = false;
  7318. break;
  7319. }
  7320. }
  7321. if ( allSpace )
  7322. {
  7323. continue;
  7324. }
  7325. return true;
  7326. }
  7327. if ( stricmp( cmd, "<aimvector>" ) == 0)
  7328. {
  7329. // Make sure these are unit length on read
  7330. VectorNormalize( vector );
  7331. pAimAtBone->aimvector = vector;
  7332. }
  7333. else if ( stricmp( cmd, "<upvector>" ) == 0)
  7334. {
  7335. // Make sure these are unit length on read
  7336. VectorNormalize( vector );
  7337. pAimAtBone->upvector = vector;
  7338. }
  7339. else if ( stricmp( cmd, "<basepos>" ) == 0)
  7340. {
  7341. pAimAtBone->basepos = vector;
  7342. }
  7343. else
  7344. {
  7345. return true;
  7346. }
  7347. }
  7348. }
  7349. // If we get here, we're at EOF
  7350. return false;
  7351. }
  7352. void Grab_QuatInterpBones( )
  7353. {
  7354. char cmd[1024];
  7355. Vector basepos;
  7356. RadianEuler rotateaxis( 0.0f, 0.0f, 0.0f );
  7357. RadianEuler jointorient( 0.0f, 0.0f, 0.0f );
  7358. s_quatinterpbone_t *pAxis = NULL;
  7359. s_quatinterpbone_t *pBone = &g_quatinterpbones[g_numquatinterpbones];
  7360. while (GetLineInput())
  7361. {
  7362. g_iLinecount++;
  7363. if (IsEnd( g_szLine ))
  7364. {
  7365. return;
  7366. }
  7367. int i = sscanf( g_szLine, "%s %s %s %s %s", cmd, pBone->bonename, pBone->parentname, pBone->controlparentname, pBone->controlname );
  7368. while ( i == 4 && stricmp( cmd, "<aimconstraint>" ) == 0 )
  7369. {
  7370. // If Grab_AimAtBones() returns false, there file is at EOF
  7371. if ( !Grab_AimAtBones() )
  7372. {
  7373. return;
  7374. }
  7375. // Grab_AimAtBones will read input into g_szLine same as here until it gets a line it doesn't understand, at which point
  7376. // it will exit leaving that line in g_szLine, so check for the end and scan the current buffer again and continue on with
  7377. // the normal QuatInterpBones process
  7378. i = sscanf( g_szLine, "%s %s %s %s %s", cmd, pBone->bonename, pBone->parentname, pBone->controlparentname, pBone->controlname );
  7379. }
  7380. if (i == 5 && stricmp( cmd, "<helper>") == 0)
  7381. {
  7382. // printf( "\"%s\" \"%s\" \"%s\" \"%s\"\n", cmd, pBone->bonename, tmp, pBone->controlname );
  7383. pAxis = pBone;
  7384. g_numquatinterpbones++;
  7385. pBone = &g_quatinterpbones[g_numquatinterpbones];
  7386. }
  7387. else if ( i > 0 )
  7388. {
  7389. // There was a bug before which could cause the same command to be parsed twice
  7390. // because if the sscanf above completely fails, it will return 0 and not
  7391. // change the contents of cmd, so i should be greater than 0 in order for
  7392. // any of these checks to be valid... Still kind of buggy as these checks
  7393. // do case insensitive stricmp but then the sscanf does case sensitive
  7394. // matching afterwards... Should probably change those to
  7395. // sscanf( g_szLine, "%*s %f ... ) etc...
  7396. if ( stricmp( cmd, "<display>" ) == 0)
  7397. {
  7398. // skip all display info
  7399. Vector size;
  7400. float distance;
  7401. i = sscanf( g_szLine, "<display> %f %f %f %f",
  7402. &size[0], &size[1], &size[2],
  7403. &distance );
  7404. if (i == 4)
  7405. {
  7406. pAxis->percentage = distance / 100.0;
  7407. pAxis->size = size;
  7408. }
  7409. else
  7410. {
  7411. MdlError( "Line %d: Unable to parse procedual <display> bone: %s", g_iLinecount, g_szLine );
  7412. }
  7413. }
  7414. else if ( stricmp( cmd, "<basepos>" ) == 0)
  7415. {
  7416. i = sscanf( g_szLine, "<basepos> %f %f %f", &basepos.x, &basepos.y, &basepos.z );
  7417. // skip all type info
  7418. }
  7419. else if ( stricmp( cmd, "<rotateaxis>" ) == 0)
  7420. {
  7421. i = sscanf( g_szLine, "%*s %f %f %f", &rotateaxis.x, &rotateaxis.y, &rotateaxis.z );
  7422. rotateaxis.x = DEG2RAD( rotateaxis.x );
  7423. rotateaxis.y = DEG2RAD( rotateaxis.y );
  7424. rotateaxis.z = DEG2RAD( rotateaxis.z );
  7425. }
  7426. else if ( stricmp( cmd, "<jointorient>" ) == 0)
  7427. {
  7428. i = sscanf( g_szLine, "%*s %f %f %f", &jointorient.x, &jointorient.y, &jointorient.z );
  7429. jointorient.x = DEG2RAD( jointorient.x );
  7430. jointorient.y = DEG2RAD( jointorient.y );
  7431. jointorient.z = DEG2RAD( jointorient.z );
  7432. }
  7433. else if ( stricmp( cmd, "<trigger>" ) == 0)
  7434. {
  7435. float tolerance;
  7436. RadianEuler trigger;
  7437. Vector pos;
  7438. RadianEuler ang;
  7439. QAngle rot;
  7440. int j;
  7441. i = sscanf( g_szLine, "<trigger> %f %f %f %f %f %f %f %f %f %f",
  7442. &tolerance,
  7443. &trigger.x, &trigger.y, &trigger.z,
  7444. &ang.x, &ang.y, &ang.z,
  7445. &pos.x, &pos.y, &pos.z );
  7446. if (i == 10)
  7447. {
  7448. trigger.x = DEG2RAD( trigger.x );
  7449. trigger.y = DEG2RAD( trigger.y );
  7450. trigger.z = DEG2RAD( trigger.z );
  7451. ang.x = DEG2RAD( ang.x );
  7452. ang.y = DEG2RAD( ang.y );
  7453. ang.z = DEG2RAD( ang.z );
  7454. Quaternion q;
  7455. AngleQuaternion( ang, q );
  7456. if ( rotateaxis.x != 0.0 || rotateaxis.y != 0.0 || rotateaxis.z != 0.0 )
  7457. {
  7458. Quaternion q1;
  7459. Quaternion q2;
  7460. AngleQuaternion( rotateaxis, q1 );
  7461. QuaternionMult( q1, q, q2 );
  7462. q = q2;
  7463. }
  7464. if ( jointorient.x != 0.0 || jointorient.y != 0.0 || jointorient.z != 0.0 )
  7465. {
  7466. Quaternion q1;
  7467. Quaternion q2;
  7468. AngleQuaternion( jointorient, q1 );
  7469. QuaternionMult( q, q1, q2 );
  7470. q = q2;
  7471. }
  7472. j = pAxis->numtriggers++;
  7473. pAxis->tolerance[j] = DEG2RAD( tolerance );
  7474. AngleQuaternion( trigger, pAxis->trigger[j] );
  7475. VectorAdd( basepos, pos, pAxis->pos[j] );
  7476. pAxis->quat[j] = q;
  7477. }
  7478. else
  7479. {
  7480. MdlError( "Line %d: Unable to parse procedual <trigger> bone: %s", g_iLinecount, g_szLine );
  7481. }
  7482. }
  7483. else
  7484. {
  7485. MdlError( "Line %d: Unable to parse procedual bone data: %s", g_iLinecount, g_szLine );
  7486. }
  7487. }
  7488. else
  7489. {
  7490. // Allow blank lines to be skipped without error
  7491. bool allSpace( true );
  7492. for ( const char *pC( g_szLine ); *pC != '\0' && pC < ( g_szLine + 4096 ); ++pC )
  7493. {
  7494. if ( !V_isspace( *pC ) )
  7495. {
  7496. allSpace = false;
  7497. break;
  7498. }
  7499. }
  7500. if ( !allSpace )
  7501. {
  7502. MdlError( "Line %d: Unable to parse procedual bone data: %s", g_iLinecount, g_szLine );
  7503. }
  7504. }
  7505. }
  7506. }
  7507. void Load_ProceduralBones( )
  7508. {
  7509. char filename[256];
  7510. char cmd[1024];
  7511. int option;
  7512. GetToken( false );
  7513. V_strcpy_safe( filename, token );
  7514. if (!OpenGlobalFile( filename ))
  7515. return;
  7516. g_iLinecount = 0;
  7517. char ext[32];
  7518. Q_ExtractFileExtension( filename, ext, sizeof( ext ) );
  7519. if (stricmp( ext, "vrd") == 0)
  7520. {
  7521. Grab_QuatInterpBones( );
  7522. }
  7523. else
  7524. {
  7525. while (GetLineInput())
  7526. {
  7527. g_iLinecount++;
  7528. sscanf( g_szLine, "%s %d", cmd, &option );
  7529. if (stricmp( cmd, "version" ) == 0)
  7530. {
  7531. if (option != 1)
  7532. {
  7533. MdlError("bad version\n");
  7534. }
  7535. }
  7536. else if (stricmp( cmd, "proceduralbones" ) == 0)
  7537. {
  7538. Grab_AxisInterpBones( );
  7539. }
  7540. }
  7541. }
  7542. fclose( g_fpInput );
  7543. }
  7544. void Cmd_CD()
  7545. {
  7546. if (cdset)
  7547. MdlError ("Two $cd in one model");
  7548. cdset = true;
  7549. GetToken (false);
  7550. V_strcpy_safe (cddir[0], token);
  7551. V_strcat_safe (cddir[0], "/" );
  7552. numdirs = 0;
  7553. }
  7554. void Cmd_CDMaterials()
  7555. {
  7556. while (TokenAvailable())
  7557. {
  7558. GetToken (false);
  7559. char szPath[512];
  7560. Q_strncpy( szPath, token, sizeof( szPath ) );
  7561. int len = strlen( szPath );
  7562. if ( len > 0 && szPath[len-1] != '/' && szPath[len-1] != '\\' )
  7563. {
  7564. Q_strncat( szPath, "/", sizeof( szPath ), COPY_ALL_CHARACTERS );
  7565. }
  7566. Q_FixSlashes( szPath );
  7567. cdtextures[numcdtextures] = strdup( szPath );
  7568. numcdtextures++;
  7569. }
  7570. }
  7571. void Cmd_Pushd()
  7572. {
  7573. GetToken(false);
  7574. V_strcpy_safe( cddir[numdirs+1], cddir[numdirs] );
  7575. V_strcat_safe( cddir[numdirs+1], token );
  7576. V_strcat_safe( cddir[numdirs+1], "/" );
  7577. numdirs++;
  7578. }
  7579. void Cmd_Popd()
  7580. {
  7581. if (numdirs > 0)
  7582. numdirs--;
  7583. }
  7584. void Cmd_CollisionModel()
  7585. {
  7586. DoCollisionModel( false );
  7587. }
  7588. void Cmd_CollisionJoints()
  7589. {
  7590. DoCollisionModel( true );
  7591. }
  7592. void Cmd_ExternalTextures()
  7593. {
  7594. MdlWarning( "ignoring $externaltextures, obsolete..." );
  7595. }
  7596. void Cmd_ClipToTextures()
  7597. {
  7598. clip_texcoords = 1;
  7599. }
  7600. void Cmd_CollapseBones()
  7601. {
  7602. g_collapse_bones = true;
  7603. }
  7604. void Cmd_CollapseBonesAggressive()
  7605. {
  7606. g_collapse_bones = true;
  7607. g_collapse_bones_aggressive = true;
  7608. }
  7609. void Cmd_AlwaysCollapse()
  7610. {
  7611. g_collapse_bones = true;
  7612. GetToken(false);
  7613. g_collapse.AddToTail( strdup( token ) );
  7614. }
  7615. void Cmd_CalcTransitions()
  7616. {
  7617. g_bMultistageGraph = true;
  7618. }
  7619. void Cmd_StaticProp()
  7620. {
  7621. g_staticprop = true;
  7622. gflags |= STUDIOHDR_FLAGS_STATIC_PROP;
  7623. }
  7624. void Cmd_ZBrush()
  7625. {
  7626. g_bZBrush = true;
  7627. }
  7628. void Cmd_RealignBones()
  7629. {
  7630. g_realignbones = true;
  7631. }
  7632. void Cmd_BaseLOD()
  7633. {
  7634. Cmd_LOD( "$lod" );
  7635. }
  7636. void Cmd_KeyValues()
  7637. {
  7638. Option_KeyValues( &g_KeyValueText );
  7639. }
  7640. void Cmd_ConstDirectionalLight()
  7641. {
  7642. gflags |= STUDIOHDR_FLAGS_CONSTANT_DIRECTIONAL_LIGHT_DOT;
  7643. GetToken (false);
  7644. g_constdirectionalightdot = (byte)( verify_atof(token) * 255.0f );
  7645. }
  7646. void Cmd_MinLOD()
  7647. {
  7648. GetToken( false );
  7649. g_minLod = atoi( token );
  7650. // "minlod" rules over "allowrootlods"
  7651. if ( g_numAllowedRootLODs > 0 && g_numAllowedRootLODs < g_minLod )
  7652. {
  7653. MdlWarning( "$minlod %d overrides $allowrootlods %d, proceeding with $allowrootlods %d.\n", g_minLod, g_numAllowedRootLODs, g_minLod );
  7654. g_numAllowedRootLODs = g_minLod;
  7655. }
  7656. }
  7657. void Cmd_AllowRootLODs()
  7658. {
  7659. GetToken( false );
  7660. g_numAllowedRootLODs = atoi( token );
  7661. // Root LOD restriction has to obey "minlod" request
  7662. if ( g_numAllowedRootLODs > 0 && g_numAllowedRootLODs < g_minLod )
  7663. {
  7664. MdlWarning( "$allowrootlods %d is conflicting with $minlod %d, proceeding with $allowrootlods %d.\n", g_numAllowedRootLODs, g_minLod, g_minLod );
  7665. g_numAllowedRootLODs = g_minLod;
  7666. }
  7667. }
  7668. void Cmd_BoneSaveFrame( )
  7669. {
  7670. s_bonesaveframe_t tmp;
  7671. // bone name
  7672. GetToken( false );
  7673. V_strcpy_safe( tmp.name, token );
  7674. tmp.bSavePos = false;
  7675. tmp.bSaveRot = false;
  7676. while (TokenAvailable( ))
  7677. {
  7678. GetToken( false );
  7679. if (stricmp( "position", token ) == 0)
  7680. {
  7681. tmp.bSavePos = true;
  7682. }
  7683. else if (stricmp( "rotation", token ) == 0)
  7684. {
  7685. tmp.bSaveRot = true;
  7686. }
  7687. else
  7688. {
  7689. MdlError( "unknown option \"%s\" on $bonesaveframe : %s\n", token, tmp.name );
  7690. }
  7691. }
  7692. g_bonesaveframe.AddToTail( tmp );
  7693. }
  7694. //
  7695. // This is the master list of the commands a QC file supports.
  7696. // To add a new command to the QC files, add it here.
  7697. //
  7698. struct
  7699. {
  7700. char *m_pName;
  7701. void (*m_pCmd)();
  7702. } g_Commands[] =
  7703. {
  7704. { "$cd", Cmd_CD },
  7705. { "$modelname", Cmd_Modelname },
  7706. { "$cdmaterials", Cmd_CDMaterials },
  7707. { "$pushd", Cmd_Pushd },
  7708. { "$popd", Cmd_Popd },
  7709. { "$scale", Cmd_ScaleUp },
  7710. { "$root", Cmd_Root },
  7711. { "$controller", Cmd_Controller },
  7712. { "$screenalign", Cmd_ScreenAlign },
  7713. { "$model", Cmd_Model },
  7714. { "$collisionmodel", Cmd_CollisionModel },
  7715. { "$collisionjoints", Cmd_CollisionJoints },
  7716. { "$collisiontext", Cmd_CollisionText },
  7717. { "$body", Cmd_Body },
  7718. { "$bodygroup", Cmd_Bodygroup },
  7719. { "$animation", Cmd_Animation },
  7720. { "$autocenter", Cmd_Autocenter },
  7721. { "$sequence", Cmd_Sequence },
  7722. { "$append", Cmd_Append },
  7723. { "$prepend", Cmd_Prepend },
  7724. { "$continue", Cmd_Continue },
  7725. { "$declaresequence", Cmd_DeclareSequence },
  7726. { "$declareanimation", Cmd_DeclareAnimation },
  7727. { "$cmdlist", Cmd_Cmdlist },
  7728. { "$animblocksize", Cmd_AnimBlockSize },
  7729. { "$weightlist", Cmd_Weightlist },
  7730. { "$defaultweightlist", Cmd_DefaultWeightlist },
  7731. { "$ikchain", Cmd_IKChain },
  7732. { "$ikautoplaylock", Cmd_IKAutoplayLock },
  7733. { "$eyeposition", Cmd_Eyeposition },
  7734. { "$illumposition", Cmd_Illumposition },
  7735. { "$origin", Cmd_Origin },
  7736. { "$upaxis", Cmd_UpAxis },
  7737. { "$bbox", Cmd_BBox },
  7738. { "$cbox", Cmd_CBox },
  7739. { "$gamma", Cmd_Gamma },
  7740. { "$texturegroup", Cmd_TextureGroup },
  7741. { "$hgroup", Cmd_Hitgroup },
  7742. { "$hbox", Cmd_Hitbox },
  7743. { "$hboxset", Cmd_HitboxSet },
  7744. { "$surfaceprop", Cmd_SurfaceProp },
  7745. { "$jointsurfaceprop", Cmd_JointSurfaceProp },
  7746. { "$contents", Cmd_Contents },
  7747. { "$jointcontents", Cmd_JointContents },
  7748. { "$attachment", Cmd_Attachment },
  7749. { "$bonemerge", Cmd_BoneMerge },
  7750. { "$externaltextures", Cmd_ExternalTextures },
  7751. { "$cliptotextures", Cmd_ClipToTextures },
  7752. { "$renamebone", Cmd_Renamebone },
  7753. { "$collapsebones", Cmd_CollapseBones },
  7754. { "$collapsebonesaggressive", Cmd_CollapseBonesAggressive },
  7755. { "$alwayscollapse", Cmd_AlwaysCollapse },
  7756. { "$proceduralbones", Load_ProceduralBones },
  7757. { "$skiptransition", Cmd_Skiptransition },
  7758. { "$calctransitions", Cmd_CalcTransitions },
  7759. { "$staticprop", Cmd_StaticProp },
  7760. { "$zbrush", Cmd_ZBrush },
  7761. { "$realignbones", Cmd_RealignBones },
  7762. { "$forcerealign", Cmd_ForceRealign },
  7763. { "$lod", Cmd_BaseLOD },
  7764. { "$shadowlod", Cmd_ShadowLOD },
  7765. { "$poseparameter", Cmd_PoseParameter },
  7766. { "$heirarchy", Cmd_ForcedHierarchy },
  7767. { "$hierarchy", Cmd_ForcedHierarchy },
  7768. { "$insertbone", Cmd_InsertHierarchy },
  7769. { "$limitrotation", Cmd_LimitRotation },
  7770. { "$definebone", Cmd_DefineBone },
  7771. { "$jigglebone", Cmd_JiggleBone },
  7772. { "$includemodel", Cmd_IncludeModel },
  7773. { "$opaque", Cmd_Opaque },
  7774. { "$mostlyopaque", Cmd_TranslucentTwoPass },
  7775. // { "$platform", Cmd_Platform },
  7776. { "$keyvalues", Cmd_KeyValues },
  7777. { "$obsolete", Cmd_Obsolete },
  7778. { "$renamematerial", Cmd_RenameMaterial },
  7779. { "$fakevta", Cmd_FakeVTA },
  7780. { "$noforcedfade", Cmd_NoForcedFade },
  7781. { "$skipboneinbbox", Cmd_SkipBoneInBBox },
  7782. { "$forcephonemecrossfade", Cmd_ForcePhonemeCrossfade },
  7783. { "$lockbonelengths", Cmd_LockBoneLengths },
  7784. { "$unlockdefinebones", Cmd_UnlockDefineBones },
  7785. { "$constantdirectionallight", Cmd_ConstDirectionalLight },
  7786. { "$minlod", Cmd_MinLOD },
  7787. { "$allowrootlods", Cmd_AllowRootLODs },
  7788. { "$bonesaveframe", Cmd_BoneSaveFrame },
  7789. { "$ambientboost", Cmd_AmbientBoost },
  7790. { "$centerbonesonverts", Cmd_CenterBonesOnVerts },
  7791. { "$donotcastshadows", Cmd_DoNotCastShadows },
  7792. { "$casttextureshadows", Cmd_CastTextureShadows },
  7793. { "$motionrollback", Cmd_MotionExtractionRollBack },
  7794. { "$sectionframes", Cmd_SectionFrames },
  7795. { "$clampworldspace", Cmd_ClampWorldspace },
  7796. { "$maxeyedeflection", Cmd_MaxEyeDeflection },
  7797. { "$boneflexdriver", Cmd_BoneFlexDriver },
  7798. { "$checkuv", Cmd_CheckUV }
  7799. };
  7800. /*
  7801. ===============
  7802. ParseScript
  7803. ===============
  7804. */
  7805. void ParseScript (void)
  7806. {
  7807. while (1)
  7808. {
  7809. GetToken (true);
  7810. if (endofscript)
  7811. return;
  7812. // Check all the commands we know about.
  7813. int i;
  7814. for ( i=0; i < ARRAYSIZE( g_Commands ); i++ )
  7815. {
  7816. if ( !stricmp( g_Commands[i].m_pName, token ) )
  7817. {
  7818. g_Commands[i].m_pCmd();
  7819. break;
  7820. }
  7821. }
  7822. if ( i == ARRAYSIZE( g_Commands ) )
  7823. {
  7824. if( !g_bCreateMakefile )
  7825. {
  7826. TokenError("bad command %s\n", token);
  7827. }
  7828. }
  7829. }
  7830. }
  7831. //-----------------------------------------------------------------------------
  7832. // Generate the model name
  7833. //-----------------------------------------------------------------------------
  7834. bool GenerateModelName( CDmeMDLMakefile *pMDLMakeFile )
  7835. {
  7836. // The model name is implicit in the makefile name
  7837. // NOTE: Model name is relative to the 'models' directory
  7838. char pOutputFullPath[MAX_PATH];
  7839. pMDLMakeFile->GetOutputName( pOutputFullPath, sizeof(pOutputFullPath) );
  7840. Q_SetExtension( pOutputFullPath, ".mdl", sizeof( pOutputFullPath) );
  7841. char pModelSubDir[MAX_PATH];
  7842. GetModSubdirectory( "models", pModelSubDir, sizeof(pModelSubDir) );
  7843. char pRelativePath[MAX_PATH];
  7844. if ( !Q_MakeRelativePath( pOutputFullPath, pModelSubDir, pRelativePath, sizeof(pRelativePath) ) )
  7845. {
  7846. MdlError( "Makefile \"%s\" doesn't lie under the correct vproject \"%s\"!\n",
  7847. pOutputFullPath, pModelSubDir );
  7848. return false;
  7849. }
  7850. ProcessModelName( pRelativePath );
  7851. return true;
  7852. }
  7853. //-----------------------------------------------------------------------------
  7854. // Process skins
  7855. //-----------------------------------------------------------------------------
  7856. bool GenerateSkin( CDmeMDLMakefile *pMDLMakeFile )
  7857. {
  7858. CUtlVector< CDmeHandle< CDmeSourceSkin > > bodies;
  7859. pMDLMakeFile->GetSources< CDmeSourceSkin >( bodies );
  7860. int nCount = bodies.Count();
  7861. for ( int i = 0; i < nCount; ++i )
  7862. {
  7863. if ( !bodies[i] )
  7864. continue;
  7865. char pFullPath[MAX_PATH];
  7866. pMDLMakeFile->GetSourceFullPath( bodies[i], pFullPath, sizeof(pFullPath) );
  7867. // Empty strings are ignored
  7868. if ( !pFullPath[0] )
  7869. continue;
  7870. ProcessCmdBody( pFullPath, bodies[i] );
  7871. }
  7872. return true;
  7873. }
  7874. //-----------------------------------------------------------------------------
  7875. // Process animations
  7876. //-----------------------------------------------------------------------------
  7877. bool GenerateAnimations( CDmeMDLMakefile *pMDLMakeFile )
  7878. {
  7879. CUtlVector< CDmeHandle< CDmeSourceAnimation > > animationFiles;
  7880. pMDLMakeFile->GetSources< CDmeSourceAnimation >( animationFiles );
  7881. int nCount = animationFiles.Count();
  7882. for ( int i = 0; i < nCount; ++i )
  7883. {
  7884. if ( !animationFiles[i] )
  7885. continue;
  7886. char pFullPath[MAX_PATH];
  7887. pMDLMakeFile->GetSourceFullPath( animationFiles[i], pFullPath, sizeof(pFullPath) );
  7888. // Empty strings are ignored
  7889. if ( !pFullPath[0] )
  7890. continue;
  7891. // Totally spoof the animation info.. not sure where to get it from yet
  7892. // assume it's an animation reference
  7893. // first look up an existing animation
  7894. s_sequence_t *pseq = ProcessCmdSequence( animationFiles[i]->m_AnimationName );
  7895. if ( !pseq )
  7896. continue;
  7897. int n;
  7898. s_animation_t *animations[64];
  7899. int numblends = 0;
  7900. for ( n = 0; n < g_numani; n++ )
  7901. {
  7902. if ( !Q_stricmp( pFullPath, g_panimation[n]->name ) )
  7903. {
  7904. animations[numblends++] = g_panimation[n];
  7905. break;
  7906. }
  7907. }
  7908. if ( n >= g_numani )
  7909. {
  7910. // assume it's an implied animation
  7911. animations[numblends++] = Cmd_ImpliedAnimation( pseq, pFullPath );
  7912. }
  7913. // hack to allow animation commands to refer to same sequence
  7914. if ( numblends == 1 )
  7915. {
  7916. pseq->panim[0][0] = animations[0];
  7917. }
  7918. // Look up the source animation from the animation name
  7919. for ( int j = 0; j < numblends; ++j )
  7920. {
  7921. s_sourceanim_t *pSourceAnim = FindSourceAnim( animations[j]->source, animationFiles[i]->m_SourceAnimationName );
  7922. // NOTE: This always affects the first source anim read in
  7923. if ( pSourceAnim )
  7924. {
  7925. animations[j]->startframe = pSourceAnim->startframe;
  7926. animations[j]->endframe = pSourceAnim->endframe;
  7927. if ( !g_bCreateMakefile && animations[j]->endframe < animations[j]->startframe )
  7928. {
  7929. TokenError( "end frame before start frame in %s", animations[j]->name );
  7930. }
  7931. animations[j]->numframes = animations[j]->endframe - animations[j]->startframe + 1;
  7932. Q_strncpy( animations[j]->animationname, animationFiles[i]->m_SourceAnimationName, sizeof(animations[j]->animationname) );
  7933. }
  7934. else
  7935. {
  7936. MdlError( "Requested unknown animation block name %s\n", animationFiles[i]->m_SourceAnimationName.Get() );
  7937. }
  7938. }
  7939. ProcessSequence( pseq, numblends, animations, false );
  7940. }
  7941. return true;
  7942. }
  7943. //-----------------------------------------------------------------------------
  7944. // Parse the MDL makefile
  7945. //-----------------------------------------------------------------------------
  7946. void ParseMDLMakeFile( CDmeMDLMakefile *pMDLMakeFile )
  7947. {
  7948. if ( !GenerateModelName( pMDLMakeFile ) )
  7949. return;
  7950. // All DMX files have Y as the up axis
  7951. RadianEuler angles( M_PI / 2.0f, 0.0f, M_PI / 2.0f );
  7952. ProcessUpAxis( angles );
  7953. // Process bodies
  7954. if ( !GenerateSkin( pMDLMakeFile ) )
  7955. return;
  7956. // Process animations
  7957. if ( !GenerateAnimations( pMDLMakeFile ) )
  7958. return;
  7959. }
  7960. // Used by the CheckSurfaceProps.py script.
  7961. // They specify the .mdl file and it prints out all the surface props that the model uses.
  7962. bool HandlePrintSurfaceProps( int &returnValue )
  7963. {
  7964. const char *pFilename = CommandLine()->ParmValue( "-PrintSurfaceProps", (const char*)NULL );
  7965. if ( pFilename )
  7966. {
  7967. CUtlVector<char> buf;
  7968. FILE *fp = fopen( pFilename, "rb" );
  7969. if ( fp )
  7970. {
  7971. fseek( fp, 0, SEEK_END );
  7972. buf.SetSize( ftell( fp ) );
  7973. fseek( fp, 0, SEEK_SET );
  7974. fread( buf.Base(), 1, buf.Count(), fp );
  7975. fclose( fp );
  7976. studiohdr_t *pHdr = (studiohdr_t*)buf.Base();
  7977. Studio_ConvertStudioHdrToNewVersion( pHdr );
  7978. if ( pHdr->version == STUDIO_VERSION )
  7979. {
  7980. for ( int i=0; i < pHdr->numbones; i++ )
  7981. {
  7982. mstudiobone_t *pBone = pHdr->pBone( i );
  7983. printf( "%s\n", pBone->pszSurfaceProp() );
  7984. }
  7985. returnValue = 0;
  7986. }
  7987. else
  7988. {
  7989. printf( "-PrintSurfaceProps: '%s' is wrong version (%d should be %d).\n",
  7990. pFilename, pHdr->version, STUDIO_VERSION );
  7991. returnValue = 1;
  7992. }
  7993. }
  7994. else
  7995. {
  7996. printf( "-PrintSurfaceProps: can't open '%s'\n", pFilename );
  7997. returnValue = 1;
  7998. }
  7999. return true;
  8000. }
  8001. else
  8002. {
  8003. return false;
  8004. }
  8005. }
  8006. // Used by the modelstats.pl script.
  8007. // They specify the .mdl file and it prints out perf info.
  8008. bool HandleMdlReport( int &returnValue )
  8009. {
  8010. const char *pFilename = CommandLine()->ParmValue( "-mdlreport", (const char*)NULL );
  8011. if ( pFilename )
  8012. {
  8013. CUtlVector<char> buf;
  8014. FILE *fp = fopen( pFilename, "rb" );
  8015. if ( fp )
  8016. {
  8017. fseek( fp, 0, SEEK_END );
  8018. buf.SetSize( ftell( fp ) );
  8019. fseek( fp, 0, SEEK_SET );
  8020. fread( buf.Base(), 1, buf.Count(), fp );
  8021. fclose( fp );
  8022. studiohdr_t *pHdr = (studiohdr_t*)buf.Base();
  8023. Studio_ConvertStudioHdrToNewVersion( pHdr );
  8024. if ( pHdr->version == STUDIO_VERSION )
  8025. {
  8026. int flags = SPEWPERFSTATS_SHOWPERF;
  8027. if( CommandLine()->CheckParm( "-mdlreportspreadsheet", NULL ) )
  8028. {
  8029. flags |= SPEWPERFSTATS_SPREADSHEET;
  8030. }
  8031. SpewPerfStats( pHdr, pFilename, flags );
  8032. returnValue = 0;
  8033. }
  8034. else
  8035. {
  8036. printf( "-mdlreport: '%s' is wrong version (%d should be %d).\n",
  8037. pFilename, pHdr->version, STUDIO_VERSION );
  8038. returnValue = 1;
  8039. }
  8040. }
  8041. else
  8042. {
  8043. printf( "-mdlreport: can't open '%s'\n", pFilename );
  8044. returnValue = 1;
  8045. }
  8046. return true;
  8047. }
  8048. else
  8049. {
  8050. return false;
  8051. }
  8052. }
  8053. void UsageAndExit()
  8054. {
  8055. MdlError( "Bad or missing options\n"
  8056. "usage: studiomdl [options] <file.qc>\n"
  8057. "options:\n"
  8058. "[-a <normal_blend_angle>]\n"
  8059. "[-checklengths]\n"
  8060. "[-d] - dump glview files\n"
  8061. "[-definebones]\n"
  8062. "[-f] - flip all triangles\n"
  8063. "[-fullcollide] - don't truncate really big collisionmodels\n"
  8064. "[-game <gamedir>]\n"
  8065. "[-h] - dump hboxes\n"
  8066. "[-i] - ignore warnings\n"
  8067. "[-minlod <lod>] - truncate to highest detail <lod>\n"
  8068. "[-n] - tag bad normals\n"
  8069. "[-perf] report perf info upon compiling model\n"
  8070. "[-printbones]\n"
  8071. "[-printgraph]\n"
  8072. "[-quiet] - operate silently\n"
  8073. "[-r] - tag reversed\n"
  8074. "[-t <texture>]\n"
  8075. "[-x360] - generate xbox360 output\n"
  8076. "[-nox360] - disable xbox360 output(default)\n"
  8077. "[-nowarnings] - disable warnings\n"
  8078. "[-dumpmaterials] - dump out material names\n"
  8079. "[-mdlreport] model.mdl - report perf info\n"
  8080. "[-mdlreportspreadsheet] - report perf info as a comma-delimited spreadsheet\n"
  8081. "[-striplods] - use only lod0\n"
  8082. "[-overridedefinebones] - equivalent to specifying $unlockdefinebones in .qc file\n"
  8083. "[-stripmodel] - process binary model files and strip extra lod data\n"
  8084. "[-stripvhv] - strip hardware verts to match the stripped model\n"
  8085. "[-vsi] - generate stripping information .vsi file - can be used on .mdl files too\n"
  8086. );
  8087. }
  8088. #ifndef _DEBUG
  8089. LONG __stdcall VExceptionFilter( struct _EXCEPTION_POINTERS *ExceptionInfo )
  8090. {
  8091. MdlExceptionFilter( ExceptionInfo->ExceptionRecord->ExceptionCode );
  8092. return EXCEPTION_EXECUTE_HANDLER; // (never gets here anyway)
  8093. }
  8094. #endif
  8095. /*
  8096. ==============
  8097. main
  8098. ==============
  8099. */
  8100. //-----------------------------------------------------------------------------
  8101. // The application object
  8102. //-----------------------------------------------------------------------------
  8103. class CStudioMDLApp : public CDefaultAppSystemGroup< CSteamAppSystemGroup >
  8104. {
  8105. typedef CDefaultAppSystemGroup< CSteamAppSystemGroup > BaseClass;
  8106. public:
  8107. // Methods of IApplication
  8108. virtual bool Create();
  8109. virtual bool PreInit( );
  8110. virtual int Main();
  8111. virtual void PostShutdown();
  8112. private:
  8113. int Main_StripModel();
  8114. int Main_StripVhv();
  8115. int Main_MakeVsi();
  8116. private:
  8117. bool ParseArguments();
  8118. };
  8119. static bool CStudioMDLApp_SuggestGameInfoDirFn( CFSSteamSetupInfo const *pFsSteamSetupInfo, char *pchPathBuffer, int nBufferLength, bool *pbBubbleDirectories )
  8120. {
  8121. const char *pProcessFileName = NULL;
  8122. int nParmCount = CommandLine()->ParmCount();
  8123. if ( nParmCount > 1 )
  8124. {
  8125. pProcessFileName = CommandLine()->GetParm( nParmCount - 1 );
  8126. }
  8127. if ( pProcessFileName )
  8128. {
  8129. Q_MakeAbsolutePath( pchPathBuffer, nBufferLength, pProcessFileName );
  8130. if ( pbBubbleDirectories )
  8131. *pbBubbleDirectories = true;
  8132. return true;
  8133. }
  8134. return false;
  8135. }
  8136. int main( int argc, char **argv )
  8137. {
  8138. SetSuggestGameInfoDirFn( CStudioMDLApp_SuggestGameInfoDirFn );
  8139. CStudioMDLApp s_ApplicationObject;
  8140. CSteamApplication s_SteamApplicationObject( &s_ApplicationObject );
  8141. return AppMain( argc, argv, &s_SteamApplicationObject );
  8142. }
  8143. //-----------------------------------------------------------------------------
  8144. // The application object
  8145. //-----------------------------------------------------------------------------
  8146. bool CStudioMDLApp::Create()
  8147. {
  8148. InstallSpewFunction();
  8149. // override the default spew function
  8150. SpewOutputFunc( MdlSpewOutputFunc );
  8151. MathLib_Init( 2.2f, 2.2f, 0.0f, 2.0f, false, false, false, false );
  8152. #ifndef _DEBUG
  8153. SetUnhandledExceptionFilter( VExceptionFilter );
  8154. #endif
  8155. if ( CommandLine()->ParmCount() == 1 )
  8156. {
  8157. UsageAndExit();
  8158. return false;
  8159. }
  8160. int nReturnValue;
  8161. if ( HandlePrintSurfaceProps( nReturnValue ) )
  8162. return false;
  8163. if ( !ParseArguments() )
  8164. return false;
  8165. AppSystemInfo_t appSystems[] =
  8166. {
  8167. { "vstdlib.dll", PROCESS_UTILS_INTERFACE_VERSION },
  8168. { "materialsystem.dll", MATERIAL_SYSTEM_INTERFACE_VERSION },
  8169. { "studiorender.dll", STUDIO_RENDER_INTERFACE_VERSION },
  8170. { "mdllib.dll", MDLLIB_INTERFACE_VERSION },
  8171. { "", "" } // Required to terminate the list
  8172. };
  8173. AddSystem( g_pDataModel, VDATAMODEL_INTERFACE_VERSION );
  8174. AddSystem( g_pDmElementFramework, VDMELEMENTFRAMEWORK_VERSION );
  8175. AddSystem( g_pDmSerializers, DMSERIALIZERS_INTERFACE_VERSION );
  8176. // Add in the locally-defined studio data cache
  8177. AppModule_t studioDataCacheModule = LoadModule( Sys_GetFactoryThis() );
  8178. AddSystem( studioDataCacheModule, STUDIO_DATA_CACHE_INTERFACE_VERSION );
  8179. // Add the P4 module separately so that if it is absent (say in the SDK) then the other system will initialize properly
  8180. if ( !CommandLine()->FindParm( "-nop4" ) )
  8181. {
  8182. AppModule_t p4Module = LoadModule( "p4lib.dll" );
  8183. AddSystem( p4Module, P4_INTERFACE_VERSION );
  8184. }
  8185. bool bOk = AddSystems( appSystems );
  8186. if ( !bOk )
  8187. return false;
  8188. IMaterialSystem *pMaterialSystem = (IMaterialSystem*)FindSystem( MATERIAL_SYSTEM_INTERFACE_VERSION );
  8189. if ( !pMaterialSystem )
  8190. return false;
  8191. pMaterialSystem->SetShaderAPI( "shaderapiempty.dll" );
  8192. return true;
  8193. }
  8194. bool CStudioMDLApp::PreInit( )
  8195. {
  8196. CreateInterfaceFn factory = GetFactory();
  8197. ConnectTier1Libraries( &factory, 1 );
  8198. ConnectTier2Libraries( &factory, 1 );
  8199. ConnectTier3Libraries( &factory, 1 );
  8200. if ( !g_pFullFileSystem || !g_pDataModel || !g_pMaterialSystem || !g_pStudioRender )
  8201. {
  8202. Warning( "StudioMDL is missing a required interface!\n" );
  8203. return false;
  8204. }
  8205. if ( !SetupSearchPaths( g_path, false, true ) )
  8206. return false;
  8207. // NOTE: This is necessary to get the cmdlib filesystem stuff to work.
  8208. g_pFileSystem = g_pFullFileSystem;
  8209. // NOTE: This is stuff copied out of cmdlib necessary to get
  8210. // the tools in cmdlib working
  8211. FileSystem_SetupStandardDirectories( g_path, GetGameInfoPath() );
  8212. return true;
  8213. }
  8214. void CStudioMDLApp::PostShutdown()
  8215. {
  8216. DisconnectTier3Libraries();
  8217. DisconnectTier2Libraries();
  8218. DisconnectTier1Libraries();
  8219. }
  8220. //-----------------------------------------------------------------------------
  8221. // Method which parses arguments
  8222. //-----------------------------------------------------------------------------
  8223. bool CStudioMDLApp::ParseArguments()
  8224. {
  8225. g_currentscale = g_defaultscale = 1.0;
  8226. g_defaultrotation = RadianEuler( 0, 0, M_PI / 2 );
  8227. // skip weightlist 0
  8228. g_numweightlist = 1;
  8229. eyeposition = Vector( 0, 0, 0 );
  8230. gflags = 0;
  8231. numrep = 0;
  8232. tag_reversed = 0;
  8233. tag_normals = 0;
  8234. normal_blend = cos( DEG2RAD( 2.0 ));
  8235. g_gamma = 2.2;
  8236. g_staticprop = false;
  8237. g_centerstaticprop = false;
  8238. g_realignbones = false;
  8239. g_constdirectionalightdot = 0;
  8240. g_bDumpGLViewFiles = false;
  8241. g_quiet = false;
  8242. g_illumpositionattachment = 0;
  8243. g_flMaxEyeDeflection = 0.0f;
  8244. int argc = CommandLine()->ParmCount();
  8245. int i;
  8246. for ( i = 1; i < argc - 1; i++ )
  8247. {
  8248. const char *pArgv = CommandLine()->GetParm( i );
  8249. if ( pArgv[0] != '-' )
  8250. continue;
  8251. if ( !Q_stricmp( pArgv, "-allowdebug" ) )
  8252. {
  8253. // Ignore, used by interface system to catch debug builds checked into release tree
  8254. continue;
  8255. }
  8256. if ( !Q_stricmp( pArgv, "-mdlreport" ) )
  8257. {
  8258. // Will reparse later, ignore rest of arguments.
  8259. return true;
  8260. }
  8261. if ( !Q_stricmp( pArgv, "-mdlreportspreadsheet" ) )
  8262. {
  8263. // Will reparse later, ignore for now.
  8264. continue;
  8265. }
  8266. if ( !Q_stricmp( pArgv, "-ihvtest" ) )
  8267. {
  8268. ++i;
  8269. g_IHVTest = true;
  8270. continue;
  8271. }
  8272. if ( !Q_stricmp( pArgv, "-overridedefinebones" ) )
  8273. {
  8274. g_bOverridePreDefinedBones = true;
  8275. continue;
  8276. }
  8277. if ( !Q_stricmp( pArgv, "-striplods" ) )
  8278. {
  8279. g_bStripLods = true;
  8280. continue;
  8281. }
  8282. if ( !Q_stricmp( pArgv, "-stripmodel" ) )
  8283. {
  8284. g_eRunMode = RUN_MODE_STRIP_MODEL;
  8285. continue;
  8286. }
  8287. if ( !Q_stricmp( pArgv, "-stripvhv" ) )
  8288. {
  8289. g_eRunMode = RUN_MODE_STRIP_VHV;
  8290. continue;
  8291. }
  8292. if ( !Q_stricmp( pArgv, "-vsi" ) )
  8293. {
  8294. g_bMakeVsi = true;
  8295. continue;
  8296. }
  8297. if ( !Q_stricmp( pArgv, "-quiet" ) )
  8298. {
  8299. g_quiet = true;
  8300. g_verbose = false;
  8301. continue;
  8302. }
  8303. if ( !Q_stricmp( pArgv, "-verbose" ) )
  8304. {
  8305. g_quiet = false;
  8306. g_verbose = true;
  8307. continue;
  8308. }
  8309. if ( !Q_stricmp( pArgv, "-fullcollide" ) )
  8310. {
  8311. g_badCollide = true;
  8312. continue;
  8313. }
  8314. if ( !Q_stricmp( pArgv, "-checklengths" ) )
  8315. {
  8316. g_bCheckLengths = true;
  8317. continue;
  8318. }
  8319. if ( !Q_stricmp( pArgv, "-printbones" ) )
  8320. {
  8321. g_bPrintBones = true;
  8322. continue;
  8323. }
  8324. if ( !Q_stricmp( pArgv, "-perf" ) )
  8325. {
  8326. g_bPerf = true;
  8327. continue;
  8328. }
  8329. if ( !Q_stricmp( pArgv, "-printgraph" ) )
  8330. {
  8331. g_bDumpGraph = true;
  8332. continue;
  8333. }
  8334. if ( !Q_stricmp( pArgv, "-definebones" ) )
  8335. {
  8336. g_definebones = true;
  8337. continue;
  8338. }
  8339. if ( !Q_stricmp( pArgv, "-makefile" ) )
  8340. {
  8341. g_bCreateMakefile = true;
  8342. g_quiet = true;
  8343. continue;
  8344. }
  8345. if ( !Q_stricmp( pArgv, "-verify" ) )
  8346. {
  8347. g_bVerifyOnly = true;
  8348. continue;
  8349. }
  8350. if ( !Q_stricmp( pArgv, "-minlod" ) )
  8351. {
  8352. g_minLod = atoi( CommandLine()->GetParm( ++i ) );
  8353. continue;
  8354. }
  8355. if (!Q_stricmp( pArgv, "-x360"))
  8356. {
  8357. StudioByteSwap::ActivateByteSwapping( true ); // Set target to big endian
  8358. g_bX360 = true;
  8359. continue;
  8360. }
  8361. if (!Q_stricmp( pArgv, "-nox360"))
  8362. {
  8363. g_bX360 = false;
  8364. continue;
  8365. }
  8366. if ( !Q_stricmp( pArgv, "-nowarnings" ) )
  8367. {
  8368. g_bNoWarnings = true;
  8369. continue;
  8370. }
  8371. if ( !Q_stricmp( pArgv, "-maxwarnings" ) )
  8372. {
  8373. g_maxWarnings = atoi( CommandLine()->GetParm( ++i ) );
  8374. continue;
  8375. }
  8376. if ( !Q_stricmp( pArgv, "-preview" ) )
  8377. {
  8378. g_bBuildPreview = true;
  8379. continue;
  8380. }
  8381. if ( !Q_stricmp( pArgv, "-dumpmaterials" ) )
  8382. {
  8383. g_bDumpMaterials = true;
  8384. continue;
  8385. }
  8386. if ( pArgv[1] && pArgv[2] == '\0' )
  8387. {
  8388. switch( pArgv[1] )
  8389. {
  8390. case 't':
  8391. i++;
  8392. V_strcpy_safe( defaulttexture[numrep], pArgv );
  8393. if (i < argc - 2 && CommandLine()->GetParm(i + 1)[0] != '-')
  8394. {
  8395. i++;
  8396. V_strcpy_safe( sourcetexture[numrep], pArgv );
  8397. printf("Replacing %s with %s\n", sourcetexture[numrep], defaulttexture[numrep] );
  8398. }
  8399. printf( "Using default texture: %s\n", defaulttexture[numrep] );
  8400. numrep++;
  8401. break;
  8402. case 'r':
  8403. tag_reversed = 1;
  8404. break;
  8405. case 'n':
  8406. tag_normals = 1;
  8407. break;
  8408. case 'a':
  8409. i++;
  8410. normal_blend = cos( DEG2RAD( verify_atof( pArgv ) ) );
  8411. break;
  8412. case 'h':
  8413. dump_hboxes = 1;
  8414. break;
  8415. case 'i':
  8416. ignore_warnings = 1;
  8417. break;
  8418. case 'd':
  8419. g_bDumpGLViewFiles = true;
  8420. break;
  8421. // case 'p':
  8422. // i++;
  8423. // V_strcpy_safe( qproject, pArgv );
  8424. // break;
  8425. }
  8426. }
  8427. }
  8428. if ( i >= argc )
  8429. {
  8430. // misformed arguments
  8431. // otherwise generating unintended results
  8432. UsageAndExit();
  8433. return false;
  8434. }
  8435. const char *pArgv = CommandLine()->GetParm( i );
  8436. Q_strncpy( g_path, pArgv, sizeof(g_path) );
  8437. if ( Q_IsAbsolutePath( g_path ) )
  8438. {
  8439. // Set the working directory to be the path of the qc file
  8440. // so the relative-file fopen code works
  8441. char pQCDir[MAX_PATH];
  8442. Q_ExtractFilePath( g_path, pQCDir, sizeof(pQCDir) );
  8443. _chdir( pQCDir );
  8444. }
  8445. Q_StripExtension( pArgv, outname, sizeof( outname ) );
  8446. return true;
  8447. }
  8448. //-----------------------------------------------------------------------------
  8449. // Purpose: search through the "GamePath" key and create a mirrored version in the content path searches
  8450. //-----------------------------------------------------------------------------
  8451. void AddContentPaths( )
  8452. {
  8453. // look for the "content" in the path to the initial QC file
  8454. char *match = "content\\";
  8455. char *sp = strstr( qdir, match );
  8456. if (!sp)
  8457. return;
  8458. // copy off everything before and including "content"
  8459. char pre[1024];
  8460. strncpy( pre, qdir, sp - qdir + strlen( match ) );
  8461. pre[sp - qdir + strlen( match )] = '\0';
  8462. sp = sp + strlen( match );
  8463. // copy off everything folling the word after "content"
  8464. char post[1024];
  8465. sp = strstr( sp+1, "\\" );
  8466. V_strcpy_safe( post, sp );
  8467. // get a copy of the game search paths
  8468. char paths[1024];
  8469. g_pFullFileSystem->GetSearchPath( "GAME", false, paths, sizeof( paths ) );
  8470. if (!g_quiet)
  8471. printf("all paths:%s\n", paths );
  8472. // pull out the game names and insert them into a content path string
  8473. sp = strstr( paths, "game\\" );
  8474. while (sp)
  8475. {
  8476. char temp[1024];
  8477. sp = sp + 5;
  8478. char *sz = strstr( sp, "\\" );
  8479. if (!sz)
  8480. return;
  8481. V_strcpy_safe( temp, pre );
  8482. strncat( temp, sp, sz - sp );
  8483. V_strcat_safe( temp, post );
  8484. sp = sz;
  8485. sp = strstr( sp, "game\\" );
  8486. CmdLib_AddBasePath( temp );
  8487. if (!g_quiet)
  8488. printf("content:%s\n", temp );
  8489. }
  8490. }
  8491. //-----------------------------------------------------------------------------
  8492. // The application object
  8493. //-----------------------------------------------------------------------------
  8494. int CStudioMDLApp::Main()
  8495. {
  8496. const bool bP4DLLExists = g_pFullFileSystem->FileExists( "p4lib.dll", "EXECUTABLE_PATH" );
  8497. // No p4 mode if specified on the command line or no p4lib.dll found
  8498. if ( ( CommandLine()->FindParm( "-nop4" ) ) || ( !bP4DLLExists ) )
  8499. {
  8500. g_bNoP4 = true;
  8501. g_p4factory->SetDummyMode( true );
  8502. }
  8503. // Set the named changelist
  8504. g_p4factory->SetOpenFileChangeList( "StudioMDL Auto Checkout" );
  8505. // This bit of hackery allows us to access files on the harddrive
  8506. g_pFullFileSystem->AddSearchPath( "", "LOCAL", PATH_ADD_TO_HEAD );
  8507. MaterialSystem_Config_t config;
  8508. g_pMaterialSystem->OverrideConfig( config, false );
  8509. int nReturnValue;
  8510. if ( HandleMdlReport( nReturnValue ) )
  8511. return false;
  8512. // Don't bother with undo here
  8513. g_pDataModel->SetUndoEnabled( false );
  8514. // look for the "content\hl2x" string in the qdir and add what should be the correct path as an alternate
  8515. // FIXME: add these to an envvar if folks are using complicated directory mappings instead of defaults
  8516. char *match = "content\\hl2x\\";
  8517. char *sp = strstr( qdir, match );
  8518. if (sp)
  8519. {
  8520. char temp[1024];
  8521. strncpy( temp, qdir, sp - qdir + strlen( match ) );
  8522. temp[sp - qdir + strlen( match )] = '\0';
  8523. CmdLib_AddBasePath( temp );
  8524. V_strcat_safe( temp, "..\\..\\..\\..\\main\\content\\hl2\\" );
  8525. CmdLib_AddBasePath( temp );
  8526. }
  8527. AddContentPaths();
  8528. if (!g_quiet)
  8529. {
  8530. printf("qdir: \"%s\"\n", qdir );
  8531. printf("gamedir: \"%s\"\n", gamedir );
  8532. printf("g_path: \"%s\"\n", g_path );
  8533. }
  8534. switch ( g_eRunMode )
  8535. {
  8536. case RUN_MODE_STRIP_MODEL:
  8537. return Main_StripModel();
  8538. case RUN_MODE_STRIP_VHV:
  8539. return Main_StripVhv();
  8540. case RUN_MODE_BUILD:
  8541. default:
  8542. break;
  8543. }
  8544. const char *pExt = Q_GetFileExtension( g_path );
  8545. // Look for the presence of a .mdl file (only -vsi is currently supported for .mdl files)
  8546. if ( pExt && !Q_stricmp( pExt, "mdl" ) )
  8547. {
  8548. if ( g_bMakeVsi )
  8549. return Main_MakeVsi();
  8550. printf( "ERROR: .qc or .dmx file should be specified to build.\n" );
  8551. return 1;
  8552. }
  8553. if ( !g_quiet )
  8554. printf( "Building binary model files...\n" );
  8555. // Look for the presence of a .dmx file of the same name
  8556. // If so, load it first
  8557. CDmeMDLMakefile *pMDLMakeFile = NULL;
  8558. if ( pExt && !Q_stricmp( pExt, "dmx" ) )
  8559. {
  8560. CDmElement *pRoot;
  8561. if ( g_pDataModel->RestoreFromFile( g_path, NULL, NULL, &pRoot ) != DMFILEID_INVALID )
  8562. {
  8563. pMDLMakeFile = CastElement<CDmeMDLMakefile>( pRoot );
  8564. }
  8565. };
  8566. Q_FileBase( g_path, g_path, sizeof( g_path ) );
  8567. Q_DefaultExtension( g_path, pMDLMakeFile ? ".dmx" : ".qc", sizeof( g_path ) );
  8568. if (!g_quiet)
  8569. {
  8570. printf( "Working on \"%s\"\n", g_path );
  8571. }
  8572. // Turn on checking for special single character tokens while parsing
  8573. SetCheckSingleCharTokens( true );
  8574. SetSingleCharTokenList( "{}()," );
  8575. // Set up script loading callback, discarding default callback
  8576. ( void ) SetScriptLoadedCallback( StudioMdl_ScriptLoadedCallback );
  8577. // load the script
  8578. if ( !pMDLMakeFile )
  8579. {
  8580. LoadScriptFile(g_path);
  8581. }
  8582. V_strcpy_safe( fullpath, g_path );
  8583. V_strcpy_safe( fullpath, ExpandPath( fullpath ) );
  8584. V_strcpy_safe( fullpath, ExpandArg( fullpath ) );
  8585. // default to having one entry in the LOD list that doesn't do anything so
  8586. // that we don't have to do any special cases for the first LOD.
  8587. g_ScriptLODs.Purge();
  8588. g_ScriptLODs.AddToTail(); // add an empty one
  8589. g_ScriptLODs[0].switchValue = 0.0f;
  8590. //
  8591. // parse it
  8592. //
  8593. ClearModel();
  8594. // V_strcpy_safe( g_pPlatformName, "" );
  8595. if ( pMDLMakeFile )
  8596. {
  8597. ParseMDLMakeFile( pMDLMakeFile );
  8598. }
  8599. else
  8600. {
  8601. ParseScript();
  8602. }
  8603. if ( !g_bCreateMakefile )
  8604. {
  8605. SetSkinValues();
  8606. SimplifyModel();
  8607. ConsistencyCheckSurfaceProp();
  8608. ConsistencyCheckContents();
  8609. CollisionModel_Build();
  8610. // ValidateSharedAnimationGroups();
  8611. WriteModelFiles();
  8612. }
  8613. if ( pMDLMakeFile )
  8614. {
  8615. DestroyElement( pMDLMakeFile );
  8616. pMDLMakeFile = NULL;
  8617. }
  8618. if ( g_bCreateMakefile )
  8619. {
  8620. CreateMakefile_OutputMakefile();
  8621. }
  8622. else if ( g_bMakeVsi )
  8623. {
  8624. Q_snprintf( g_path, ARRAYSIZE( g_path ), "%smodels/%s", gamedir, outname );
  8625. Main_MakeVsi();
  8626. }
  8627. if (!g_quiet)
  8628. {
  8629. printf("\nCompleted \"%s\"\n", g_path);
  8630. }
  8631. g_pDataModel->UnloadFile( DMFILEID_INVALID );
  8632. return 0;
  8633. }
  8634. //
  8635. // WriteFileToDisk
  8636. // Equivalent to g_pFullFileSystem->WriteFile( pFileName, pPath, buf ), but works
  8637. // for relative paths.
  8638. //
  8639. bool WriteFileToDisk( const char *pFileName, const char *pPath, CUtlBuffer &buf )
  8640. {
  8641. // For some reason calling full filesystem will write into hl2 root dir
  8642. // return g_pFullFileSystem->WriteFile( pFileName, pPath, buf );
  8643. FILE *f = fopen( pFileName, "wb" );
  8644. if ( !f )
  8645. return false;
  8646. fwrite( buf.Base(), 1, buf.TellPut(), f );
  8647. fclose( f );
  8648. return true;
  8649. }
  8650. //
  8651. // WriteBufferToFile
  8652. // Helper to concatenate file base and extension.
  8653. //
  8654. bool WriteBufferToFile( CUtlBuffer &buf, const char *szFilebase, const char *szExt )
  8655. {
  8656. char szFilename[ 1024 ];
  8657. Q_snprintf( szFilename, ARRAYSIZE( szFilename ), "%s%s", szFilebase, szExt );
  8658. return WriteFileToDisk( szFilename, NULL, buf );
  8659. }
  8660. //
  8661. // LoadBufferFromFile
  8662. // Loads the buffer from file, return true on success, false otherwise.
  8663. // If bError is true prints an error upon failure.
  8664. //
  8665. bool LoadBufferFromFile( CUtlBuffer &buffer, char const *szFilebase, char const *szExt, bool bError = true )
  8666. {
  8667. char szFilename[1024];
  8668. Q_snprintf( szFilename, ARRAYSIZE( szFilename ), "%s%s", szFilebase, szExt );
  8669. if ( g_pFullFileSystem->ReadFile( szFilename, NULL, buffer ) )
  8670. return true;
  8671. if ( bError )
  8672. MdlError( "Failed to open '%s'!\n", szFilename );
  8673. return false;
  8674. }
  8675. bool Load3ModelBuffers( CUtlBuffer &bufMDL, CUtlBuffer &bufVVD, CUtlBuffer &bufVTX, char const *szFilebase )
  8676. {
  8677. // Load up the mdl file
  8678. if ( !LoadBufferFromFile( bufMDL, szFilebase, ".mdl" ) )
  8679. return false;
  8680. // Load up the vvd file
  8681. if ( !LoadBufferFromFile( bufVVD, szFilebase, ".vvd" ) )
  8682. return false;
  8683. // Load up the dx90.vtx file
  8684. if ( !LoadBufferFromFile( bufVTX, szFilebase, ".dx90.vtx" ) )
  8685. return false;
  8686. return true;
  8687. }
  8688. //////////////////////////////////////////////////////////////////////////
  8689. //
  8690. // Studiomdl hooks to call the stripping routines:
  8691. // Main_StripVhv
  8692. // Main_StripModel
  8693. //
  8694. //////////////////////////////////////////////////////////////////////////
  8695. int CStudioMDLApp::Main_StripVhv()
  8696. {
  8697. if ( !g_quiet )
  8698. {
  8699. printf( "Stripping vhv data...\n" );
  8700. }
  8701. if ( !mdllib )
  8702. {
  8703. printf( "ERROR: mdllib is not available!\n" );
  8704. return 1;
  8705. }
  8706. Q_StripExtension( g_path, g_path, sizeof( g_path ) );
  8707. char *pExt = g_path + strlen( g_path );
  8708. *pExt = 0;
  8709. //
  8710. // ====== Load files
  8711. //
  8712. // Load up the vhv file
  8713. CUtlBuffer bufVHV;
  8714. if ( !LoadBufferFromFile( bufVHV, g_path, ".vhv" ) )
  8715. return 1;
  8716. // Load up the info.strip file
  8717. CUtlBuffer bufRemapping;
  8718. if ( !LoadBufferFromFile( bufRemapping, g_path, ".info.strip", false ) &&
  8719. !LoadBufferFromFile( bufRemapping, g_path, ".vsi" ) )
  8720. return 1;
  8721. //
  8722. // ====== Process file contents
  8723. //
  8724. bool bResult = false;
  8725. {
  8726. SpewActivate( "mdllib", 3 );
  8727. IMdlStripInfo *pMdlStripInfo = NULL;
  8728. if ( mdllib->CreateNewStripInfo( &pMdlStripInfo ) )
  8729. {
  8730. pMdlStripInfo->UnSerialize( bufRemapping );
  8731. bResult = pMdlStripInfo->StripHardwareVertsBuffer( bufVHV );
  8732. }
  8733. if ( pMdlStripInfo )
  8734. pMdlStripInfo->DeleteThis();
  8735. }
  8736. if ( !bResult )
  8737. {
  8738. printf( "ERROR: stripping failed!\n" );
  8739. return 1;
  8740. }
  8741. //
  8742. // ====== Save out processed data
  8743. //
  8744. // Save vhv
  8745. if ( !WriteBufferToFile( bufVHV, g_path, ".vhv.strip" ) )
  8746. {
  8747. printf( "ERROR: Failed to save '%s'!\n", g_path );
  8748. return 1;
  8749. }
  8750. return 0;
  8751. }
  8752. int CStudioMDLApp::Main_MakeVsi()
  8753. {
  8754. if ( !mdllib )
  8755. {
  8756. printf( "ERROR: mdllib is not available!\n" );
  8757. return 1;
  8758. }
  8759. Q_StripExtension( g_path, g_path, sizeof( g_path ) );
  8760. char *pExt = g_path + strlen( g_path );
  8761. *pExt = 0;
  8762. // Load up the files
  8763. CUtlBuffer bufMDL;
  8764. CUtlBuffer bufVVD;
  8765. CUtlBuffer bufVTX;
  8766. if ( !Load3ModelBuffers( bufMDL, bufVVD, bufVTX, g_path ) )
  8767. return 1;
  8768. //
  8769. // ====== Process file contents
  8770. //
  8771. CUtlBuffer bufMappingTable;
  8772. bool bResult = false;
  8773. {
  8774. if ( !g_quiet )
  8775. {
  8776. printf( "---------------------\n" );
  8777. printf( "Generating .vsi stripping information...\n" );
  8778. SpewActivate( "mdllib", 3 );
  8779. }
  8780. IMdlStripInfo *pMdlStripInfo = NULL;
  8781. bResult =
  8782. mdllib->StripModelBuffers( bufMDL, bufVVD, bufVTX, &pMdlStripInfo ) &&
  8783. pMdlStripInfo->Serialize( bufMappingTable );
  8784. if ( pMdlStripInfo )
  8785. pMdlStripInfo->DeleteThis();
  8786. }
  8787. if ( !bResult )
  8788. {
  8789. printf( "ERROR: stripping failed!\n" );
  8790. return 1;
  8791. }
  8792. //
  8793. // ====== Save out processed data
  8794. //
  8795. // Save remapping data using "P4 edit -> save -> P4 add" approach
  8796. sprintf( pExt, ".vsi" );
  8797. CP4AutoEditAddFile _auto_edit_vsi( g_path );
  8798. if ( !WriteFileToDisk( g_path, NULL, bufMappingTable ) )
  8799. {
  8800. printf( "ERROR: Failed to save '%s'!\n", g_path );
  8801. return 1;
  8802. }
  8803. else if ( !g_quiet )
  8804. {
  8805. printf( "Generated .vsi stripping information.\n" );
  8806. }
  8807. return 0;
  8808. }
  8809. int CStudioMDLApp::Main_StripModel()
  8810. {
  8811. if ( !g_quiet )
  8812. {
  8813. printf( "Stripping binary model files...\n" );
  8814. }
  8815. if ( !mdllib )
  8816. {
  8817. printf( "ERROR: mdllib is not available!\n" );
  8818. return 1;
  8819. }
  8820. Q_FileBase( g_path, g_path, sizeof( g_path ) );
  8821. char *pExt = g_path + strlen( g_path );
  8822. *pExt = 0;
  8823. // Load up the files
  8824. CUtlBuffer bufMDL;
  8825. CUtlBuffer bufVVD;
  8826. CUtlBuffer bufVTX;
  8827. if ( !Load3ModelBuffers( bufMDL, bufVVD, bufVTX, g_path ) )
  8828. return 1;
  8829. //
  8830. // ====== Process file contents
  8831. //
  8832. CUtlBuffer bufMappingTable;
  8833. bool bResult = false;
  8834. {
  8835. SpewActivate( "mdllib", 3 );
  8836. IMdlStripInfo *pMdlStripInfo = NULL;
  8837. bResult =
  8838. mdllib->StripModelBuffers( bufMDL, bufVVD, bufVTX, &pMdlStripInfo ) &&
  8839. pMdlStripInfo->Serialize( bufMappingTable );
  8840. if ( pMdlStripInfo )
  8841. pMdlStripInfo->DeleteThis();
  8842. }
  8843. if ( !bResult )
  8844. {
  8845. printf( "ERROR: stripping failed!\n" );
  8846. return 1;
  8847. }
  8848. //
  8849. // ====== Save out processed data
  8850. //
  8851. // Save mdl
  8852. sprintf( pExt, ".mdl.strip" );
  8853. if ( !WriteFileToDisk( g_path, NULL, bufMDL ) )
  8854. {
  8855. printf( "ERROR: Failed to save '%s'!\n", g_path );
  8856. return 1;
  8857. }
  8858. // Save vvd
  8859. sprintf( pExt, ".vvd.strip" );
  8860. if ( !WriteFileToDisk( g_path, NULL, bufVVD ) )
  8861. {
  8862. printf( "ERROR: Failed to save '%s'!\n", g_path );
  8863. return 1;
  8864. }
  8865. // Save vtx
  8866. sprintf( pExt, ".vtx.strip" );
  8867. if ( !WriteFileToDisk( g_path, NULL, bufVTX ) )
  8868. {
  8869. printf( "ERROR: Failed to save '%s'!\n", g_path );
  8870. return 1;
  8871. }
  8872. // Save remapping data
  8873. sprintf( pExt, ".info.strip" );
  8874. if ( !WriteFileToDisk( g_path, NULL, bufMappingTable ) )
  8875. {
  8876. printf( "ERROR: Failed to save '%s'!\n", g_path );
  8877. return 1;
  8878. }
  8879. return 0;
  8880. }