blob_id
stringlengths 40
40
| directory_id
stringlengths 40
40
| path
stringlengths 5
146
| content_id
stringlengths 40
40
| detected_licenses
listlengths 0
7
| license_type
stringclasses 2
values | repo_name
stringlengths 6
79
| snapshot_id
stringlengths 40
40
| revision_id
stringlengths 40
40
| branch_name
stringclasses 4
values | visit_date
timestamp[us] | revision_date
timestamp[us] | committer_date
timestamp[us] | github_id
int64 5.07k
426M
⌀ | star_events_count
int64 0
27
| fork_events_count
int64 0
12
| gha_license_id
stringclasses 3
values | gha_event_created_at
timestamp[us] | gha_created_at
timestamp[us] | gha_language
stringclasses 6
values | src_encoding
stringclasses 26
values | language
stringclasses 1
value | is_vendor
bool 1
class | is_generated
bool 1
class | length_bytes
int64 20
6.28M
| extension
stringclasses 20
values | content
stringlengths 20
6.28M
| authors
listlengths 1
16
| author_lines
listlengths 1
16
|
---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
53877797458d191a89d38366a91218eb00a72cd8 | b2d46af9c6152323ce240374afc998c1574db71f | /cursovideojuegos/theflostiproject/3rdParty/boost/libs/config/test/no_ll_limits_pass.cpp | 2813fd8afdebb6a979b591fc66d909cb0deb7b53 | []
| no_license | bugbit/cipsaoscar | 601b4da0f0a647e71717ed35ee5c2f2d63c8a0f4 | 52aa8b4b67d48f59e46cb43527480f8b3552e96d | refs/heads/master | 2021-01-10T21:31:18.653163 | 2011-09-28T16:39:12 | 2011-09-28T16:39:12 | 33,032,640 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,245 | cpp |
// This file was automatically generated on Sun Jul 25 11:47:49 GMTDT 2004,
// by libs/config/tools/generate
// Copyright John Maddock 2002-4.
// Use, modification and distribution are subject to the
// Boost Software License, Version 1.0. (See accompanying file
// LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt)
// See http://www.boost.org/libs/config for the most recent version.
// Test file for macro BOOST_NO_LONG_LONG_NUMERIC_LIMITS
// This file should compile, if it does not then
// BOOST_NO_LONG_LONG_NUMERIC_LIMITS needs to be defined.
// see boost_no_ll_limits.ipp for more details
// Do not edit this file, it was generated automatically by
// ../tools/generate from boost_no_ll_limits.ipp on
// Sun Jul 25 11:47:49 GMTDT 2004
// Must not have BOOST_ASSERT_CONFIG set; it defeats
// the objective of this file:
#ifdef BOOST_ASSERT_CONFIG
# undef BOOST_ASSERT_CONFIG
#endif
#include <boost/config.hpp>
#include "test.hpp"
#ifndef BOOST_NO_LONG_LONG_NUMERIC_LIMITS
#include "boost_no_ll_limits.ipp"
#else
namespace boost_no_long_long_numeric_limits = empty_boost;
#endif
int main( int, char *[] )
{
return boost_no_long_long_numeric_limits::test();
}
| [
"ohernandezba@71d53fa2-cca5-e1f2-4b5e-677cbd06613a"
]
| [
[
[
1,
39
]
]
]
|
71822b68f26150b6e7fbec8756996c69a7cc84eb | 1c9f99b2b2e3835038aba7ec0abc3a228e24a558 | /Projects/elastix/elastix_sources_v4/src/Components/Transforms/StackTransform/elxBSplineStackTransform.hxx | 33f0420553f683d485c86c92a47aa97e14d939dd | []
| no_license | mijc/Diploma | 95fa1b04801ba9afb6493b24b53383d0fbd00b33 | bae131ed74f1b344b219c0ffe0fffcd90306aeb8 | refs/heads/master | 2021-01-18T13:57:42.223466 | 2011-02-15T14:19:49 | 2011-02-15T14:19:49 | 1,369,569 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 28,690 | hxx | /*======================================================================
This file is part of the elastix software.
Copyright (c) University Medical Center Utrecht. All rights reserved.
See src/CopyrightElastix.txt or http://elastix.isi.uu.nl/legal.php for
details.
This software is distributed WITHOUT ANY WARRANTY; without even
the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR
PURPOSE. See the above copyright notices for more information.
======================================================================*/
#ifndef __elxBSplineStackTransform_hxx
#define __elxBSplineStackTransform_hxx
#include "elxBSplineStackTransform.h"
#include "itkImageRegionExclusionConstIteratorWithIndex.h"
#include "vnl/vnl_math.h"
namespace elastix
{
using namespace itk;
/**
* ********************* Constructor ****************************
*/
template <class TElastix>
BSplineStackTransform<TElastix>
::BSplineStackTransform()
{
} // end Constructor()
/**
* ************ InitializeBSplineTransform ***************
*/
template <class TElastix>
unsigned int BSplineStackTransform<TElastix>
::InitializeBSplineTransform() {
/** Initialize the right BSplineTransform and GridScheduleComputer. */
this->m_GridScheduleComputer = GridScheduleComputerType::New();
this->m_GridScheduleComputer->SetBSplineOrder( m_SplineOrder );
if ( m_SplineOrder == 1)
{
this->m_BSplineDummySubTransform = BSplineTransformLinearType::New();
}
else if ( m_SplineOrder == 2)
{
this->m_BSplineDummySubTransform = BSplineTransformQuadraticType::New();
}
else if ( m_SplineOrder == 3)
{
this->m_BSplineDummySubTransform = BSplineTransformCubicType::New();
}
else
{
itkExceptionMacro( << "ERROR: The provided spline order is not supported." );
return 1;
}
/** Note: periodic B-splines are not supported here as they do not seem to
* make sense as a subtransform and deliver problems when compiling elastix
* for image dimension 2.
*/
/** Create stack transform. */
this->m_BSplineStackTransform = BSplineStackTransformType::New();
/** Set stack transform as current transform. */
this->SetCurrentTransform( this->m_BSplineStackTransform );
/** Create grid upsampler. */
this->m_GridUpsampler = GridUpsamplerType::New();
this->m_GridUpsampler->SetBSplineOrder( m_SplineOrder );
return 0;
}
/**
* ******************* BeforeAll ***********************
*/
template <class TElastix>
int BSplineStackTransform<TElastix>
::BeforeAll( void )
{
/** Read spline order from configuration file. */
m_SplineOrder = 3;
this->GetConfiguration()->ReadParameter( m_SplineOrder,
"BSplineTransformSplineOrder", this->GetComponentLabel(), 0, 0, true );
/** Initialize B-spline transform and grid scheduler. */
return InitializeBSplineTransform();
}
/**
* ******************* BeforeRegistration ***********************
*/
template <class TElastix>
void BSplineStackTransform<TElastix>
::BeforeRegistration( void )
{
/** Set initial transform parameters to a 1x1x1 grid, with deformation (0,0,0).
* In the method BeforeEachResolution() this will be replaced by the right grid size.
* This seems not logical, but it is required, since the registration
* class checks if the number of parameters in the transform is equal to
* the number of parameters in the registration class. This check is done
* before calling the BeforeEachResolution() methods.
*/
/** Task 1 - Set the Grid. */
/** Declarations. */
ReducedDimensionRegionType gridregion;
ReducedDimensionSizeType gridsize;
ReducedDimensionIndexType gridindex;
ReducedDimensionSpacingType gridspacing;
ReducedDimensionOriginType gridorigin;
/** Fill everything with default values. */
gridsize.Fill( 1 );
gridindex.Fill( 0 );
gridspacing.Fill( 1.0 );
gridorigin.Fill( 0.0 );
/** Set gridsize for large dimension to 4 to prevent errors when checking
* on support region size.
*/
gridsize.SetElement( gridsize.GetSizeDimension()-1, 4 );
/** Set it all. */
gridregion.SetIndex( gridindex );
gridregion.SetSize( gridsize );
this->m_BSplineDummySubTransform->SetGridRegion( gridregion );
this->m_BSplineDummySubTransform->SetGridSpacing( gridspacing );
this->m_BSplineDummySubTransform->SetGridOrigin( gridorigin );
/** Task 2 - Set the stack transform parameters. */
/** Determine stack transform settings. Here they are based on the fixed image. */
const SizeType imageSize = this->GetElastix()->GetFixedImage()->GetLargestPossibleRegion().GetSize();
this->m_NumberOfSubTransforms = imageSize[ SpaceDimension - 1 ];
this->m_StackSpacing = this->GetElastix()->GetFixedImage()->GetSpacing()[ SpaceDimension - 1 ];
this->m_StackOrigin = this->GetElastix()->GetFixedImage()->GetOrigin()[ SpaceDimension - 1 ];
/** Set stack transform parameters. */
this->m_BSplineStackTransform->SetNumberOfSubTransforms( this->m_NumberOfSubTransforms );
this->m_BSplineStackTransform->SetStackOrigin( this->m_StackOrigin );
this->m_BSplineStackTransform->SetStackSpacing( this->m_StackSpacing );
/** Initialize stack sub transforms. */
this->m_BSplineStackTransform->SetAllSubTransforms( this->m_BSplineDummySubTransform );
/** Task 3 - Give the registration an initial parameter-array. */
ParametersType dummyInitialParameters( this->GetNumberOfParameters() );
dummyInitialParameters.Fill( 0.0 );
/** Put parameters in the registration. */
this->m_Registration->GetAsITKBaseType()
->SetInitialTransformParameters( dummyInitialParameters );
/** Precompute the B-spline grid regions. */
this->PreComputeGridInformation();
} // end BeforeRegistration()
/**
* ***************** BeforeEachResolution ***********************
*/
template <class TElastix>
void BSplineStackTransform<TElastix>
::BeforeEachResolution( void )
{
/** What is the current resolution level? */
unsigned int level =
this->m_Registration->GetAsITKBaseType()->GetCurrentLevel();
/** Define the grid. */
if ( level == 0 )
{
this->InitializeTransform();
}
else
{
/** Upsample the B-spline grid for all sub transforms, if required. */
this->IncreaseScale();
}
/** Get the PassiveEdgeWidth and use it to set the OptimizerScales. */
unsigned int passiveEdgeWidth = 0;
this->GetConfiguration()->ReadParameter( passiveEdgeWidth,
"PassiveEdgeWidth", this->GetComponentLabel(), level, 0, false );
this->SetOptimizerScales( passiveEdgeWidth );
} // end BeforeEachResolution()
/**
* ******************** PreComputeGridInformation ***********************
*/
template <class TElastix>
void BSplineStackTransform<TElastix>
::PreComputeGridInformation( void )
{
/** Get the total number of resolution levels. */
const unsigned int nrOfResolutions =
this->m_Registration->GetAsITKBaseType()->GetNumberOfLevels();
/** Get current image origin, spacing, direction and largest possible region. */
const OriginType origin = this->GetElastix()->GetFixedImage()->GetOrigin();
const SpacingType spacing = this->GetElastix()->GetFixedImage()->GetSpacing();
const DirectionType direction = this->GetElastix()->GetFixedImage()->GetDirection();
const RegionType region = this->GetElastix()->GetFixedImage()->GetLargestPossibleRegion();
/** Variables to store reduced dimension origin, spacing, direction and region in. */
ReducedDimensionOriginType rorigin;
ReducedDimensionSpacingType rspacing;
ReducedDimensionDirectionType rdirection;
ReducedDimensionRegionType rregion;
/** Reduce dimension of origin, spacing, direction and region. */
for ( unsigned int d = 0; d < ReducedSpaceDimension; ++d )
{
rorigin[ d ] = origin[ d ];
rspacing[ d ] = spacing[ d ];
rregion.SetSize( d, region.GetSize( d ) );
rregion.SetIndex( d, region.GetIndex( d ) );
for ( unsigned int e = 0; e < ReducedSpaceDimension; ++e )
{
rdirection[ d ][ e ] = direction[ d ][ e ];
}
}
/** Set up grid schedule computer with reduced dimension image info. */
this->m_GridScheduleComputer->SetImageOrigin( rorigin );
this->m_GridScheduleComputer->SetImageSpacing( rspacing );
this->m_GridScheduleComputer->SetImageDirection( rdirection );
this->m_GridScheduleComputer->SetImageRegion( rregion );
/** Take the initial transform only into account, if composition is used. */
if ( this->GetUseComposition() )
{
/** \todo To do this, we need a grid schedule computer which can handle an
* initial transform of a higher dimension than the grid. We probably need
* to program some kind of stack grid schedule computer for that.
*/
// this->m_GridScheduleComputer->SetInitialTransform( this->Superclass1::GetInitialTransform() );
}
/** Get the grid spacing schedule from the parameter file.
*
* Method 1: The user specifies "FinalGridSpacingInVoxels"
* Method 2: The user specifies "FinalGridSpacingInPhysicalUnits"
*
* Method 1 and 2 additionally take the "GridSpacingSchedule".
* The GridSpacingSchedule is defined by downsampling factors
* for each resolution, for each dimension (just like the image
* pyramid schedules). So, for 2D images, and 3 resulutions,
* we can specify:
* (GridSpacingSchedule 4.0 4.0 2.0 2.0 1.0 1.0)
* Which is the default schedule, if no GridSpacingSchedule is supplied.
*/
/** Determine which method is used. */
bool method1 = false;
unsigned int count1 = this->m_Configuration
->CountNumberOfParameterEntries( "FinalGridSpacingInVoxels" );
if ( count1 > 0 )
{
method1 = true;
}
bool method2 = false;
unsigned int count2 = this->m_Configuration
->CountNumberOfParameterEntries( "FinalGridSpacingInPhysicalUnits" );
if ( count2 > 0 )
{
method2 = true;
}
/** Throw an exception if both methods are used. */
if ( count1 > 0 && count2 > 0 )
{
itkExceptionMacro( << "ERROR: You can not specify both \"FinalGridSpacingInVoxels\""
" and \"FinalGridSpacingInPhysicalUnits\" in the parameter file." );
}
/** Declare variables and set defaults. */
ReducedDimensionSpacingType finalGridSpacingInVoxels;
ReducedDimensionSpacingType finalGridSpacingInPhysicalUnits;
finalGridSpacingInVoxels.Fill( 16.0 );
finalGridSpacingInPhysicalUnits.Fill( 8.0 );
/** Method 1: Read the FinalGridSpacingInVoxels. */
if ( method1 )
{
for ( unsigned int dim = 0; dim < ReducedSpaceDimension; ++dim )
{
this->m_Configuration->ReadParameter(
finalGridSpacingInVoxels[ dim ], "FinalGridSpacingInVoxels",
this->GetComponentLabel(), dim , 0 );
}
/** Compute the grid spacing in physical units. */
for ( unsigned int dim = 0; dim < ReducedSpaceDimension; ++dim )
{
finalGridSpacingInPhysicalUnits[ dim ] =
finalGridSpacingInVoxels[ dim ] *
this->GetElastix()->GetFixedImage()->GetSpacing()[ dim ];
}
}
/** Method 2: Read the FinalGridSpacingInPhysicalUnits. */
if ( method2 )
{
for ( unsigned int dim = 0; dim < ReducedSpaceDimension; ++dim )
{
this->m_Configuration->ReadParameter(
finalGridSpacingInPhysicalUnits[ dim ], "FinalGridSpacingInPhysicalUnits",
this->GetComponentLabel(), dim , 0 );
}
}
/** Set up a default grid spacing schedule. */
this->m_GridScheduleComputer->SetDefaultSchedule(
nrOfResolutions, 2.0 );
GridScheduleType gridSchedule;
this->m_GridScheduleComputer->GetSchedule( gridSchedule );
/** Read what the user has specified. This overrules everything. */
count2 = this->m_Configuration
->CountNumberOfParameterEntries( "GridSpacingSchedule" );
unsigned int entry_nr = 0;
if ( count2 == 0 )
{
// keep the default schedule
}
else if ( count2 == nrOfResolutions )
{
for ( unsigned int res = 0; res < nrOfResolutions; ++res )
{
for ( unsigned int dim = 0; dim < ReducedSpaceDimension; ++dim )
{
this->m_Configuration->ReadParameter( gridSchedule[ res ][ dim ],
"GridSpacingSchedule", entry_nr, false );
}
++entry_nr;
}
}
else if ( count2 == nrOfResolutions * ReducedSpaceDimension )
{
for ( unsigned int res = 0; res < nrOfResolutions; ++res )
{
for ( unsigned int dim = 0; dim < ReducedSpaceDimension; ++dim )
{
this->m_Configuration->ReadParameter( gridSchedule[ res ][ dim ],
"GridSpacingSchedule", entry_nr, false );
++entry_nr;
}
}
}
else
{
xl::xout["error"]
<< "ERROR: Invalid GridSpacingSchedule! The number of entries"
<< " behind the GridSpacingSchedule option should equal the"
<< " numberOfResolutions, or the numberOfResolutions * ( ImageDimension - 1 )."
<< std::endl;
itkExceptionMacro( << "ERROR: Invalid GridSpacingSchedule!" );
}
/** Set the grid schedule and final grid spacing in the schedule computer. */
this->m_GridScheduleComputer->SetFinalGridSpacing(
finalGridSpacingInPhysicalUnits );
this->m_GridScheduleComputer->SetSchedule( gridSchedule );
/** Compute the necessary information. */
this->m_GridScheduleComputer->ComputeBSplineGrid();
} // end PreComputeGridInformation()
/**
* ******************** InitializeTransform ***********************
*
* Set the size of the initial control point grid and initialize
* the parameters to 0.
*/
template <class TElastix>
void BSplineStackTransform<TElastix>
::InitializeTransform( void )
{
/** Compute the B-spline grid region, origin, and spacing. */
ReducedDimensionRegionType gridRegion;
ReducedDimensionOriginType gridOrigin;
ReducedDimensionSpacingType gridSpacing;
ReducedDimensionDirectionType gridDirection;
this->m_GridScheduleComputer->GetBSplineGrid( 0,
gridRegion, gridSpacing, gridOrigin, gridDirection );
/** Set it in the BSplineTransform. */
this->m_BSplineDummySubTransform->SetGridRegion( gridRegion );
this->m_BSplineDummySubTransform->SetGridSpacing( gridSpacing );
this->m_BSplineDummySubTransform->SetGridOrigin( gridOrigin );
this->m_BSplineDummySubTransform->SetGridDirection( gridDirection );
/** Set all subtransforms to a copy of the dummy B-spline sub transform. */
this->m_BSplineStackTransform->SetAllSubTransforms( this->m_BSplineDummySubTransform );
/** Set initial parameters for the first resolution to 0.0. */
ParametersType initialParameters( this->GetNumberOfParameters() );
initialParameters.Fill( 0.0 );
this->m_Registration->GetAsITKBaseType()
->SetInitialTransformParametersOfNextLevel( initialParameters );
} // end InitializeTransform()
/**
* *********************** IncreaseScale ************************
*
* Upsample the grid of control points.
*/
template <class TElastix>
void BSplineStackTransform<TElastix>
::IncreaseScale( void )
{
/** What is the current resolution level? */
unsigned int level =
this->m_Registration->GetAsITKBaseType()->GetCurrentLevel();
/** Get first sub transform. */
ReducedDimensionBSplineTransformBasePointer firstsubtransform =
dynamic_cast< ReducedDimensionBSplineTransformBaseType * >(
this->m_BSplineStackTransform->GetSubTransform( 0 ).GetPointer() );
/** Get the current grid settings. */
ReducedDimensionOriginType currentGridOrigin = firstsubtransform->GetGridOrigin();
ReducedDimensionSpacingType currentGridSpacing = firstsubtransform->GetGridSpacing();
ReducedDimensionRegionType currentGridRegion = firstsubtransform->GetGridRegion();
ReducedDimensionDirectionType currentGridDirection = firstsubtransform->GetGridDirection();
/** Determine new required grid settings. */
ReducedDimensionOriginType requiredGridOrigin;
ReducedDimensionSpacingType requiredGridSpacing;
ReducedDimensionRegionType requiredGridRegion;
ReducedDimensionDirectionType requiredGridDirection;
this->m_GridScheduleComputer->GetBSplineGrid( level,
requiredGridRegion, requiredGridSpacing, requiredGridOrigin, requiredGridDirection );
/** Setup the GridUpsampler. */
this->m_GridUpsampler->SetCurrentGridOrigin( currentGridOrigin );
this->m_GridUpsampler->SetCurrentGridSpacing( currentGridSpacing );
this->m_GridUpsampler->SetCurrentGridRegion( currentGridRegion );
this->m_GridUpsampler->SetCurrentGridDirection( currentGridDirection );
this->m_GridUpsampler->SetRequiredGridOrigin( requiredGridOrigin );
this->m_GridUpsampler->SetRequiredGridSpacing( requiredGridSpacing );
this->m_GridUpsampler->SetRequiredGridRegion( requiredGridRegion );
this->m_GridUpsampler->SetRequiredGridDirection( requiredGridDirection );
for ( unsigned int t = 0; t < this->m_NumberOfSubTransforms; ++t )
{
/** Get sub transform pointer. */
ReducedDimensionBSplineTransformBasePointer subtransform =
dynamic_cast< ReducedDimensionBSplineTransformBaseType * >( this->m_BSplineStackTransform->GetSubTransform( t ).GetPointer() );
/** Get the lastest subtransform parameters. */
ParametersType latestParameters =
subtransform->GetParameters();
/** Compute the upsampled B-spline parameters. */
ParametersType upsampledParameters;
this->m_GridUpsampler->UpsampleParameters( latestParameters, upsampledParameters );
/** Set the new grid definition in the BSplineTransform. */
subtransform->SetGridOrigin( requiredGridOrigin );
subtransform->SetGridSpacing( requiredGridSpacing );
subtransform->SetGridRegion( requiredGridRegion );
subtransform->SetGridDirection( requiredGridDirection );
/** Set the initial parameters for the next level. */
subtransform->SetParametersByValue( upsampledParameters );
}
/** Set the initial parameters for the next level. */
this->m_Registration->GetAsITKBaseType()
->SetInitialTransformParametersOfNextLevel( this->GetParameters() );
} // end IncreaseScale()
/**
* ************************* ReadFromFile ************************
*/
template <class TElastix>
void BSplineStackTransform<TElastix>
::ReadFromFile( void )
{
/** Read spline order settings and initialize BSplineTransform. */
m_SplineOrder = 3;
this->GetConfiguration()->ReadParameter( m_SplineOrder,
"BSplineTransformSplineOrder", this->GetComponentLabel(), 0, 0 );
/** Read stack-spacing, stack-origin and number of sub-transforms. */
this->GetConfiguration()->ReadParameter( this->m_NumberOfSubTransforms,
"NumberOfSubTransforms", this->GetComponentLabel(), 0, 0 );
this->GetConfiguration()->ReadParameter( this->m_StackOrigin,
"StackOrigin", this->GetComponentLabel(), 0, 0 );
this->GetConfiguration()->ReadParameter( this->m_StackSpacing,
"StackSpacing", this->GetComponentLabel(), 0, 0 );
/** Initialize the right B-spline transform. */
InitializeBSplineTransform();
/** Set stack transform parameters. */
this->m_BSplineStackTransform->SetNumberOfSubTransforms( this->m_NumberOfSubTransforms );
this->m_BSplineStackTransform->SetStackOrigin( this->m_StackOrigin );
this->m_BSplineStackTransform->SetStackSpacing( this->m_StackSpacing );
/** Read and Set the Grid. */
/** Declarations. */
ReducedDimensionRegionType gridregion;
ReducedDimensionSizeType gridsize;
ReducedDimensionIndexType gridindex;
ReducedDimensionSpacingType gridspacing;
ReducedDimensionOriginType gridorigin;
ReducedDimensionDirectionType griddirection;
/** Fill everything with default values. */
gridsize.Fill( 1 );
gridindex.Fill( 0 );
gridspacing.Fill( 1.0 );
gridorigin.Fill( 0.0 );
griddirection.SetIdentity();
/** Get GridSize, GridIndex, GridSpacing and GridOrigin. */
for ( unsigned int i = 0; i < ReducedSpaceDimension; i++ )
{
this->m_Configuration->ReadParameter( gridsize[ i ], "GridSize", i );
this->m_Configuration->ReadParameter( gridindex[ i ], "GridIndex", i );
this->m_Configuration->ReadParameter( gridspacing[ i ], "GridSpacing", i );
this->m_Configuration->ReadParameter( gridorigin[ i ], "GridOrigin", i );
for ( unsigned int j = 0; j < ReducedSpaceDimension; j++ )
{
this->m_Configuration->ReadParameter( griddirection( j, i),
"GridDirection", i * ReducedSpaceDimension + j );
}
}
/** Set it all. */
gridregion.SetIndex( gridindex );
gridregion.SetSize( gridsize );
this->m_BSplineDummySubTransform->SetGridRegion( gridregion );
this->m_BSplineDummySubTransform->SetGridSpacing( gridspacing );
this->m_BSplineDummySubTransform->SetGridOrigin( gridorigin );
this->m_BSplineDummySubTransform->SetGridDirection( griddirection );
/** Set stack subtransforms. */
this->m_BSplineStackTransform->SetAllSubTransforms( this->m_BSplineDummySubTransform );
/** Call the ReadFromFile from the TransformBase.
* This must be done after setting the Grid, because later the
* ReadFromFile from TransformBase calls SetParameters, which
* checks the parameter-size, which is based on the GridSize.
*/
this->Superclass2::ReadFromFile();
} // end ReadFromFile()
/**
* ************************* WriteToFile ************************
*
* Saves the TransformParameters as a vector and if wanted
* also as a deformation field.
*/
template <class TElastix>
void BSplineStackTransform<TElastix>
::WriteToFile( const ParametersType & param ) const
{
/** Call the WriteToFile from the TransformBase. */
this->Superclass2::WriteToFile( param );
/** Add some BSplineTransform specific lines. */
xout["transpar"] << std::endl << "// BSplineStackTransform specific" << std::endl;
/** Get the GridSize, GridIndex, GridSpacing,
* GridOrigin, and GridDirection of this transform. */
ReducedDimensionBSplineTransformBasePointer firstSubTransform =
dynamic_cast< ReducedDimensionBSplineTransformBaseType * > ( this->m_BSplineStackTransform->GetSubTransform( 0 ).GetPointer() );
ReducedDimensionSizeType size = firstSubTransform->GetGridRegion().GetSize();
ReducedDimensionIndexType index = firstSubTransform->GetGridRegion().GetIndex();
ReducedDimensionSpacingType spacing = firstSubTransform->GetGridSpacing();
ReducedDimensionOriginType origin = firstSubTransform->GetGridOrigin();
ReducedDimensionDirectionType direction = firstSubTransform->GetGridDirection();
/** Write the GridSize of this transform. */
xout["transpar"] << "(GridSize ";
for ( unsigned int i = 0; i < ReducedSpaceDimension; i++ )
{
xout["transpar"] << size[ i ] << " ";
}
xout["transpar"] << ")" << std::endl;
/** Write the GridIndex of this transform. */
xout["transpar"] << "(GridIndex ";
for ( unsigned int i = 0; i < ReducedSpaceDimension; i++ )
{
xout["transpar"] << index[ i ] << " ";
}
xout["transpar"] << ")" << std::endl;
/** Set the precision of cout to 2, because GridSpacing and
* GridOrigin must have at least one digit precision.
*/
xout["transpar"] << std::setprecision( 10 );
/** Write the GridSpacing of this transform. */
xout["transpar"] << "(GridSpacing ";
for ( unsigned int i = 0; i < ReducedSpaceDimension; i++ )
{
xout["transpar"] << spacing[ i ] << " ";
}
xout["transpar"] << ")" << std::endl;
/** Write the GridOrigin of this transform. */
xout["transpar"] << "(GridOrigin ";
for ( unsigned int i = 0; i < ReducedSpaceDimension; i++ )
{
xout["transpar"] << origin[ i ] << " ";
}
xout["transpar"] << ")" << std::endl;
/** Write the GridDirection of this transform. */
xout["transpar"] << "(GridDirection";
for ( unsigned int i = 0; i < ReducedSpaceDimension; i++ )
{
for ( unsigned int j = 0; j < ReducedSpaceDimension; j++ )
{
xout["transpar"] << " " << direction(j,i);
}
}
xout["transpar"] << ")" << std::endl;
/** Write the spline order of this transform. */
xout["transpar"] << "(BSplineTransformSplineOrder " << m_SplineOrder << ")" << std::endl;
/** Write the stack spacing, stack origina and number of sub transforms. */
xout["transpar"] << "(StackSpacing " << this->m_BSplineStackTransform->GetStackSpacing() << ")" << std::endl;
xout["transpar"] << "(StackOrigin " << this->m_BSplineStackTransform->GetStackOrigin() << ")" << std::endl;
xout["transpar"] << "(NumberOfSubTransforms " << this->m_BSplineStackTransform->GetNumberOfSubTransforms() << ")" << std::endl;
/** Set the precision back to default value. */
xout["transpar"] << std::setprecision(
this->m_Elastix->GetDefaultOutputPrecision() );
} // end WriteToFile()
/**
* *********************** SetOptimizerScales ***********************
*
* Set the optimizer scales of the edge coefficients to infinity.
*/
template <class TElastix>
void BSplineStackTransform<TElastix>::
SetOptimizerScales( const unsigned int edgeWidth )
{
/** Some typedefs. */
typedef ImageRegionExclusionConstIteratorWithIndex<ImageType> IteratorType;
typedef typename RegistrationType::ITKBaseType ITKRegistrationType;
typedef typename ITKRegistrationType::OptimizerType OptimizerType;
typedef typename OptimizerType::ScalesType ScalesType;
typedef typename ScalesType::ValueType ScalesValueType;
/** Define new scales. */
const unsigned long numberOfParameters
= this->m_BSplineDummySubTransform->GetNumberOfParameters();
const unsigned long offset = numberOfParameters / SpaceDimension;
ScalesType newScales( numberOfParameters );
newScales.Fill( NumericTraits<ScalesValueType>::One );
const ScalesValueType infScale = 10000.0;
if ( edgeWidth == 0 )
{
/** Just set the unit scales into the optimizer. */
this->m_Registration->GetAsITKBaseType()->GetOptimizer()->SetScales( newScales );
return;
}
/** Get the grid region information and create a fake coefficient image. */
BSplineTransformBasePointer firstSubTransform = dynamic_cast< BSplineTransformBaseType * > ( this->m_BSplineStackTransform->GetSubTransform( 0 ).GetPointer() );
RegionType gridregion = firstSubTransform->GetGridRegion();
SizeType gridsize = gridregion.GetSize();
IndexType gridindex = gridregion.GetIndex();
ImagePointer coeff = ImageType::New();
coeff->SetRegions( gridregion );
coeff->Allocate();
/** Determine inset region. (so, the region with active parameters). */
RegionType insetgridregion;
SizeType insetgridsize;
IndexType insetgridindex;
for ( unsigned int i = 0; i < SpaceDimension; ++i )
{
insetgridsize[ i ] = static_cast<unsigned int>( vnl_math_max(
0, static_cast<int>( gridsize[ i ] - 2 * edgeWidth ) ) );
if ( insetgridsize[ i ] == 0 )
{
xl::xout["error"]
<< "ERROR: you specified a PassiveEdgeWidth of "
<< edgeWidth
<< ", while the total grid size in dimension "
<< i
<< " is only "
<< gridsize[ i ] << "." << std::endl;
itkExceptionMacro( << "ERROR: the PassiveEdgeWidth is too large!" );
}
insetgridindex[ i ] = gridindex[ i ] + edgeWidth;
}
insetgridregion.SetSize( insetgridsize );
insetgridregion.SetIndex( insetgridindex );
/** Set up iterator over the coefficient image. */
IteratorType cIt( coeff, coeff->GetLargestPossibleRegion() );
cIt.SetExclusionRegion( insetgridregion );
cIt.GoToBegin();
/** Set the scales to infinity that correspond to edge coefficients
* This (hopefully) makes sure they are not optimized during registration.
*/
while ( !cIt.IsAtEnd() )
{
const IndexType & index = cIt.GetIndex();
const unsigned long baseOffset = coeff->ComputeOffset( index );
for ( unsigned int i = 0; i < SpaceDimension; ++i )
{
const unsigned int scalesIndex = static_cast<unsigned int>(
baseOffset + i * offset );
newScales[ scalesIndex ] = infScale;
}
++cIt;
}
/** Set the scales into the optimizer. */
this->m_Registration->GetAsITKBaseType()->GetOptimizer()->SetScales( newScales );
} // end SetOptimizerScales()
} // end namespace elastix
#endif // end #ifndef __elxBSplineStackTransform_hxx
| [
"[email protected]"
]
| [
[
[
1,
770
]
]
]
|
e89ddc335cc7d72559b11004e174e6d665b9e542 | 619941b532c6d2987c0f4e92b73549c6c945c7e5 | /Include/Nuclex/Video/TextureCache.h | dd5c0a75c3cd75889fc3e4daa29e4afc63e684ad | []
| no_license | dzw/stellarengine | 2b70ddefc2827be4f44ec6082201c955788a8a16 | 2a0a7db2e43c7c3519e79afa56db247f9708bc26 | refs/heads/master | 2016-09-01T21:12:36.888921 | 2008-12-12T12:40:37 | 2008-12-12T12:40:37 | 36,939,169 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 5,838 | h | // //
// # # ### # # -= Nuclex Library =- //
// ## # # # ## ## TextureCache.h - Texture cache //
// ### # # ### //
// # ### # ### Caches images and smaller textures onto intermediary //
// # ## # # ## ## textures to reduce temporary objects and texture switching //
// # # ### # # R1 (C)2002-2004 Markus Ewald -> License.txt //
// //
#ifndef NUCLEX_VIDEO_TEXTURECACHE_H
#define NUCLEX_VIDEO_TEXTURECACHE_H
#include "Nuclex/Nuclex.h"
#include "Nuclex/Video/Video.h"
#include "Nuclex/Video/VideoDevice.h"
#include "Nuclex/Video/Texture.h"
#include "Nuclex/Video/Image.h"
#include "SigC++/sigc++.h"
#include <map>
namespace Nuclex { namespace Video {
// //
// Nuclex::Video::TextureCache //
// //
/// Dynamic texture cache
/** Caches multiple smaller textures on large cache textures to reduce the number of
required texture switches and drawPrimitive() calls for frame.
@todo If a new font is used, the frame rate may crash down temporarily due to locking the
cache texture up to 50 times in a row. Maybe the lock could be kept active until
the cache texture is required for rendering ?
After profiling, it seems lock is no problem at all, compared to the time taken
for copying the image pixels :-/
*/
class TextureCache {
public:
typedef std::pair<shared_ptr<Texture>, Box2<float> > CacheSlot;
typedef sigc::slot<void, const Surface::LockInfo &> UpdateCacheSlot;
/// Constructor
NUCLEX_API TextureCache(const shared_ptr<VideoDevice> &spVideoDevice);
//
// TextureCache implementation
//
public:
/// Maximum size an image is allowed to have in order to fit in the cache
NUCLEX_API Point2<size_t> getMaxResolution() const { return m_Resolution; }
/// Retrieves the number of cache textures used
NUCLEX_API size_t getTextureCount() const { return m_CacheTextures.size(); }
/// @todo For debugging purpose. Remove it!
NUCLEX_API const shared_ptr<Texture> &getTexture(size_t Index) const {
return m_CacheTextures.at(Index)->spTexture;
}
/// Cache a texture
NUCLEX_API CacheSlot cache(const shared_ptr<Texture> &spTexture);
/// Cache an arbitrary size image
NUCLEX_API CacheSlot cache(const shared_ptr<Surface> &spSurface);
/// Cache a random thing ;)
NUCLEX_API CacheSlot cache(
Cacheable::CacheID ID, const Point2<size_t> Size, UpdateCacheSlot UpdateCallback
);
/// Try to clean the cache
NUCLEX_API void flush();
private:
/// Surface with cached images
struct SharedTexture {
/// Optimized rectangle allocator
struct RectanglePacker {
/// Constructor
RectanglePacker(const Point2<size_t> &Size);
/// Allocate space for a rectangle
Point2<size_t> placeRectangle(const Point2<size_t> &Size);
private:
Point2<size_t> m_Size; ///< Total packing area size
size_t m_lCurrentLine; ///< Current packing line
size_t m_lMaxHeight; ///< Largest rectangle in current line
size_t m_lXPosition; ///< Offset within current line
};
/// Constructor
SharedTexture(const shared_ptr<Texture> &spTexture) :
Packer(spTexture->getSize()),
spTexture(spTexture) {}
RectanglePacker Packer; ///< Rectangle allocator
shared_ptr<Texture> spTexture; ///< Texture with cached images
};
/// An entry in the texture cache
struct CacheEntry {
/// Initializes a texture cache entry
CacheEntry(const weak_ptr<void> &wpSurface, const shared_ptr<Texture> &spCacheTexture,
Box2<float> Location) :
wpSurface(wpSurface), spCacheTexture(spCacheTexture), Location(Location) {}
weak_ptr<void> wpSurface; ///< The object itself
shared_ptr<Texture> spCacheTexture; ///< Used cache texture
Box2<float> Location; ///< Location of the cached object
};
/// Vector of shared textures
typedef std::vector<shared_ptr<SharedTexture> > SharedTextureVector;
/// Map of cache entries by id
typedef std::map<Cacheable::CacheID, CacheEntry> CacheEntryMap;
/// Appends a new shared cache texture to the cache
void appendSharedTexture();
/// Caches an arbitrary size surface
CacheEntryMap::iterator addToCache(const shared_ptr<Surface> &spSurface);
shared_ptr<VideoDevice> m_spVideoDevice; ///< Owner of the VertexDrawer
SharedTextureVector m_CacheTextures; ///< The cache's textures
shared_ptr<SharedTexture> m_spCurrentTexture; ///< Current cache texture
Point2<size_t> m_Resolution; ///< Cache texture resolution
CacheEntryMap m_CacheEntries; ///< Texture cache entries
};
}} // namespace Nuclex::Video
#endif // NUCLEX_VIDEO_VIDEOSERVER_H
| [
"ctuoMail@5f320639-c338-0410-82ad-c55551ec1e38"
]
| [
[
[
1,
126
]
]
]
|
14930bc628138d769cdf3724067256d4e7a7bb08 | 3ec3b97044e4e6a87125470cfa7eef535f26e376 | /darkbits-secret_of_fantasy_2/src/BackgroundEntity.hpp | 2447c4dacf093e644707cddb5f266828f44f4468 | []
| no_license | strategist922/TINS-Is-not-speedhack-2010 | 6d7a43ebb9ab3b24208b3a22cbcbb7452dae48af | 718b9d037606f0dbd9eb6c0b0e021eeb38c011f9 | refs/heads/master | 2021-01-18T14:14:38.724957 | 2010-10-17T14:04:40 | 2010-10-17T14:04:40 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 200 | hpp | #pragma once
#include "Entity.hpp"
class BackgroundEntity : public Entity {
virtual float getZOrder();
virtual int getX();
virtual int getY();
virtual bool isToBeDestroyed();
}; | [
"[email protected]"
]
| [
[
[
1,
14
]
]
]
|
df9721dccf5fa4a35b5b4f284f09cc38245c58a4 | fd3f2268460656e395652b11ae1a5b358bfe0a59 | /srchybrid/SharedFileList.cpp | 6f06cdee9751af23348785ce86ce1592f8818f79 | []
| no_license | mikezhoubill/emule-gifc | e1cc6ff8b1bb63197bcfc7e67c57cfce0538ff60 | 46979cf32a313ad6d58603b275ec0b2150562166 | refs/heads/master | 2021-01-10T20:37:07.581465 | 2011-08-13T13:58:37 | 2011-08-13T13:58:37 | 32,465,033 | 4 | 2 | null | null | null | null | UTF-8 | C++ | false | false | 76,649 | cpp | //this file is part of eMule
//Copyright (C)2002-2008 Merkur ( strEmail.Format("%s@%s", "devteam", "emule-project.net") / http://www.emule-project.net )
//
//This program is free software; you can redistribute it and/or
//modify it under the terms of the GNU General Public License
//as published by the Free Software Foundation; either
//version 2 of the License, or (at your option) any later version.
//
//This program is distributed in the hope that it will be useful,
//but WITHOUT ANY WARRANTY; without even the implied warranty of
//MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
//GNU General Public License for more details.
//
//You should have received a copy of the GNU General Public License
//along with this program; if not, write to the Free Software
//Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.
#include "stdafx.h"
#include <io.h>
#include <sys/stat.h>
#include "emule.h"
#include "SharedFileList.h"
#include "KnownFileList.h"
#include "Packets.h"
#include "Kademlia/Kademlia/Kademlia.h"
#include "kademlia/kademlia/search.h"
#include "kademlia/kademlia/SearchManager.h"
#include "kademlia/kademlia/prefs.h"
#include "kademlia/kademlia/Tag.h"
#include "DownloadQueue.h"
#include "Statistics.h"
#include "Preferences.h"
#include "OtherFunctions.h"
#include "KnownFile.h"
#include "Sockets.h"
#include "SafeFile.h"
#include "Server.h"
#include "UpDownClient.h"
#include "PartFile.h"
#include "emuledlg.h"
#include "SharedFilesWnd.h"
#include "StringConversion.h"
#include "ClientList.h"
#include "Log.h"
#include "Collection.h"
#include "kademlia/kademlia/UDPFirewallTester.h"
#include "md5sum.h"
#include "SR13-ImportParts.h" //MORPH - Added by SiRoB, Import Parts [SR13] - added by zz_fly
//Xman advanced upload-priority
#include "UploadQueue.h"
#ifdef _DEBUG
#define new DEBUG_NEW
#undef THIS_FILE
static char THIS_FILE[] = __FILE__;
#endif
typedef CSimpleArray<CKnownFile*> CSimpleKnownFileArray;
#define SHAREDFILES_FILE _T("sharedfiles.dat")
///////////////////////////////////////////////////////////////////////////////
// CPublishKeyword
class CPublishKeyword
{
public:
CPublishKeyword(const Kademlia::CKadTagValueString& rstrKeyword)
{
m_strKeyword = rstrKeyword;
// min. keyword char is allowed to be < 3 in some cases (see also 'CSearchManager::GetWords')
//ASSERT( rstrKeyword.GetLength() >= 3 );
ASSERT( !rstrKeyword.IsEmpty() );
KadGetKeywordHash(rstrKeyword, &m_nKadID);
SetNextPublishTime(0);
SetPublishedCount(0);
}
const Kademlia::CUInt128& GetKadID() const { return m_nKadID; }
const Kademlia::CKadTagValueString& GetKeyword() const { return m_strKeyword; }
int GetRefCount() const { return m_aFiles.GetSize(); }
const CSimpleKnownFileArray& GetReferences() const { return m_aFiles; }
UINT GetNextPublishTime() const { return m_tNextPublishTime; }
void SetNextPublishTime(UINT tNextPublishTime) { m_tNextPublishTime = tNextPublishTime; }
UINT GetPublishedCount() const { return m_uPublishedCount; }
void SetPublishedCount(UINT uPublishedCount) { m_uPublishedCount = uPublishedCount; }
void IncPublishedCount() { m_uPublishedCount++; }
BOOL AddRef(CKnownFile* pFile)
{
if (m_aFiles.Find(pFile) != -1)
{
ASSERT(0);
return FALSE;
}
return m_aFiles.Add(pFile);
}
int RemoveRef(CKnownFile* pFile)
{
m_aFiles.Remove(pFile);
return m_aFiles.GetSize();
}
void RemoveAllReferences()
{
m_aFiles.RemoveAll();
}
void RotateReferences(int iRotateSize)
{
if (m_aFiles.GetSize() > iRotateSize)
{
CKnownFile** ppRotated = (CKnownFile**)malloc(m_aFiles.m_nAllocSize * sizeof(*m_aFiles.GetData()));
if (ppRotated != NULL)
{
memcpy(ppRotated, m_aFiles.GetData() + iRotateSize, (m_aFiles.GetSize() - iRotateSize) * sizeof(*m_aFiles.GetData()));
memcpy(ppRotated + m_aFiles.GetSize() - iRotateSize, m_aFiles.GetData(), iRotateSize * sizeof(*m_aFiles.GetData()));
free(m_aFiles.GetData());
m_aFiles.m_aT = ppRotated;
}
}
}
protected:
Kademlia::CKadTagValueString m_strKeyword;
Kademlia::CUInt128 m_nKadID;
UINT m_tNextPublishTime;
UINT m_uPublishedCount;
CSimpleKnownFileArray m_aFiles;
};
///////////////////////////////////////////////////////////////////////////////
// CPublishKeywordList
class CPublishKeywordList
{
public:
CPublishKeywordList();
~CPublishKeywordList();
void AddKeywords(CKnownFile* pFile);
void RemoveKeywords(CKnownFile* pFile);
void RemoveAllKeywords();
void RemoveAllKeywordReferences();
void PurgeUnreferencedKeywords();
int GetCount() const { return m_lstKeywords.GetCount(); }
CPublishKeyword* GetNextKeyword();
void ResetNextKeyword();
UINT GetNextPublishTime() const { return m_tNextPublishKeywordTime; }
void SetNextPublishTime(UINT tNextPublishKeywordTime) { m_tNextPublishKeywordTime = tNextPublishKeywordTime; }
#ifdef _DEBUG
void Dump();
#endif
protected:
// can't use a CMap - too many disadvantages in processing the 'list'
//CTypedPtrMap<CMapStringToPtr, CString, CPublishKeyword*> m_lstKeywords;
CTypedPtrList<CPtrList, CPublishKeyword*> m_lstKeywords;
POSITION m_posNextKeyword;
UINT m_tNextPublishKeywordTime;
CPublishKeyword* FindKeyword(const CStringW& rstrKeyword, POSITION* ppos = NULL) const;
};
CPublishKeywordList::CPublishKeywordList()
{
ResetNextKeyword();
SetNextPublishTime(0);
}
CPublishKeywordList::~CPublishKeywordList()
{
RemoveAllKeywords();
}
CPublishKeyword* CPublishKeywordList::GetNextKeyword()
{
if (m_posNextKeyword == NULL)
{
m_posNextKeyword = m_lstKeywords.GetHeadPosition();
if (m_posNextKeyword == NULL)
return NULL;
}
return m_lstKeywords.GetNext(m_posNextKeyword);
}
void CPublishKeywordList::ResetNextKeyword()
{
m_posNextKeyword = m_lstKeywords.GetHeadPosition();
}
CPublishKeyword* CPublishKeywordList::FindKeyword(const CStringW& rstrKeyword, POSITION* ppos) const
{
POSITION pos = m_lstKeywords.GetHeadPosition();
while (pos)
{
POSITION posLast = pos;
CPublishKeyword* pPubKw = m_lstKeywords.GetNext(pos);
if (pPubKw->GetKeyword() == rstrKeyword)
{
if (ppos)
*ppos = posLast;
return pPubKw;
}
}
return NULL;
}
void CPublishKeywordList::AddKeywords(CKnownFile* pFile)
{
const Kademlia::WordList& wordlist = pFile->GetKadKeywords();
//ASSERT( wordlist.size() > 0 );
Kademlia::WordList::const_iterator it;
for (it = wordlist.begin(); it != wordlist.end(); it++)
{
const CStringW& strKeyword = *it;
CPublishKeyword* pPubKw = FindKeyword(strKeyword);
if (pPubKw == NULL)
{
pPubKw = new CPublishKeyword(strKeyword);
m_lstKeywords.AddTail(pPubKw);
SetNextPublishTime(0);
}
if(pPubKw->AddRef(pFile) && pPubKw->GetNextPublishTime() > MIN2S(30))
{
// User may be adding and removing files, so if this is a keyword that
// has already been published, we reduce the time, but still give the user
// enough time to finish what they are doing.
// If this is a hot node, the Load list will prevent from republishing.
pPubKw->SetNextPublishTime(MIN2S(30));
}
}
}
void CPublishKeywordList::RemoveKeywords(CKnownFile* pFile)
{
const Kademlia::WordList& wordlist = pFile->GetKadKeywords();
//ASSERT( wordlist.size() > 0 );
Kademlia::WordList::const_iterator it;
for (it = wordlist.begin(); it != wordlist.end(); it++)
{
const CStringW& strKeyword = *it;
POSITION pos;
CPublishKeyword* pPubKw = FindKeyword(strKeyword, &pos);
if (pPubKw != NULL)
{
if (pPubKw->RemoveRef(pFile) == 0)
{
if (pos == m_posNextKeyword)
(void)m_lstKeywords.GetNext(m_posNextKeyword);
m_lstKeywords.RemoveAt(pos);
delete pPubKw;
SetNextPublishTime(0);
}
}
}
}
void CPublishKeywordList::RemoveAllKeywords()
{
POSITION pos = m_lstKeywords.GetHeadPosition();
while (pos)
delete m_lstKeywords.GetNext(pos);
m_lstKeywords.RemoveAll();
ResetNextKeyword();
SetNextPublishTime(0);
}
void CPublishKeywordList::RemoveAllKeywordReferences()
{
POSITION pos = m_lstKeywords.GetHeadPosition();
while (pos)
m_lstKeywords.GetNext(pos)->RemoveAllReferences();
}
void CPublishKeywordList::PurgeUnreferencedKeywords()
{
POSITION pos = m_lstKeywords.GetHeadPosition();
while (pos)
{
POSITION posLast = pos;
CPublishKeyword* pPubKw = m_lstKeywords.GetNext(pos);
if (pPubKw->GetRefCount() == 0)
{
if (posLast == m_posNextKeyword)
(void)m_lstKeywords.GetNext(m_posNextKeyword);
m_lstKeywords.RemoveAt(posLast);
delete pPubKw;
SetNextPublishTime(0);
}
}
}
#ifdef _DEBUG
void CPublishKeywordList::Dump()
{
int i = 0;
POSITION pos = m_lstKeywords.GetHeadPosition();
while (pos)
{
CPublishKeyword* pPubKw = m_lstKeywords.GetNext(pos);
TRACE(_T("%3u: %-10ls ref=%u %s\n"), i, pPubKw->GetKeyword(), pPubKw->GetRefCount(), CastSecondsToHM(pPubKw->GetNextPublishTime()));
i++;
}
}
#endif
///////////////////////////////////////////////////////////////////////////////
// CAddFileThread
IMPLEMENT_DYNCREATE(CAddFileThread, CWinThread)
CAddFileThread::CAddFileThread()
{
m_pOwner = NULL;
m_partfile = NULL;
}
void CAddFileThread::SetValues(CSharedFileList* pOwner, LPCTSTR directory, LPCTSTR filename, LPCTSTR strSharedDir, CPartFile* partfile)
{
m_pOwner = pOwner;
m_strDirectory = directory;
m_strFilename = filename;
m_partfile = partfile;
m_strSharedDir = strSharedDir;
}
BOOL CAddFileThread::InitInstance()
{
InitThreadLocale();
return TRUE;
}
int CAddFileThread::Run()
{
DbgSetThreadName("Hashing %s", m_strFilename);
if ( !(m_pOwner || m_partfile) || m_strFilename.IsEmpty() || !theApp.emuledlg->IsRunning() )
return 0;
//Xman
// BEGIN SLUGFILLER: SafeHash
CReadWriteLock lock(&theApp.m_threadlock);
if (!lock.ReadLock(0))
return 0;
// END SLUGFILLER: SafeHash
CoInitialize(NULL);
// locking that hashing thread is needed because we may create a couple of those threads at startup when rehashing
// potentially corrupted downloading part files. if all those hash threads would run concurrently, the io-system would be
// under very heavy load and slowly progressing
//Xman
// SLUGFILLER: SafeHash remove - locking code removed, unnecessary
/*
CSingleLock sLock1(&theApp.hashing_mut); // only one filehash at a time
sLock1.Lock();
*/
//Xman End
//MORPH START - Added by SiRoB, Import Parts [SR13] - added by zz_fly
if (m_partfile && m_partfile->GetFileOp() == PFOP_SR13_IMPORTPARTS){
SR13_ImportParts();
//sLock1.Unlock(); //SafeHash
CoUninitialize();
return 0;
}
// TODO: Test case when suposeddly correct, but actually broken verified data is
// completed with import and see if file recovers its started/paused state correctly
// after failed completion.
//MORPH END - Added by SiRoB, Import Parts [SR13]
CString strFilePath;
_tmakepathlimit(strFilePath.GetBuffer(MAX_PATH), NULL, m_strDirectory, m_strFilename, NULL);
strFilePath.ReleaseBuffer();
if (m_partfile)
Log(GetResString(IDS_HASHINGFILE) + _T(" \"%s\" \"%s\""), m_partfile->GetFileName(), strFilePath);
else
Log(GetResString(IDS_HASHINGFILE) + _T(" \"%s\""), strFilePath);
CKnownFile* newrecord = new CKnownFile();
//zz_fly :: minor issue in case of shutdown while still hashing :: WiZaRd :: start
/*
if (newrecord->CreateFromFile(m_strDirectory, m_strFilename, m_partfile) && theApp.emuledlg && theApp.emuledlg->IsRunning()) // SLUGFILLER: SafeHash - in case of shutdown while still hashing
*/
if (newrecord->CreateFromFile(m_strDirectory, m_strFilename, m_partfile))
//zz_fly :: end
{
newrecord->SetSharedDirectory(m_strSharedDir);
if (m_partfile && m_partfile->GetFileOp() == PFOP_HASHING)
m_partfile->SetFileOp(PFOP_NONE);
if (theApp.emuledlg == NULL || !theApp.emuledlg->IsRunning() || // SLUGFILLER: SafeHash - in case of shutdown while still hashing
!PostMessage(theApp.emuledlg->m_hWnd, TM_FINISHEDHASHING, (m_pOwner ? 0: (WPARAM)m_partfile), (LPARAM)newrecord))
delete newrecord;
}
else
{
//zz_fly :: minor issue in case of shutdown while still hashing :: WiZaRd :: start
/*
if (theApp.emuledlg && theApp.emuledlg->IsRunning())
{
*/
//zz_fly :: end
if (m_partfile && m_partfile->GetFileOp() == PFOP_HASHING)
m_partfile->SetFileOp(PFOP_NONE);
//}
// SLUGFILLER: SafeHash - inform main program of hash failure
if (m_pOwner && theApp.emuledlg && theApp.emuledlg->IsRunning())
{
UnknownFile_Struct* hashed = new UnknownFile_Struct;
hashed->strDirectory = m_strDirectory;
hashed->strName = m_strFilename;
if (!PostMessage(theApp.emuledlg->m_hWnd, TM_HASHFAILED, 0, (LPARAM)hashed))
delete hashed;
}
// SLUGFILLER: SafeHash
delete newrecord;
}
//Xman
// SLUGFILLER: SafeHash remove - locking code removed, unnecessary
/*
sLock1.Unlock();
*/
//Xman End
CoUninitialize();
return 0;
}
///////////////////////////////////////////////////////////////////////////////
// CSharedFileList
CSharedFileList::CSharedFileList(CServerConnect* in_server)
{
server = in_server;
output = 0;
m_Files_map.InitHashTable(1031);
m_keywords = new CPublishKeywordList;
m_lastPublishED2K = 0;
m_lastPublishED2KFlag = true;
m_currFileSrc = 0;
m_currFileNotes = 0;
m_lastPublishKadSrc = 0;
m_lastPublishKadNotes = 0;
m_currFileKey = 0;
bHaveSingleSharedFiles = false;
//Xman advanced upload-priority
m_lastavgPercent = 0;
m_avg_virtual_sources = 0;
m_avg_client_on_uploadqueue = 0;
//Xman end
// SLUGFILLER: SafeHash remove - delay load shared files
/*
LoadSingleSharedFilesList();
FindSharedFiles();
*/
// SLUGFILLER End
m_dwFile_map_updated = 0; // requpfile optimization [SiRoB] - Stulle
}
CSharedFileList::~CSharedFileList(){
while (!waitingforhash_list.IsEmpty()){
UnknownFile_Struct* nextfile = waitingforhash_list.RemoveHead();
delete nextfile;
}
// SLUGFILLER: SafeHash
while (!currentlyhashing_list.IsEmpty()){
UnknownFile_Struct* nextfile = currentlyhashing_list.RemoveHead();
delete nextfile;
}
// SLUGFILLER: SafeHash
delete m_keywords;
// ==> Automatic shared files updater [MoNKi] - Stulle
/*
#ifdef _BETA
// On Beta builds we created a testfile, delete it when closing eMule
CString tempDir = thePrefs.GetMuleDirectory(EMULE_INCOMINGDIR);
if (tempDir.Right(1)!=_T("\\"))
tempDir+=_T("\\");
CString strBetaFileName;
strBetaFileName.Format(_T("eMule%u.%u%c.%u Beta Testfile "), CemuleApp::m_nVersionMjr,
CemuleApp::m_nVersionMin, _T('a') + CemuleApp::m_nVersionUpd, CemuleApp::m_nVersionBld);
MD5Sum md5(strBetaFileName);
strBetaFileName += md5.GetHash().Left(6) + _T(".txt");
DeleteFile(tempDir + strBetaFileName);
#endif
*/
// <== Automatic shared files updater [MoNKi] - Stulle
}
void CSharedFileList::CopySharedFileMap(CMap<CCKey,const CCKey&,CKnownFile*,CKnownFile*> &Files_Map)
{
if (!m_Files_map.IsEmpty())
{
POSITION pos = m_Files_map.GetStartPosition();
while (pos)
{
CCKey key;
CKnownFile* cur_file;
m_Files_map.GetNextAssoc(pos, key, cur_file);
Files_Map.SetAt(key, cur_file);
}
}
}
void CSharedFileList::FindSharedFiles()
{
//Xman
// BEGIN SLUGFILLER: SafeHash
while (!waitingforhash_list.IsEmpty()) {
UnknownFile_Struct* nextfile = waitingforhash_list.RemoveHead();
delete nextfile;
}
// END SLUGFILLER: SafeHash
// SLUGFILLER: SafeHash remove - only called after the download queue is created
/*
if (!m_Files_map.IsEmpty())
*/
{
CSingleLock listlock(&m_mutWriteList);
POSITION pos = m_Files_map.GetStartPosition();
while (pos)
{
CCKey key;
CKnownFile* cur_file;
m_Files_map.GetNextAssoc(pos, key, cur_file);
if (cur_file->IsKindOf(RUNTIME_CLASS(CPartFile))
&& !theApp.downloadqueue->IsPartFile(cur_file)
&& !theApp.knownfiles->IsFilePtrInList(cur_file)
&& _taccess(cur_file->GetFilePath(), 0) == 0)
continue;
m_UnsharedFiles_map.SetAt(CSKey(cur_file->GetFileHash()), true);
listlock.Lock();
m_Files_map.RemoveKey(key);
m_dwFile_map_updated = GetTickCount(); // requpfile optimization [SiRoB] - Stulle
listlock.Unlock();
theApp.uploadqueue->SetSuperiorInQueueDirty(); // Keep Sup clients in up if there is no other sup client in queue [Stulle] - Stulle
}
ASSERT( theApp.downloadqueue );
if (theApp.downloadqueue)
theApp.downloadqueue->AddPartFilesToShare(); // read partfiles
}
// khaos::kmod+ Fix: Shared files loaded multiple times.
CStringList l_sAdded;
CString tempDir;
CString ltempDir;
tempDir = thePrefs.GetMuleDirectory(EMULE_INCOMINGDIR);
if (tempDir.Right(1)!=_T("\\"))
tempDir+=_T("\\");
// ==> Automatic shared files updater [MoNKi] - Stulle
/*
#ifdef _BETA
// In Betaversion we create a testfile which is published in order to make testing easier
// by allowing to easily find files which are published and shared by "new" nodes
CStdioFile f;
CString strBetaFileName;
strBetaFileName.Format(_T("eMule%u.%u%c.%u Beta Testfile "), CemuleApp::m_nVersionMjr,
CemuleApp::m_nVersionMin, _T('a') + CemuleApp::m_nVersionUpd, CemuleApp::m_nVersionBld);
MD5Sum md5(strBetaFileName);
strBetaFileName += md5.GetHash().Left(6) + _T(".txt");
if (!f.Open(tempDir + strBetaFileName, CFile::modeCreate | CFile::modeWrite | CFile::shareDenyWrite))
ASSERT( false );
else
{
try {
// do not translate the content!
f.WriteString(strBetaFileName + '\n'); // garantuees a different hash on different versions
f.WriteString(_T("This file is automatically created by eMule Beta versions to help the developers testing and debugging new the new features. eMule will delete this file when exiting, otherwise you can remove this file at any time.\nThanks for beta testing eMule :)"));
f.Close();
}
catch (CFileException* ex) {
ASSERT(0);
ex->Delete();
}
}
#endif
*/
// <== Automatic shared files updater [MoNKi] - Stulle
AddFilesFromDirectory(tempDir);
tempDir.MakeLower();
l_sAdded.AddHead( tempDir );
// ==> Smart Category Control (SCC) [khaos/SiRoB/Stulle] - Stulle
/*
for (int ix=1;ix<thePrefs.GetCatCount();ix++)
*/
for (int ix=0;ix<thePrefs.GetCatCount();ix++)
// <== Smart Category Control (SCC) [khaos/SiRoB/Stulle] - Stulle
{
tempDir=CString( thePrefs.GetCatPath(ix) );
if (tempDir.Right(1)!=_T("\\"))
tempDir+=_T("\\");
ltempDir=tempDir;
ltempDir.MakeLower();
if( l_sAdded.Find( ltempDir ) ==NULL ) {
l_sAdded.AddHead( ltempDir );
AddFilesFromDirectory(tempDir);
}
}
for (POSITION pos = thePrefs.shareddir_list.GetHeadPosition();pos != 0;)
{
tempDir = thePrefs.shareddir_list.GetNext(pos);
if (tempDir.Right(1)!=_T("\\"))
tempDir+=_T("\\");
ltempDir= tempDir;
ltempDir.MakeLower();
if( l_sAdded.Find( ltempDir ) ==NULL ) {
l_sAdded.AddHead( ltempDir );
AddFilesFromDirectory(tempDir);
}
}
// add all single shared files
for (POSITION pos = m_liSingleSharedFiles.GetHeadPosition(); pos != NULL; m_liSingleSharedFiles.GetNext(pos))
CheckAndAddSingleFile(m_liSingleSharedFiles.GetAt(pos));
// khaos::kmod-
if (waitingforhash_list.IsEmpty())
AddLogLine(false,GetResString(IDS_SHAREDFOUND), m_Files_map.GetCount());
else
AddLogLine(false,GetResString(IDS_SHAREDFOUNDHASHING), m_Files_map.GetCount(), waitingforhash_list.GetCount());
HashNextFile();
}
void CSharedFileList::AddFilesFromDirectory(const CString& rstrDirectory)
{
CFileFind ff;
CString strSearchPath(rstrDirectory);
PathAddBackslash(strSearchPath.GetBuffer(strSearchPath.GetLength() + 1));
strSearchPath.ReleaseBuffer();
strSearchPath += _T("*");
bool end = !ff.FindFile(strSearchPath, 0);
if (end) {
DWORD dwError = GetLastError();
if (dwError != ERROR_FILE_NOT_FOUND)
LogWarning(GetResString(IDS_ERR_SHARED_DIR), rstrDirectory, GetErrorMessage(dwError));
return;
}
while (!end)
{
end = !ff.FindNextFile();
CheckAndAddSingleFile(ff);
}
ff.Close();
}
bool CSharedFileList::AddSingleSharedFile(const CString& rstrFilePath, bool bNoUpdate)
// ==> Automatic shared files updater [MoNKi] - Stulle
{
int iDoAsfuReset = -1;
return AddSingleSharedFile(rstrFilePath,bNoUpdate,iDoAsfuReset);
}
bool CSharedFileList::AddSingleSharedFile(const CString& rstrFilePath, bool bNoUpdate, int &iDoAsfuReset)
// <== Automatic shared files updater [MoNKi] - Stulle
{
bool bExclude = false;
bool bShared = false;
// first check if we are explicty exluding this file
for (POSITION pos = m_liSingleExcludedFiles.GetHeadPosition(); pos != NULL; m_liSingleExcludedFiles.GetNext(pos) )
{
if (rstrFilePath.CompareNoCase(m_liSingleExcludedFiles.GetAt(pos)) == 0)
{
bExclude = true;
m_liSingleExcludedFiles.RemoveAt(pos);
break;
}
}
// check if we share this file in general
bShared = ShouldBeShared(rstrFilePath.Left(rstrFilePath.ReverseFind('\\') + 1), rstrFilePath, false);
if (bShared && !bExclude){
// we should share this file already
return false;
}
else if (!bShared){
// the directory is not shared, so we need a special entry
m_liSingleSharedFiles.AddTail(rstrFilePath);
// ==> Automatic shared files updater [MoNKi] - Stulle
if(!bNoUpdate)
{
if(iDoAsfuReset == -1) // checked checkbox to share single file
{
if(thePrefs.GetDirectoryWatcher() && thePrefs.GetSingleSharedDirWatcher())
theApp.ResetDirectoryWatcher();
}
else if(iDoAsfuReset == 0) // adding single files via drop
iDoAsfuReset = 1; // we would have resetted but don't do so just now
}
// <== Automatic shared files updater [MoNKi] - Stulle
}
return bNoUpdate || CheckAndAddSingleFile(rstrFilePath);
}
bool CSharedFileList::CheckAndAddSingleFile(const CString& rstrFilePath)
{
CFileFind ff;
bool end = !ff.FindFile(rstrFilePath, 0);
if (end) {
DWORD dwError = GetLastError();
if (dwError != ERROR_FILE_NOT_FOUND)
LogWarning(GetResString(IDS_ERR_SHARED_DIR), rstrFilePath, GetErrorMessage(dwError));
return false;
}
ff.FindNextFile();
CheckAndAddSingleFile(ff);
ff.Close();
// SLUGFILLER: SafeHash - only hash when there is something to hash
if (!waitingforhash_list.IsEmpty())
// SLUGFILLER: SafeHash - only hash when there is something to hash
HashNextFile();
bHaveSingleSharedFiles = true;
// GUI updating needs to be done by caller
return true;
}
bool CSharedFileList::SafeAddKFile(CKnownFile* toadd, bool bOnlyAdd)
{
// >> add by Ken
if (IsGIFCFileName(toadd->GetFileName()))
return false;
// << add by Ken
bool bAdded = false;
RemoveFromHashing(toadd); // SLUGFILLER: SafeHash - hashed ok, remove from list, in case it was on the list
bAdded = AddFile(toadd);
//Xman advanced upload-priority
if(bAdded)
{
toadd->CheckAUPFilestats(true);
}
//Xman end
if (bOnlyAdd)
return bAdded;
if (bAdded && output)
{
output->AddFile(toadd);
//Xman [MoNKi: -Downloaded History-]
if(!toadd->IsPartFile())
theApp.emuledlg->sharedfileswnd->historylistctrl.AddFile(toadd);
//Xman end
output->ShowFilesCount();
}
m_lastPublishED2KFlag = true;
return bAdded;
}
void CSharedFileList::RepublishFile(CKnownFile* pFile)
{
CServer* pCurServer = server->GetCurrentServer();
if (pCurServer && (pCurServer->GetTCPFlags() & SRV_TCPFLG_COMPRESSION))
{
m_lastPublishED2KFlag = true;
pFile->SetPublishedED2K(false); // FIXME: this creates a wrong 'No' for the ed2k shared info in the listview until the file is shared again.
}
}
bool CSharedFileList::AddFile(CKnownFile* pFile)
{
ASSERT( pFile->GetFileIdentifier().HasExpectedMD4HashCount() );
ASSERT( !pFile->IsKindOf(RUNTIME_CLASS(CPartFile)) || !STATIC_DOWNCAST(CPartFile, pFile)->m_bMD4HashsetNeeded );
ASSERT( !pFile->IsShellLinked() || ShouldBeShared(pFile->GetSharedDirectory(), _T(""), false) );
CCKey key(pFile->GetFileHash());
CKnownFile* pFileInMap;
if (m_Files_map.Lookup(key, pFileInMap))
{
TRACE(_T("%hs: File already in shared file list: %s \"%s\" \"%s\"\n"), __FUNCTION__, md4str(pFileInMap->GetFileHash()), pFileInMap->GetFileName(), pFileInMap->GetFilePath());
TRACE(_T("%hs: File to add: %s \"%s\" \"%s\"\n"), __FUNCTION__, md4str(pFile->GetFileHash()), pFile->GetFileName(), pFile->GetFilePath());
if (!pFileInMap->IsKindOf(RUNTIME_CLASS(CPartFile)) || theApp.downloadqueue->IsPartFile(pFileInMap))
LogWarning(GetResString(IDS_ERR_DUPL_FILES), pFileInMap->GetFilePath(), pFile->GetFilePath());
return false;
}
m_UnsharedFiles_map.RemoveKey(CSKey(pFile->GetFileHash()));
CSingleLock listlock(&m_mutWriteList);
listlock.Lock();
m_Files_map.SetAt(key, pFile);
m_dwFile_map_updated = GetTickCount(); // requpfile optimization [SiRoB] - Stulle
listlock.Unlock();
theApp.uploadqueue->SetSuperiorInQueueDirty(); // Keep Sup clients in up if there is no other sup client in queue [Stulle] - Stulle
bool bKeywordsNeedUpdated = true;
//Xman Code Improvement for HasCollectionExtention
/*
if(!pFile->IsPartFile() && !pFile->m_pCollection && CCollection::HasCollectionExtention(pFile->GetFileName()))
*/
if(!pFile->IsPartFile() && !pFile->m_pCollection && pFile->HasCollectionExtenesion_Xtreme())
//Xman end
{
pFile->m_pCollection = new CCollection();
if(!pFile->m_pCollection->InitCollectionFromFile(pFile->GetFilePath(), pFile->GetFileName()))
{
delete pFile->m_pCollection;
pFile->m_pCollection = NULL;
}
else if (!pFile->m_pCollection->GetCollectionAuthorKeyString().IsEmpty())
{
//If the collection has a key, resetting the file name will
//cause the key to be added into the wordlist to be stored
//into Kad.
pFile->SetFileName(pFile->GetFileName());
//During the initial startup, sharedfiles is not accessable
//to SetFileName which will then not call AddKeywords..
//But when it is accessable, we don't allow it to readd them.
if(theApp.sharedfiles)
bKeywordsNeedUpdated = false;
}
}
if(bKeywordsNeedUpdated)
m_keywords->AddKeywords(pFile);
pFile->SetLastSeen();
theApp.knownfiles->m_nRequestedTotal += pFile->statistic.GetAllTimeRequests();
theApp.knownfiles->m_nAcceptedTotal += pFile->statistic.GetAllTimeAccepts();
theApp.knownfiles->m_nTransferredTotal += pFile->statistic.GetAllTimeTransferred();
return true;
}
void CSharedFileList::FileHashingFinished(CKnownFile* file)
{
// File hashing finished for a shared file (none partfile)
// - reading shared directories at startup and hashing files which were not found in known.met
// - reading shared directories during runtime (user hit Reload button, added a shared directory, ...)
ASSERT( !IsFilePtrInList(file) );
ASSERT( !theApp.knownfiles->IsFilePtrInList(file) );
CKnownFile* found_file = GetFileByID(file->GetFileHash());
if (found_file == NULL)
{
// check if we still want to actually share this file, the user might have unshared it while hashing
if (!ShouldBeShared(file->GetSharedDirectory(), file->GetFilePath(), false)){
RemoveFromHashing(file);
if (!IsFilePtrInList(file) && !theApp.knownfiles->IsFilePtrInList(file))
delete file;
else
ASSERT(0);
}
else
{
SafeAddKFile(file);
theApp.knownfiles->SafeAddKFile(file);
}
}
else
{
TRACE(_T("%hs: File already in shared file list: %s \"%s\"\n"), __FUNCTION__, md4str(found_file->GetFileHash()), found_file->GetFilePath());
TRACE(_T("%hs: File to add: %s \"%s\"\n"), __FUNCTION__, md4str(file->GetFileHash()), file->GetFilePath());
LogWarning(GetResString(IDS_ERR_DUPL_FILES), found_file->GetFilePath(), file->GetFilePath());
RemoveFromHashing(file);
if (!IsFilePtrInList(file) && !theApp.knownfiles->IsFilePtrInList(file))
delete file;
else
ASSERT(0);
}
}
bool CSharedFileList::RemoveFile(CKnownFile* pFile, bool bDeleted)
{
CSingleLock listlock(&m_mutWriteList);
listlock.Lock();
bool bResult = (m_Files_map.RemoveKey(CCKey(pFile->GetFileHash())) != FALSE);
listlock.Unlock();
output->RemoveFile(pFile, bDeleted);
m_keywords->RemoveKeywords(pFile);
if (bResult)
{
m_UnsharedFiles_map.SetAt(CSKey(pFile->GetFileHash()), true);
theApp.knownfiles->m_nRequestedTotal -= pFile->statistic.GetAllTimeRequests();
theApp.knownfiles->m_nAcceptedTotal -= pFile->statistic.GetAllTimeAccepts();
theApp.knownfiles->m_nTransferredTotal -= pFile->statistic.GetAllTimeTransferred();
}
m_dwFile_map_updated = GetTickCount(); // requpfile optimization [SiRoB] - Stulle
theApp.uploadqueue->SetSuperiorInQueueDirty(); // Keep Sup clients in up if there is no other sup client in queue [Stulle] - Stulle
return bResult;
}
void CSharedFileList::Reload()
{
//Xman
// BEGIN SLUGFILLER: SafeHash - don't allow to be called until after the control is loaded
if (!output)
return;
// END SLUGFILLER: SafeHash
ClearVolumeInfoCache();
m_mapPseudoDirNames.RemoveAll();
m_keywords->RemoveAllKeywordReferences();
while (!waitingforhash_list.IsEmpty()) // delete all files which are waiting to get hashed, will be readded if still shared below
delete waitingforhash_list.RemoveHead();
bHaveSingleSharedFiles = false;
FindSharedFiles();
m_keywords->PurgeUnreferencedKeywords();
// SLUGFILLER: SafeHash remove - check moved up
/*
if (output)
*/
// SLUGFILLER: SafeHash remove - check moved up
output->ReloadFileList();
m_lastPublishED2KFlag = true; //Xman CodeFix: we need to check if this files were published to server
}
void CSharedFileList::SetOutputCtrl(CSharedFilesCtrl* in_ctrl)
{
output = in_ctrl;
output->ReloadFileList();
//Xman
// SLUGFILLER: SafeHash - load shared files after everything
/*
HashNextFile(); // SLUGFILLER: SafeHash - if hashing not yet started, start it now
*/
LoadSingleSharedFilesList();
Reload();
//Xman end
// ==> Automatic shared files updater [MoNKi] - Stulle
if(thePrefs.GetDirectoryWatcher() && thePrefs.GetSingleSharedDirWatcher())
theApp.ResetDirectoryWatcher();
// <== Automatic shared files updater [MoNKi] - Stulle
}
uint8 GetRealPrio(uint8 in)
{
switch(in) {
case 4 : return 0;
case 0 : return 1;
case 1 : return 2;
case 2 : return 3;
case 3 : return 4;
}
return 0;
}
void CSharedFileList::SendListToServer(){
if (m_Files_map.IsEmpty() || !server->IsConnected())
{
return;
}
CServer* pCurServer = server->GetCurrentServer();
CSafeMemFile files(1024);
CCKey bufKey;
CKnownFile* cur_file,cur_file2;
POSITION pos,pos2;
CTypedPtrList<CPtrList, CKnownFile*> sortedList;
bool added=false;
for(pos=m_Files_map.GetStartPosition(); pos!=0;)
{
m_Files_map.GetNextAssoc(pos, bufKey, cur_file);
added=false;
//insertsort into sortedList
// ==> Don't publish incomplete small files [WiZaRd] - Stulle
/*
if(!cur_file->GetPublishedED2K() && (!cur_file->IsLargeFile() || (pCurServer != NULL && pCurServer->SupportsLargeFilesTCP())))
*/
if(cur_file->GetFileSize() <= PARTSIZE && cur_file->IsPartFile())
added=true;
if(!added && !cur_file->GetPublishedED2K() && (!cur_file->IsLargeFile() || (pCurServer != NULL && pCurServer->SupportsLargeFilesTCP())))
// <== Don't publish incomplete small files [WiZaRd] - Stulle
{
for (pos2 = sortedList.GetHeadPosition();pos2 != 0 && !added;sortedList.GetNext(pos2))
{
if (GetRealPrio(sortedList.GetAt(pos2)->GetUpPriority()) <= GetRealPrio(cur_file->GetUpPriority()) )
{
sortedList.InsertBefore(pos2,cur_file);
added=true;
}
}
if (!added)
{
sortedList.AddTail(cur_file);
}
}
}
// add to packet
uint32 limit = pCurServer ? pCurServer->GetSoftFiles() : 0;
if( limit == 0 || limit > 200 )
{
limit = 200;
}
if( (uint32)sortedList.GetCount() < limit )
{
limit = sortedList.GetCount();
if (limit == 0)
{
m_lastPublishED2KFlag = false;
return;
}
}
files.WriteUInt32(limit);
uint32 count=0;
for (pos = sortedList.GetHeadPosition();pos != 0 && count<limit; )
{
count++;
CKnownFile* file = sortedList.GetNext(pos);
CreateOfferedFilePacket(file, &files, pCurServer);
file->SetPublishedED2K(true);
}
sortedList.RemoveAll();
Packet* packet = new Packet(&files);
packet->opcode = OP_OFFERFILES;
// compress packet
// - this kind of data is highly compressable (N * (1 MD4 and at least 3 string meta data tags and 1 integer meta data tag))
// - the min. amount of data needed for one published file is ~100 bytes
// - this function is called once when connecting to a server and when a file becomes shareable - so, it's called rarely.
// - if the compressed size is still >= the original size, we send the uncompressed packet
// therefor we always try to compress the packet
if (pCurServer && pCurServer->GetTCPFlags() & SRV_TCPFLG_COMPRESSION){
UINT uUncomprSize = packet->size;
packet->PackPacket();
if (thePrefs.GetDebugServerTCPLevel() > 0)
Debug(_T(">>> Sending OP__OfferFiles(compressed); uncompr size=%u compr size=%u files=%u\n"), uUncomprSize, packet->size, limit);
}
else{
if (thePrefs.GetDebugServerTCPLevel() > 0)
Debug(_T(">>> Sending OP__OfferFiles; size=%u files=%u\n"), packet->size, limit);
}
theStats.AddUpDataOverheadServer(packet->size);
if (thePrefs.GetVerbose())
AddDebugLogLine(false, _T("Server, Sendlist: Packet size:%u"), packet->size);
server->SendPacket(packet,true);
}
CKnownFile* CSharedFileList::GetFileByIndex(int index){
int count=0;
CKnownFile* cur_file;
CCKey bufKey;
for (POSITION pos = m_Files_map.GetStartPosition();pos != 0;){
m_Files_map.GetNextAssoc(pos,bufKey,cur_file);
if (index==count)
return cur_file;
count++;
}
return 0;
}
void CSharedFileList::ClearED2KPublishInfo()
{
CKnownFile* cur_file;
CCKey bufKey;
m_lastPublishED2KFlag = true;
for (POSITION pos = m_Files_map.GetStartPosition();pos != 0;)
{
m_Files_map.GetNextAssoc(pos,bufKey,cur_file);
cur_file->SetPublishedED2K(false);
}
}
void CSharedFileList::ClearKadSourcePublishInfo()
{
CKnownFile* cur_file;
CCKey bufKey;
for (POSITION pos = m_Files_map.GetStartPosition();pos != 0;)
{
m_Files_map.GetNextAssoc(pos,bufKey,cur_file);
cur_file->SetLastPublishTimeKadSrc(0,0);
}
}
void CSharedFileList::CreateOfferedFilePacket(CKnownFile* cur_file, CSafeMemFile* files,
CServer* pServer, CUpDownClient* pClient)
{
UINT uEmuleVer = (pClient && pClient->IsEmuleClient()) ? pClient->GetVersion() : 0;
// NOTE: This function is used for creating the offered file packet for Servers _and_ for Clients..
files->WriteHash16(cur_file->GetFileHash());
// *) This function is used for offering files to the local server and for sending
// shared files to some other client. In each case we send our IP+Port only, if
// we have a HighID.
// *) Newer eservers also support 2 special IP+port values which are used to hold basic file status info.
uint32 nClientID = 0;
uint16 nClientPort = 0;
if (pServer)
{
// we use the 'TCP-compression' server feature flag as indicator for a 'newer' server.
if (pServer->GetTCPFlags() & SRV_TCPFLG_COMPRESSION)
{
if (cur_file->IsPartFile())
{
// publishing an incomplete file
nClientID = 0xFCFCFCFC;
nClientPort = 0xFCFC;
}
else
{
// publishing a complete file
nClientID = 0xFBFBFBFB;
nClientPort = 0xFBFB;
}
}
else
{
// check eD2K ID state
if (theApp.serverconnect->IsConnected() && !theApp.serverconnect->IsLowID())
{
nClientID = theApp.GetID();
nClientPort = thePrefs.GetPort();
}
}
}
else
{
if (theApp.IsConnected() && !theApp.IsFirewalled())
{
nClientID = theApp.GetID();
nClientPort = thePrefs.GetPort();
}
}
files->WriteUInt32(nClientID);
files->WriteUInt16(nClientPort);
//TRACE(_T("Publishing file: Hash=%s ClientIP=%s ClientPort=%u\n"), md4str(cur_file->GetFileHash()), ipstr(nClientID), nClientPort);
CSimpleArray<CTag*> tags;
tags.Add(new CTag(FT_FILENAME, cur_file->GetFileName()));
if (!cur_file->IsLargeFile()){
tags.Add(new CTag(FT_FILESIZE, (uint32)(uint64)cur_file->GetFileSize()));
}
else{
// we send 2*32 bit tags to servers, but a real 64 bit tag to other clients.
if (pServer != NULL){
if (!pServer->SupportsLargeFilesTCP()){
ASSERT( false );
tags.Add(new CTag(FT_FILESIZE, 0, false));
}
else{
tags.Add(new CTag(FT_FILESIZE, (uint32)(uint64)cur_file->GetFileSize()));
tags.Add(new CTag(FT_FILESIZE_HI, (uint32)((uint64)cur_file->GetFileSize() >> 32)));
}
}
else{
if (!pClient->SupportsLargeFiles()){
ASSERT( false );
tags.Add(new CTag(FT_FILESIZE, 0, false));
}
else{
tags.Add(new CTag(FT_FILESIZE, cur_file->GetFileSize(), true));
}
}
}
// eserver 17.6+ supports eMule file rating tag. There is no TCP-capabilities bit available to determine
// whether the server is really supporting it -- this is by intention (lug). That's why we always send it.
if (cur_file->GetFileRating()) {
uint32 uRatingVal = cur_file->GetFileRating();
if (pClient) {
// eserver is sending the rating which it received in a different format (see
// 'CSearchFile::CSearchFile'). If we are creating the packet for an other client
// we must use eserver's format.
uRatingVal *= (255/5/*RatingExcellent*/);
}
tags.Add(new CTag(FT_FILERATING, uRatingVal));
}
// NOTE: Archives and CD-Images are published+searched with file type "Pro"
bool bAddedFileType = false;
if (pServer && (pServer->GetTCPFlags() & SRV_TCPFLG_TYPETAGINTEGER)) {
// Send integer file type tags to newer servers
EED2KFileType eFileType = GetED2KFileTypeSearchID(GetED2KFileTypeID(cur_file->GetFileName()));
if (eFileType >= ED2KFT_AUDIO && eFileType <= ED2KFT_CDIMAGE) {
tags.Add(new CTag(FT_FILETYPE, (UINT)eFileType));
bAddedFileType = true;
}
}
if (!bAddedFileType) {
// Send string file type tags to:
// - newer servers, in case there is no integer type available for the file type (e.g. emulecollection)
// - older servers
// - all clients
CString strED2KFileType(GetED2KFileTypeSearchTerm(GetED2KFileTypeID(cur_file->GetFileName())));
if (!strED2KFileType.IsEmpty()) {
tags.Add(new CTag(FT_FILETYPE, strED2KFileType));
bAddedFileType = true;
}
}
// eserver 16.4+ does not need the FT_FILEFORMAT tag at all nor does any eMule client. This tag
// was used for older (very old) eDonkey servers only. -> We send it only to non-eMule clients.
if (pServer == NULL && uEmuleVer == 0) {
CString strExt;
int iExt = cur_file->GetFileName().ReverseFind(_T('.'));
if (iExt != -1){
strExt = cur_file->GetFileName().Mid(iExt);
if (!strExt.IsEmpty()){
strExt = strExt.Mid(1);
if (!strExt.IsEmpty()){
strExt.MakeLower();
tags.Add(new CTag(FT_FILEFORMAT, strExt)); // file extension without a "."
}
}
}
}
// only send verified meta data to servers/clients
if (cur_file->GetMetaDataVer() > 0)
{
static const struct
{
bool bSendToServer;
uint8 nName;
uint8 nED2KType;
LPCSTR pszED2KName;
} _aMetaTags[] =
{
// Artist, Album and Title are disabled because they should be already part of the filename
// and would therefore be redundant information sent to the servers.. and the servers count the
// amount of sent data!
{ false, FT_MEDIA_ARTIST, TAGTYPE_STRING, FT_ED2K_MEDIA_ARTIST },
{ false, FT_MEDIA_ALBUM, TAGTYPE_STRING, FT_ED2K_MEDIA_ALBUM },
{ false, FT_MEDIA_TITLE, TAGTYPE_STRING, FT_ED2K_MEDIA_TITLE },
{ true, FT_MEDIA_LENGTH, TAGTYPE_STRING, FT_ED2K_MEDIA_LENGTH },
{ true, FT_MEDIA_BITRATE, TAGTYPE_UINT32, FT_ED2K_MEDIA_BITRATE },
{ true, FT_MEDIA_CODEC, TAGTYPE_STRING, FT_ED2K_MEDIA_CODEC }
};
for (int i = 0; i < ARRSIZE(_aMetaTags); i++)
{
if (pServer!=NULL && !_aMetaTags[i].bSendToServer)
continue;
CTag* pTag = cur_file->GetTag(_aMetaTags[i].nName);
if (pTag != NULL)
{
// skip string tags with empty string values
if (pTag->IsStr() && pTag->GetStr().IsEmpty())
continue;
// skip integer tags with '0' values
if (pTag->IsInt() && pTag->GetInt() == 0)
continue;
if (_aMetaTags[i].nED2KType == TAGTYPE_STRING && pTag->IsStr())
{
if (pServer && (pServer->GetTCPFlags() & SRV_TCPFLG_NEWTAGS))
tags.Add(new CTag(_aMetaTags[i].nName, pTag->GetStr()));
else
tags.Add(new CTag(_aMetaTags[i].pszED2KName, pTag->GetStr()));
}
else if (_aMetaTags[i].nED2KType == TAGTYPE_UINT32 && pTag->IsInt())
{
if (pServer && (pServer->GetTCPFlags() & SRV_TCPFLG_NEWTAGS))
tags.Add(new CTag(_aMetaTags[i].nName, pTag->GetInt()));
else
tags.Add(new CTag(_aMetaTags[i].pszED2KName, pTag->GetInt()));
}
else if (_aMetaTags[i].nName == FT_MEDIA_LENGTH && pTag->IsInt())
{
ASSERT( _aMetaTags[i].nED2KType == TAGTYPE_STRING );
// All 'eserver' versions and eMule versions >= 0.42.4 support the media length tag with type 'integer'
if ( pServer!=NULL && (pServer->GetTCPFlags() & SRV_TCPFLG_COMPRESSION)
|| uEmuleVer >= MAKE_CLIENT_VERSION(0,42,4))
{
if (pServer && (pServer->GetTCPFlags() & SRV_TCPFLG_NEWTAGS))
tags.Add(new CTag(_aMetaTags[i].nName, pTag->GetInt()));
else
tags.Add(new CTag(_aMetaTags[i].pszED2KName, pTag->GetInt()));
}
else
{
CString strValue;
SecToTimeLength(pTag->GetInt(), strValue);
tags.Add(new CTag(_aMetaTags[i].pszED2KName, strValue));
}
}
else
ASSERT(0);
}
}
}
EUtf8Str eStrEncode;
if (pServer != NULL && (pServer->GetTCPFlags() & SRV_TCPFLG_UNICODE))
eStrEncode = utf8strRaw;
else if (pClient && !pClient->GetUnicodeSupport())
eStrEncode = utf8strNone;
else
eStrEncode = utf8strRaw;
files->WriteUInt32(tags.GetSize());
for (int i = 0; i < tags.GetSize(); i++)
{
const CTag* pTag = tags[i];
//TRACE(_T(" %s\n"), pTag->GetFullInfo(DbgGetFileMetaTagName));
if (pServer && (pServer->GetTCPFlags() & SRV_TCPFLG_NEWTAGS) || (uEmuleVer >= MAKE_CLIENT_VERSION(0,42,7)))
pTag->WriteNewEd2kTag(files, eStrEncode);
else
pTag->WriteTagToFile(files, eStrEncode);
delete pTag;
}
}
// -khaos--+++> New param: pbytesLargest, pointer to uint64.
// Various other changes to accomodate our new statistic...
// Point of this is to find the largest file currently shared.
uint64 CSharedFileList::GetDatasize(uint64 &pbytesLargest) const
{
pbytesLargest=0;
// <-----khaos-
uint64 fsize;
fsize=0;
CCKey bufKey;
CKnownFile* cur_file;
for (POSITION pos = m_Files_map.GetStartPosition();pos != 0;){
m_Files_map.GetNextAssoc(pos,bufKey,cur_file);
fsize += (uint64)cur_file->GetFileSize();
// -khaos--+++> If this file is bigger than all the others...well duh.
if (cur_file->GetFileSize() > pbytesLargest)
pbytesLargest = cur_file->GetFileSize();
// <-----khaos-
}
return fsize;
}
CKnownFile* CSharedFileList::GetFileByID(const uchar* hash) const
{
if (hash)
{
CKnownFile* found_file;
CCKey key(hash);
if (m_Files_map.Lookup(key, found_file))
return found_file;
}
return NULL;
}
CKnownFile* CSharedFileList::GetFileByIdentifier(const CFileIdentifierBase& rFileIdent, bool bStrict) const
{
CKnownFile* pResult;
if (m_Files_map.Lookup(CCKey(rFileIdent.GetMD4Hash()), pResult))
{
if (bStrict)
return pResult->GetFileIdentifier().CompareStrict(rFileIdent) ? pResult : NULL;
else
return pResult->GetFileIdentifier().CompareRelaxed(rFileIdent) ? pResult : NULL;
}
else
return NULL;
}
bool CSharedFileList::IsFilePtrInList(const CKnownFile* file) const
{
if (file)
{
POSITION pos = m_Files_map.GetStartPosition();
while (pos)
{
CCKey key;
CKnownFile* cur_file;
m_Files_map.GetNextAssoc(pos, key, cur_file);
if (file == cur_file)
return true;
}
}
return false;
}
void CSharedFileList::HashNextFile(){
// SLUGFILLER: SafeHash
//Xman
/*
if (!theApp.emuledlg || !::IsWindow(theApp.emuledlg->m_hWnd)) // wait for the dialog to open
*/
if (!theApp.emuledlg || !theApp.emuledlg->IsRunning() || !::IsWindow(theApp.emuledlg->m_hWnd)) // wait for the dialog to open
//Xman end
return;
if (theApp.emuledlg && theApp.emuledlg->IsRunning())
theApp.emuledlg->sharedfileswnd->sharedfilesctrl.ShowFilesCount();
if (!currentlyhashing_list.IsEmpty()) // one hash at a time
return;
// SLUGFILLER: SafeHash
if (waitingforhash_list.IsEmpty())
return;
UnknownFile_Struct* nextfile = waitingforhash_list.RemoveHead();
currentlyhashing_list.AddTail(nextfile); // SLUGFILLER: SafeHash - keep track
CAddFileThread* addfilethread = (CAddFileThread*) AfxBeginThread(RUNTIME_CLASS(CAddFileThread), THREAD_PRIORITY_BELOW_NORMAL,0, CREATE_SUSPENDED);
addfilethread->SetValues(this, nextfile->strDirectory, nextfile->strName, nextfile->strSharedDirectory);
addfilethread->ResumeThread();
// SLUGFILLER: SafeHash - nextfile deleting handled elsewhere
//delete nextfile;
}
// SLUGFILLER: SafeHash
bool CSharedFileList::IsHashing(const CString& rstrDirectory, const CString& rstrName){
for (POSITION pos = waitingforhash_list.GetHeadPosition(); pos != 0; ){
const UnknownFile_Struct* pFile = waitingforhash_list.GetNext(pos);
if (!pFile->strName.CompareNoCase(rstrName) && !CompareDirectories(pFile->strDirectory, rstrDirectory))
return true;
}
for (POSITION pos = currentlyhashing_list.GetHeadPosition(); pos != 0; ){
const UnknownFile_Struct* pFile = currentlyhashing_list.GetNext(pos);
if (!pFile->strName.CompareNoCase(rstrName) && !CompareDirectories(pFile->strDirectory, rstrDirectory))
return true;
}
return false;
}
void CSharedFileList::RemoveFromHashing(CKnownFile* hashed){
for (POSITION pos = currentlyhashing_list.GetHeadPosition(); pos != 0; ){
POSITION posLast = pos;
const UnknownFile_Struct* pFile = currentlyhashing_list.GetNext(pos);
if (!pFile->strName.CompareNoCase(hashed->GetFileName()) && !CompareDirectories(pFile->strDirectory, hashed->GetPath())){
currentlyhashing_list.RemoveAt(posLast);
delete pFile;
HashNextFile(); // start next hash if possible, but only if a previous hash finished
return;
}
}
}
void CSharedFileList::HashFailed(UnknownFile_Struct* hashed){
for (POSITION pos = currentlyhashing_list.GetHeadPosition(); pos != 0; ){
POSITION posLast = pos;
const UnknownFile_Struct* pFile = currentlyhashing_list.GetNext(pos);
if (!pFile->strName.CompareNoCase(hashed->strName) && !CompareDirectories(pFile->strDirectory, hashed->strDirectory)){
currentlyhashing_list.RemoveAt(posLast);
delete pFile;
HashNextFile(); // start next hash if possible, but only if a previous hash finished
break;
}
}
delete hashed;
}
void CSharedFileList::UpdateFile(CKnownFile* toupdate)
{
output->UpdateFile(toupdate);
}
void CSharedFileList::Process()
{
Publish();
if( !m_lastPublishED2KFlag || ( ::GetTickCount() - m_lastPublishED2K < ED2KREPUBLISHTIME ) )
{
return;
}
SendListToServer();
m_lastPublishED2K = ::GetTickCount();
}
void CSharedFileList::Publish()
{
// Variables to save cpu.
// ==> Make code VS 2005 and VS 2008 ready [MorphXT] - Stulle
/*
UINT tNow = time(NULL);
*/
UINT tNow = (UINT)time(NULL);
// <== Make code VS 2005 and VS 2008 ready [MorphXT] - Stulle
bool isFirewalled = theApp.IsFirewalled();
bool bDirectCallback = Kademlia::CKademlia::IsRunning() && !Kademlia::CUDPFirewallTester::IsFirewalledUDP(true) && Kademlia::CUDPFirewallTester::IsVerified();
if( Kademlia::CKademlia::IsConnected() && ( !isFirewalled || ( isFirewalled && theApp.clientlist->GetBuddyStatus() == Connected) || bDirectCallback) && GetCount() && Kademlia::CKademlia::GetPublish())
{
//We are connected to Kad. We are either open or have a buddy. And Kad is ready to start publishing.
if( Kademlia::CKademlia::GetTotalStoreKey() < KADEMLIATOTALSTOREKEY)
{
//We are not at the max simultaneous keyword publishes
if (tNow >= m_keywords->GetNextPublishTime())
{
//Enough time has passed since last keyword publish
//Get the next keyword which has to be (re)-published
CPublishKeyword* pPubKw = m_keywords->GetNextKeyword();
if(pPubKw)
{
//We have the next keyword to check if it can be published
//Debug check to make sure things are going well.
ASSERT( pPubKw->GetRefCount() != 0 );
if (tNow >= pPubKw->GetNextPublishTime())
{
//This keyword can be published.
Kademlia::CSearch* pSearch = Kademlia::CSearchManager::PrepareLookup(Kademlia::CSearch::STOREKEYWORD, false, pPubKw->GetKadID());
if (pSearch)
{
//pSearch was created. Which means no search was already being done with this HashID.
//This also means that it was checked to see if network load wasn't a factor.
//This sets the filename into the search object so we can show it in the gui.
pSearch->SetGUIName(pPubKw->GetKeyword());
//Add all file IDs which relate to the current keyword to be published
const CSimpleKnownFileArray& aFiles = pPubKw->GetReferences();
uint32 count = 0;
for (int f = 0; f < aFiles.GetSize(); f++)
{
//Debug check to make sure things are working well.
ASSERT_VALID( aFiles[f] );
// JOHNTODO - Why is this happening.. I think it may have to do with downloading a file that is already
// in the known file list..
// ASSERT( IsFilePtrInList(aFiles[f]) );
//Only publish complete files as someone else should have the full file to publish these keywords.
//As a side effect, this may help reduce people finding incomplete files in the network.
if( !aFiles[f]->IsPartFile() && IsFilePtrInList(aFiles[f]))
{
count++;
pSearch->AddFileID(Kademlia::CUInt128(aFiles[f]->GetFileHash()));
if( count > 150 )
{
//We only publish up to 150 files per keyword publish then rotate the list.
pPubKw->RotateReferences(f);
break;
}
}
}
if( count )
{
//Start our keyword publish
pPubKw->SetNextPublishTime(tNow+(KADEMLIAREPUBLISHTIMEK));
pPubKw->IncPublishedCount();
Kademlia::CSearchManager::StartSearch(pSearch);
}
else
{
//There were no valid files to publish with this keyword.
delete pSearch;
}
}
}
}
m_keywords->SetNextPublishTime(KADEMLIAPUBLISHTIME+tNow);
}
}
if( Kademlia::CKademlia::GetTotalStoreSrc() < KADEMLIATOTALSTORESRC)
{
if(tNow >= m_lastPublishKadSrc)
{
if(m_currFileSrc > GetCount())
m_currFileSrc = 0;
CKnownFile* pCurKnownFile = GetFileByIndex(m_currFileSrc);
if(pCurKnownFile)
{
if(pCurKnownFile->PublishSrc())
{
//Xman Code-Improvement: show filename immediately
/*
if(Kademlia::CSearchManager::PrepareLookup(Kademlia::CSearch::STOREFILE, true, Kademlia::CUInt128(pCurKnownFile->GetFileHash()))==NULL)
pCurKnownFile->SetLastPublishTimeKadSrc(0,0);
*/
Kademlia::CSearch* pSearch = Kademlia::CSearchManager::PrepareLookup(Kademlia::CSearch::STOREFILE, true, Kademlia::CUInt128(pCurKnownFile->GetFileHash()));
if(pSearch==NULL)
{
pCurKnownFile->SetLastPublishTimeKadSrc(0,0);
}
else
pSearch->SetGUIName(pCurKnownFile->GetFileName());
//Xman end
}
}
m_currFileSrc++;
// even if we did not publish a source, reset the timer so that this list is processed
// only every KADEMLIAPUBLISHTIME seconds.
m_lastPublishKadSrc = KADEMLIAPUBLISHTIME+tNow;
}
}
if( Kademlia::CKademlia::GetTotalStoreNotes() < KADEMLIATOTALSTORENOTES)
{
if(tNow >= m_lastPublishKadNotes)
{
if(m_currFileNotes > GetCount())
m_currFileNotes = 0;
CKnownFile* pCurKnownFile = GetFileByIndex(m_currFileNotes);
if(pCurKnownFile)
{
if(pCurKnownFile->PublishNotes())
{
if(Kademlia::CSearchManager::PrepareLookup(Kademlia::CSearch::STORENOTES, true, Kademlia::CUInt128(pCurKnownFile->GetFileHash()))==NULL)
pCurKnownFile->SetLastPublishTimeKadNotes(0);
}
}
m_currFileNotes++;
// even if we did not publish a source, reset the timer so that this list is processed
// only every KADEMLIAPUBLISHTIME seconds.
m_lastPublishKadNotes = KADEMLIAPUBLISHTIME+tNow;
}
}
}
}
void CSharedFileList::AddKeywords(CKnownFile* pFile)
{
m_keywords->AddKeywords(pFile);
}
void CSharedFileList::RemoveKeywords(CKnownFile* pFile)
{
m_keywords->RemoveKeywords(pFile);
}
void CSharedFileList::DeletePartFileInstances() const
{
// this is only allowed during shut down
ASSERT( theApp.m_app_state == APP_STATE_SHUTTINGDOWN );
ASSERT( theApp.knownfiles );
POSITION pos = m_Files_map.GetStartPosition();
while (pos)
{
CCKey key;
CKnownFile* cur_file;
m_Files_map.GetNextAssoc(pos, key, cur_file);
if (cur_file->IsKindOf(RUNTIME_CLASS(CPartFile)))
{
if (!theApp.downloadqueue->IsPartFile(cur_file) && !theApp.knownfiles->IsFilePtrInList(cur_file))
delete cur_file; // this is only allowed during shut down
}
}
}
bool CSharedFileList::IsUnsharedFile(const uchar* auFileHash) const {
bool bFound;
if (auFileHash){
CSKey key(auFileHash);
if (m_UnsharedFiles_map.Lookup(key, bFound))
return true;
}
return false;
}
void CSharedFileList::RebuildMetaData()
{
POSITION pos = m_Files_map.GetStartPosition();
while (pos)
{
CCKey key;
CKnownFile *file;
m_Files_map.GetNextAssoc(pos, key, file);
if (!file->IsKindOf(RUNTIME_CLASS(CPartFile)))
file->UpdateMetaDataTags();
}
}
bool CSharedFileList::ShouldBeShared(CString strPath, CString strFilePath, bool bMustBeShared) const
{
// determines if a file should be a shared file based on out shared directories/files preferences
CStringList l_sAdded;
if (CompareDirectories(strPath, thePrefs.GetMuleDirectory(EMULE_INCOMINGDIR)) == 0)
return true;
// ==> Smart Category Control (SCC) [khaos/SiRoB/Stulle] - Stulle
/*
for (int ix=1;ix<thePrefs.GetCatCount();ix++)
*/
for (int ix=0;ix<thePrefs.GetCatCount();ix++)
// <== Smart Category Control (SCC) [khaos/SiRoB/Stulle] - Stulle
{
if (CompareDirectories(strPath, thePrefs.GetCatPath(ix)) == 0)
return true;
}
if (bMustBeShared)
return false;
// check if this file is explicit unshared
if (!strFilePath.IsEmpty())
{
for (POSITION pos = m_liSingleExcludedFiles.GetHeadPosition(); pos != NULL; m_liSingleExcludedFiles.GetNext(pos) )
{
if (strFilePath.CompareNoCase(m_liSingleExcludedFiles.GetAt(pos)) == 0)
return false;
}
// check if this file is explicit shared
for (POSITION pos = m_liSingleSharedFiles.GetHeadPosition(); pos != NULL; m_liSingleSharedFiles.GetNext(pos) )
{
if (strFilePath.CompareNoCase(m_liSingleSharedFiles.GetAt(pos)) == 0)
return true;
}
}
for (POSITION pos = thePrefs.shareddir_list.GetHeadPosition();pos != 0;)
{
if (CompareDirectories(strPath, thePrefs.shareddir_list.GetNext(pos)) == 0)
return true;
}
return false;
}
bool CSharedFileList::ContainsSingleSharedFiles(CString strDirectory) const
{
if (strDirectory.Right(1) != '\\')
strDirectory += '\\';
for (POSITION pos = m_liSingleSharedFiles.GetHeadPosition(); pos != NULL; m_liSingleSharedFiles.GetNext(pos) )
{
if (strDirectory.CompareNoCase(m_liSingleSharedFiles.GetAt(pos).Left(strDirectory.GetLength())) == 0)
return true;
}
return false;
}
bool CSharedFileList::ExcludeFile(CString strFilePath)
{
bool bShared = false;
// first check if we are explicty sharing this file
for (POSITION pos = m_liSingleSharedFiles.GetHeadPosition(); pos != NULL; m_liSingleSharedFiles.GetNext(pos) )
{
if (strFilePath.CompareNoCase(m_liSingleSharedFiles.GetAt(pos)) == 0)
{
bShared = true;
m_liSingleSharedFiles.RemoveAt(pos);
break;
}
}
//MORPH START - Added by Stulle, Only exclude file if it was not single shared
bool bSingleShared = bShared;
//MORPH END - Added by Stulle, Only exlcude file if it was not single shared
// check if we implicity share this file
bShared |= ShouldBeShared(strFilePath.Left(strFilePath.ReverseFind('\\') + 1), strFilePath, false);
if (!bShared)
{
// we don't actually share this file, can't be excluded
return false;
}
else if (ShouldBeShared(strFilePath.Left(strFilePath.ReverseFind('\\') + 1), strFilePath, true))
{
// we cannot unshare this file (incoming directories)
ASSERT( false ); // checks should be done earlier already
return false;
}
// add to exclude list
//MORPH START - Added by Stulle, Only exclude file if it was not single shared
if(!bSingleShared)
//MORPH END - Added by Stulle, Only exlcude file if it was not single shared
m_liSingleExcludedFiles.AddTail(strFilePath);
// ==> Automatic shared files updater [MoNKi] - Stulle
else
{
if(thePrefs.GetDirectoryWatcher() && thePrefs.GetSingleSharedDirWatcher())
theApp.ResetDirectoryWatcher();
}
// <== Automatic shared files updater [MoNKi] - Stulle
// check if the file is in the shared list (doesn't has to for example if it is hashing or not loaded yet) and remove
CKnownFile* cur_file;
CCKey bufKey;
for (POSITION pos = m_Files_map.GetStartPosition();pos != NULL;)
{
m_Files_map.GetNextAssoc(pos,bufKey,cur_file);
if (strFilePath.CompareNoCase(cur_file->GetFilePath()) == 0)
{
RemoveFile(cur_file);
break;
}
}
// updating the GUI needs to be done by the caller
return true;
}
void CSharedFileList::CheckAndAddSingleFile(const CFileFind& ff){
if (ff.IsDirectory() || ff.IsDots() || ff.IsSystem() || ff.IsTemporary() || ff.GetLength()==0 || ff.GetLength()>MAX_EMULE_FILE_SIZE)
return;
CString strFoundFileName(ff.GetFileName());
CString strFoundFilePath(ff.GetFilePath());
CString strFoundDirectory(strFoundFilePath.Left(ff.GetFilePath().ReverseFind('\\') + 1));
CString strShellLinkDir;
ULONGLONG ullFoundFileSize = ff.GetLength();
// check if this file is explicit unshared
for (POSITION pos = m_liSingleExcludedFiles.GetHeadPosition(); pos != NULL; m_liSingleExcludedFiles.GetNext(pos) )
{
if (strFoundFilePath.CompareNoCase(m_liSingleExcludedFiles.GetAt(pos)) == 0)
return;
}
CTime tFoundFileTime;
try{
ff.GetLastWriteTime(tFoundFileTime);
}
catch(CException* ex){
ex->Delete();
}
// ignore real(!) LNK files
TCHAR szExt[_MAX_EXT];
_tsplitpath(strFoundFileName, NULL, NULL, NULL, szExt);
if (_tcsicmp(szExt, _T(".lnk")) == 0){
SHFILEINFO info;
if (SHGetFileInfo(strFoundFilePath, 0, &info, sizeof(info), SHGFI_ATTRIBUTES) && (info.dwAttributes & SFGAO_LINK)){
if (!thePrefs.GetResolveSharedShellLinks()) {
TRACE(_T("%hs: Did not share file \"%s\" - not supported file type\n"), __FUNCTION__, strFoundFilePath);
return;
}
// Win98: Would need to implement a different code path which is using 'IShellLinkA' on Win9x.
CComPtr<IShellLink> pShellLink;
if (SUCCEEDED(pShellLink.CoCreateInstance(CLSID_ShellLink))){
CComQIPtr<IPersistFile> pPersistFile = pShellLink;
if (pPersistFile){
if (SUCCEEDED(pPersistFile->Load(strFoundFilePath, STGM_READ))){
TCHAR szResolvedPath[MAX_PATH];
if (pShellLink->GetPath(szResolvedPath, _countof(szResolvedPath), (WIN32_FIND_DATA *)NULL/*DO NOT USE (read below)*/, 0) == NOERROR){
// WIN32_FIND_DATA povided by "IShellLink::GetPath" contains the file stats which where
// taken when the shortcut was created! Thus the file stats which are returned do *not*
// reflect the current real file stats. So, do *not* use that data!
//
// Need to do an explicit 'FindFile' to get the current WIN32_FIND_DATA file stats.
//
CFileFind ffResolved;
if (!ffResolved.FindFile(szResolvedPath))
return;
VERIFY( !ffResolved.FindNextFile() );
if (ffResolved.IsDirectory() || ffResolved.IsDots() || ffResolved.IsSystem() || ffResolved.IsTemporary() || ffResolved.GetLength() == 0 || ffResolved.GetLength() > MAX_EMULE_FILE_SIZE)
return;
strShellLinkDir = strFoundDirectory;
strFoundDirectory = ffResolved.GetRoot();
strFoundFileName = ffResolved.GetFileName();
strFoundFilePath = ffResolved.GetFilePath();
ullFoundFileSize = ffResolved.GetLength();
try {
ffResolved.GetLastWriteTime(tFoundFileTime);
}
catch (CException *ex) {
ex->Delete();
return;
}
if (strFoundDirectory.Right(1) != _T("\\"))
strFoundDirectory += _T('\\');
}
}
}
}
}
}
// ignore real(!) thumbs.db files -- seems that lot of ppl have 'thumbs.db' files without the 'System' file attribute
if (strFoundFileName.CompareNoCase(_T("thumbs.db")) == 0)
{
// if that's a valid 'Storage' file, we declare it as a "thumbs.db" file.
CComPtr<IStorage> pStorage;
if (StgOpenStorage(strFoundFilePath, NULL, STGM_READ | STGM_SHARE_DENY_WRITE, NULL, 0, &pStorage) == S_OK)
{
CComPtr<IEnumSTATSTG> pEnumSTATSTG;
if (SUCCEEDED(pStorage->EnumElements(0, NULL, 0, &pEnumSTATSTG)))
{
STATSTG statstg = {0};
if (pEnumSTATSTG->Next(1, &statstg, 0) == S_OK)
{
CoTaskMemFree(statstg.pwcsName);
statstg.pwcsName = NULL;
TRACE(_T("%hs: Did not share file \"%s\" - not supported file type\n"), __FUNCTION__, strFoundFilePath);
return;
}
}
}
}
// ==> Make code VS 2005 and VS 2008 ready [MorphXT] - Stulle
/*
uint32 fdate = (UINT)tFoundFileTime.GetTime();
*/
time_t fdate = (time_t)tFoundFileTime.GetTime();
// <== Make code VS 2005 and VS 2008 ready [MorphXT] - Stulle
if (fdate == 0)
fdate = (UINT)-1;
if (fdate == -1){
if (thePrefs.GetVerbose())
AddDebugLogLine(false, _T("Failed to get file date of \"%s\""), strFoundFilePath);
}
else
AdjustNTFSDaylightFileTime(fdate, strFoundFilePath);
CKnownFile* toadd = theApp.knownfiles->FindKnownFile(strFoundFileName, fdate, ullFoundFileSize);
if (toadd)
{
CCKey key(toadd->GetFileHash());
CKnownFile* pFileInMap;
if (m_Files_map.Lookup(key, pFileInMap))
{
TRACE(_T("%hs: File already in shared file list: %s \"%s\"\n"), __FUNCTION__, md4str(pFileInMap->GetFileHash()), pFileInMap->GetFilePath());
TRACE(_T("%hs: File to add: %s \"%s\"\n"), __FUNCTION__, md4str(toadd->GetFileHash()), strFoundFilePath);
if (!pFileInMap->IsKindOf(RUNTIME_CLASS(CPartFile)) || theApp.downloadqueue->IsPartFile(pFileInMap))
{
if (pFileInMap->GetFilePath().CompareNoCase(toadd->GetFilePath()) != 0) /* is it actually really the same file in the same place we already share? if so don't bother too much */
LogWarning( GetResString(IDS_ERR_DUPL_FILES) , pFileInMap->GetFilePath(), strFoundFilePath);
else
DebugLog( _T("File shared twice, might have been a single shared file before - %s") , pFileInMap->GetFilePath());
}
}
else
{
if (!strShellLinkDir.IsEmpty())
DebugLog(_T("Shared link: %s from %s"), strFoundFilePath, strShellLinkDir);
toadd->SetPath(strFoundDirectory);
toadd->SetFilePath(strFoundFilePath);
toadd->SetSharedDirectory(strShellLinkDir);
//Xman advanced upload-priority
/*
AddFile(toadd);
*/
if(AddFile(toadd))
toadd->CheckAUPFilestats(false);
//Xman end
}
}
else
{
//not in knownfilelist - start adding thread to hash file if the hashing of this file isnt already waiting
// SLUGFILLER: SafeHash - don't double hash, MY way
//Xman
/*
if (!IsHashing(strFoundDirectory, strFoundFileName) && !thePrefs.IsTempFile(strFoundDirectory, strFoundFileName)){
*/
if (!IsHashing(strFoundDirectory, strFoundFileName) && !theApp.downloadqueue->IsTempFile(strFoundDirectory, strFoundFileName) && !thePrefs.IsConfigFile(strFoundDirectory, strFoundFileName)){
//Xman end
UnknownFile_Struct* tohash = new UnknownFile_Struct;
tohash->strDirectory = strFoundDirectory;
tohash->strName = strFoundFileName;
tohash->strSharedDirectory = strShellLinkDir;
waitingforhash_list.AddTail(tohash);
}
else
TRACE(_T("%hs: Did not share file \"%s\" - already hashing or temp. file\n"), __FUNCTION__, strFoundFilePath);
// SLUGFILLER: SafeHash
}
}
void CSharedFileList::Save() const
{
CString strFullPath = thePrefs.GetMuleDirectory(EMULE_CONFIGDIR) + SHAREDFILES_FILE;
CStdioFile sdirfile;
if (sdirfile.Open(strFullPath, CFile::modeCreate | CFile::modeWrite | CFile::shareDenyWrite | CFile::typeBinary))
{
try{
// write Unicode byte-order mark 0xFEFF
WORD wBOM = 0xFEFF;
sdirfile.Write(&wBOM, sizeof(wBOM));
for (POSITION pos = m_liSingleSharedFiles.GetHeadPosition();pos != 0;){
sdirfile.WriteString(m_liSingleSharedFiles.GetNext(pos));
sdirfile.Write(L"\r\n", sizeof(TCHAR)*2);
}
for (POSITION pos = m_liSingleExcludedFiles.GetHeadPosition();pos != 0;){
sdirfile.WriteString(_T("-") + m_liSingleExcludedFiles.GetNext(pos)); // a '-' prefix means excluded
sdirfile.Write(L"\r\n", sizeof(TCHAR)*2);
}
if (thePrefs.GetCommitFiles() >= 2 || (thePrefs.GetCommitFiles() >= 1 && !theApp.emuledlg->IsRunning())){
sdirfile.Flush(); // flush file stream buffers to disk buffers
if (_commit(_fileno(sdirfile.m_pStream)) != 0) // commit disk buffers to disk
AfxThrowFileException(CFileException::hardIO, GetLastError(), sdirfile.GetFileName());
}
sdirfile.Close();
}
catch(CFileException* error){
TCHAR buffer[MAX_CFEXP_ERRORMSG];
error->GetErrorMessage(buffer,_countof(buffer));
DebugLogError(L"Failed to save %s - %s", strFullPath, buffer);
error->Delete();
}
}
else
DebugLogError(L"Failed to save %s", strFullPath);
}
void CSharedFileList::LoadSingleSharedFilesList()
{
CString strFullPath = thePrefs.GetMuleDirectory(EMULE_CONFIGDIR) + SHAREDFILES_FILE;
CStdioFile* sdirfile = new CStdioFile();
bool bIsUnicodeFile = IsUnicodeFile(strFullPath); // check for BOM
if (sdirfile->Open(strFullPath, CFile::modeRead | CFile::shareDenyWrite | (bIsUnicodeFile ? CFile::typeBinary : 0)))
{
try {
if (bIsUnicodeFile)
sdirfile->Seek(sizeof(WORD), SEEK_CUR); // skip BOM
CString toadd;
while (sdirfile->ReadString(toadd))
{
toadd.Trim(L" \t\r\n"); // need to trim '\r' in binary mode
if (toadd.IsEmpty())
continue;
bool bExclude = false;
if (toadd.Left(1) == '-') // a '-' prefix means excluded
{
bExclude = true;
toadd = toadd.Right(toadd.GetLength() - 1);
}
// Skip non-existing directories from fixed disks only
int iDrive = PathGetDriveNumber(toadd);
if (iDrive >= 0 && iDrive <= 25) {
WCHAR szRootPath[4] = L" :\\";
szRootPath[0] = (WCHAR)(L'A' + iDrive);
if (GetDriveType(szRootPath) == DRIVE_FIXED) {
if (_taccess(toadd, 0) != 0)
continue;
}
}
if (bExclude)
ExcludeFile(toadd);
else
AddSingleSharedFile(toadd, true);
}
sdirfile->Close();
}
catch(CFileException* error){
TCHAR buffer[MAX_CFEXP_ERRORMSG];
error->GetErrorMessage(buffer,_countof(buffer));
DebugLogError(L"Failed to load %s - %s", strFullPath, buffer);
error->Delete();
}
}
else
DebugLogError(L"Failed to load %s", strFullPath);
delete sdirfile;
}
bool CSharedFileList::AddSingleSharedDirectory(const CString& rstrFilePath, bool bNoUpdate)
{
ASSERT( rstrFilePath.Right(1) == _T('\\') );
// check if we share this dir already or are not allowed to
// SLUGFILLER: SafeHash remove - removed installation dir unsharing
/*
if (ShouldBeShared(rstrFilePath, _T(""), false) || !thePrefs.IsShareableDirectory(rstrFilePath))
*/
if (ShouldBeShared(rstrFilePath, _T(""), false))
// SLUGFILLER: SafeHash remove - removed installation dir unsharing
return false;
thePrefs.shareddir_list.AddTail(rstrFilePath); // adds the new directory as shared, GUI updates need to be done by the caller
if (!bNoUpdate)
{
AddFilesFromDirectory(rstrFilePath);
HashNextFile();
}
return true;
}
CString CSharedFileList::GetPseudoDirName(const CString& strDirectoryName)
{
// those pseudo names are sent to other clients when requestin shared files instead of the full directory names to avoid
// giving away too many information about our local file structure, which might be sensitive data in some cases,
// but we still want to use a descriptive name so the information of files sorted by directories is not lost
// So, in general we use only the name of the directory, shared subdirs keep the path up to the highest shared dir,
// this way we never reveal the name of any not directly shared directory. We then make sure its unique.
if (!ShouldBeShared(strDirectoryName, _T(""), false))
{
ASSERT( false );
return _T("");
}
// does the name already exists?
for (POSITION pos = m_mapPseudoDirNames.GetStartPosition(); pos != NULL;)
{
CString strTmpPseudo;
CString strTmpPath;
m_mapPseudoDirNames.GetNextAssoc(pos, strTmpPseudo, strTmpPath);
if (CompareDirectories(strTmpPath, strDirectoryName) == 0)
{
// already done here
return strTmpPseudo;
}
}
// create a new Pseudoname
CString strDirectoryTmp = strDirectoryName;
if (strDirectoryTmp.Right(1) == _T('\\'))
strDirectoryTmp.Truncate(strDirectoryTmp.GetLength() - 1);
CString strPseudoName;
int iPos;
while ((iPos = strDirectoryTmp.ReverseFind(_T('\\'))) != (-1))
{
strPseudoName = strDirectoryTmp.Right(strDirectoryTmp.GetLength() - iPos) + strPseudoName;
strDirectoryTmp.Truncate(iPos);
if (!ShouldBeShared(strDirectoryTmp, _T(""), false))
break;
}
if (!strPseudoName.IsEmpty())
{
// remove first backslash
ASSERT( strPseudoName.GetAt(0) == _T('\\') );
strPseudoName = strPseudoName.Right(strPseudoName.GetLength() - 1);
}
else
{
// must be a rootdirectory
ASSERT( strDirectoryTmp.GetLength() == 2 );
strPseudoName = strDirectoryTmp;
}
// we have the name, make sure it is unique
if (m_mapPseudoDirNames.Lookup(strPseudoName, strDirectoryTmp))
{
CString strUnique;
for (iPos = 2; ; iPos++)
{
strUnique.Format(_T("%s_%u"), strPseudoName, iPos);
if (!m_mapPseudoDirNames.Lookup(strUnique, strDirectoryTmp))
{
DebugLog(_T("Using Pseudoname %s for directory %s"), strUnique, strDirectoryName);
m_mapPseudoDirNames.SetAt(strUnique, strDirectoryName);
return strUnique;
}
else if (iPos > 200)
{
// wth?
ASSERT( false );
return _T("");
}
}
}
else
{
DebugLog(_T("Using Pseudoname %s for directory %s"), strPseudoName, strDirectoryName);
m_mapPseudoDirNames.SetAt(strPseudoName, strDirectoryName);
return strPseudoName;
}
}
CString CSharedFileList::GetDirNameByPseudo(const CString& strPseudoName) const
{
CString strResult;
m_mapPseudoDirNames.Lookup(strPseudoName, strResult);
return strResult;
}
bool CSharedFileList::GetPopularityRank(const CKnownFile* pFile, uint32& rnOutSession, uint32& rnOutTotal) const
{
rnOutSession = 0;
rnOutTotal = 0;
if (GetFileByIdentifier(pFile->GetFileIdentifierC()) == NULL)
{
ASSERT( false );
return false;
}
// cycle all files, each file which has more request than the given files lowers the rank
CKnownFile* cur_file;
CCKey bufKey;
for (POSITION pos = m_Files_map.GetStartPosition(); pos != 0; )
{
m_Files_map.GetNextAssoc(pos,bufKey,cur_file);
if (cur_file == pFile)
continue;
if (cur_file->statistic.GetAllTimeRequests() > pFile->statistic.GetAllTimeRequests())
rnOutTotal++;
if (cur_file->statistic.GetRequests() > pFile->statistic.GetRequests())
rnOutSession++;
}
// we start at rank #1, not 0
rnOutSession++;
rnOutTotal++;
return true;
}
//Xman advanced upload-priority
void CSharedFileList::CalculateUploadPriority(bool force)
{
static uint32 lastprocess; //if used Advanced Auto Prio
static uint32 lastprocess2; //if Advanced Auto Prio is not used
if(!thePrefs.UseAdvancedAutoPtio())
{
if(::GetTickCount() - lastprocess2 > HR2MS(1))
{
lastprocess2=::GetTickCount();
//the counted upload stats must be updated from time to time, user can switch to AUP
POSITION pos = m_Files_map.GetStartPosition();
while( pos != NULL )
{
CKnownFile* pFile;
CCKey key;
m_Files_map.GetNextAssoc( pos, key, pFile );
pFile->statistic.UpdateCountedTransferred();
}
}
return;
}
if(force || ::GetTickCount() - lastprocess > MIN2MS(2))
{
lastprocess=::GetTickCount();
lastprocess2=lastprocess;
#ifdef _DEBUG
AddDebugLogLine(false,_T("calculating auto uploadprios. mapcount: %i"), m_Files_map.GetCount());
#endif
// v2 other avg calculation
double sum_wanted_upload=0;
double sum_uploaded=0;
uint32 all_virtual_sources=0;
//first loop to calculate the avg
POSITION pos = m_Files_map.GetStartPosition();
while( pos != NULL )
{
CKnownFile* pFile;
CCKey key;
m_Files_map.GetNextAssoc( pos, key, pFile );
pFile->statistic.UpdateCountedTransferred();
//we only take files > 500k into account
if((uint64)pFile->GetFileSize() > 500*1024)
{
//update virtual uploadsources not in realtime
if(pFile->IsPartFile())
pFile->UpdateVirtualUploadSources();
sum_wanted_upload += pFile->GetWantedUpload();
/*
uint64 oldtransferred ;
if (pFile->statistic.GetAllTimeTransferred() > pFile->statistic.GetTransferred())
oldtransferred = pFile->statistic.GetAllTimeTransferred()-pFile->statistic.GetTransferred();
else
oldtransferred = 0;
sum_uploaded += (pFile->statistic.GetTransferred() + oldtransferred/2.0);
*/
sum_uploaded += pFile->statistic.GetCountedTransferred();
all_virtual_sources += pFile->GetVirtualSourceIndicator();
}
}
float avgpercent;
if (sum_wanted_upload > 0)
avgpercent = (float)(sum_uploaded / sum_wanted_upload * 100.0);
else
avgpercent = 0;
m_lastavgPercent=avgpercent;
if(m_Files_map.GetCount()>0)
{
m_avg_virtual_sources = all_virtual_sources / m_Files_map.GetCount();
m_avg_client_on_uploadqueue = theApp.uploadqueue->GetWaitingUserCount() / m_Files_map.GetCount();
}
else
{
m_avg_virtual_sources = 0;
m_avg_client_on_uploadqueue = 0;
}
//end v2
//second loop to set new prios
pos = m_Files_map.GetStartPosition();
while( pos != NULL )
{
CKnownFile* pFile;
CCKey key;
m_Files_map.GetNextAssoc( pos, key, pFile );
pFile->CalculateAndSetUploadPriority();
}
}
}
void CSharedFileList::CalculateUploadPriority_Standard()
{
POSITION pos = m_Files_map.GetStartPosition();
while( pos != NULL )
{
CKnownFile* pFile;
CCKey key;
m_Files_map.GetNextAssoc( pos, key, pFile );
pFile->UpdateAutoUpPriority();
}
}
//Xman end
// ==> PowerShare [ZZ/MorphXT] - Stulle
void CSharedFileList::UpdatePartsInfo()
{
if (m_Files_map.IsEmpty())
return;
CCKey bufKey;
CKnownFile* file;
POSITION pos;
for(pos=m_Files_map.GetStartPosition(); pos!=0;)
{
m_Files_map.GetNextAssoc(pos, bufKey, file);
if (((file->GetPowerSharedMode()>=0)?file->GetPowerSharedMode():thePrefs.GetPowerShareMode()) == 3)
file->UpdatePartsInfo();
}
}
// <== PowerShare [ZZ/MorphXT] - Stulle | [
"Mike.Ken.S@dd569cc8-ff36-11de-bbca-1111db1fd05b",
"[email protected]@dd569cc8-ff36-11de-bbca-1111db1fd05b"
]
| [
[
[
1,
362
],
[
364,
369
],
[
371,
435
],
[
437,
464
],
[
466,
469
],
[
472,
550
],
[
552,
552
],
[
554,
605
],
[
608,
608
],
[
612,
791
],
[
794,
809
],
[
811,
811
],
[
813,
847
],
[
852,
904
],
[
906,
906
],
[
913,
988
],
[
991,
991
],
[
997,
1366
],
[
1381,
1689
],
[
1692,
1692
],
[
1696,
2172
],
[
2201,
2319
],
[
2321,
2336
]
],
[
[
363,
363
],
[
370,
370
],
[
436,
436
],
[
465,
465
],
[
470,
471
],
[
551,
551
],
[
553,
553
],
[
606,
607
],
[
609,
611
],
[
792,
793
],
[
810,
810
],
[
812,
812
],
[
848,
851
],
[
905,
905
],
[
907,
912
],
[
989,
990
],
[
992,
996
],
[
1367,
1380
],
[
1690,
1691
],
[
1693,
1695
],
[
2173,
2200
],
[
2320,
2320
]
]
]
|
7ebdfa5de0c7201b5de89fb62cc338766140ea75 | 119ba245bea18df8d27b84ee06e152b35c707da1 | /unreal/branches/robots/qrgui/interpreters/robots/details/blocks/functionBlock.cpp | 040b8976ca0a072ef7ed44a37e9d1b239fb6c875 | []
| no_license | nfrey/qreal | 05cd4f9b9d3193531eb68ff238d8a447babcb3d2 | 71641e6c5f8dc87eef9ec3a01cabfb9dd7b0e164 | refs/heads/master | 2020-04-06T06:43:41.910531 | 2011-05-30T19:30:09 | 2011-05-30T19:30:09 | 1,634,768 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 230 | cpp | #include "functionBlock.h"
using namespace qReal;
using namespace interpreters::robots::details::blocks;
FunctionBlock::FunctionBlock()
{
}
void FunctionBlock::run()
{
evaluate("Body");
emit done(mNextBlock);
}
| [
"[email protected]"
]
| [
[
[
1,
14
]
]
]
|
e73bd243872e351783ee0a2aef700fcfa33ccb4e | 2bf221bc84477471c79e47bdb758776176202e0a | /plc/lekcja4.cpp | 6c9ab9f0951d08f7baa41b3c5b521c8c486c9fe7 | []
| no_license | uraharasa/plc-programming-simulator | 9613522711f6f9b477c5017e7e1dd0237316a3f4 | a03e068db8b9fdee83ae4db8fe3666f0396000ef | refs/heads/master | 2016-09-06T12:01:02.666354 | 2011-08-14T08:36:49 | 2011-08-14T08:36:49 | 34,528,882 | 0 | 1 | null | null | null | null | WINDOWS-1250 | C++ | false | false | 6,219 | cpp | #include "lekcja4.h"
#include "pamiec.h"
const float temperatura_wody_doplywu = 16; // oC
const float cieplo_wlasciwe = 4190; // [J/(kg * K)]
const float masa_piksla = 1; // [kg]
const float moc_grzalki = 1000; // [W]
void lekcja4::zresetuj()
{
kat_obrotu = 0;
poziom_wody = 0;
nastaw_temperatury = 0;
predkosc_obrotowa = 0;
wskazanie_temperatury_wody = temperatura_wody = temperatura_wody_doplywu;
przycisk = FALSE;
spalona_grzalka = FALSE;
lekcja::zresetuj();
}
BOOL lekcja4::click(int x, int y)
{
if ((x >= 51) && (x < 150) && (y >= 16) && (y < 25))
{
nastaw_temperatury = x-51;
return TRUE;
}
if ((x>=10) && (y>=10) && (x<=30) && (y<=30))
przycisk = TRUE;
return FALSE;
}
lekcja4::lekcja4() : tlo(L"lekcja4\\tlo"),
lampka_czerwona(L"lekcja4\\lampka_czerwona"),
lampka_zielona(L"lekcja4\\lampka_zielona"),
ubrania1(L"lekcja4\\ubrania1"),
ubrania2(L"lekcja4\\ubrania2"),
ubrania3(L"lekcja4\\ubrania3"),
ubrania4(L"lekcja4\\ubrania4"),
ubrania5(L"lekcja4\\ubrania5"),
ubrania6(L"lekcja4\\ubrania6"),
ubrania7(L"lekcja4\\ubrania7"),
ubrania8(L"lekcja4\\ubrania8"),
ubrania9(L"lekcja4\\ubrania9"),
ubrania10(L"lekcja4\\ubrania10"),
ubrania11(L"lekcja4\\ubrania11"),
ubrania12(L"lekcja4\\ubrania12"),
woda(L"lekcja4\\woda")
{
nazwa = L"lekcja4";
pamiec::nowe_parametry_sterownika(1, 5, 100, 100, 3, 0);
wejscia_I = new pamiec(typ_I, 0, 1);
wejscia_AI = new pamiec(typ_AI, 0, 3);
wyjscia_Q = new pamiec(typ_Q, 0, 5);
pamiec::dodaj_opis(typ_I, 0, L"PRANIE");
pamiec::dodaj_opis(typ_AI, 0, L"POZIOM");
pamiec::dodaj_opis(typ_AI, 1, L"CZUJ_TEMP");
pamiec::dodaj_opis(typ_AI, 2, L"NAST_TEMP");
pamiec::dodaj_opis(typ_Q, 0, L"BĘBEN");
pamiec::dodaj_opis(typ_Q, 1, L"KIER_BĘB");
pamiec::dodaj_opis(typ_Q, 2, L"GRZAŁKA");
pamiec::dodaj_opis(typ_Q, 3, L"DOPŁYW");
pamiec::dodaj_opis(typ_Q, 4, L"ODPŁYW");
zresetuj();
}
lekcja4::~lekcja4()
{
pamiec::nowe_parametry_sterownika(0, 0, 0, 0, 0, 0);
}
void lekcja4::podaj_rozmiar_okna(int & szerokosc, int & wysokosc)
{
szerokosc = 200;
wysokosc = 240;
}
void lekcja4::dzialaj()
{
if (!spalona_grzalka)
{
if (przycisk)
{
wejscia_I->zapisz_pamiec(1, 0);
przycisk = FALSE;
}
else
wejscia_I->zapisz_pamiec(0, 0);
kat_obrotu += (float)predkosc_obrotowa / 10.0f;
while (kat_obrotu >= 360)
kat_obrotu -= 360;
while (kat_obrotu < 0)
kat_obrotu += 360;
if (wyjscia_Q->odczytaj_pamiec(0))
if (wyjscia_Q->odczytaj_pamiec(1))
predkosc_obrotowa += 3;
else
predkosc_obrotowa -= 3;
else
if (predkosc_obrotowa > 0)
predkosc_obrotowa -= 1;
else
if (predkosc_obrotowa < 0)
predkosc_obrotowa += 1;
if (predkosc_obrotowa > 100)
predkosc_obrotowa = 100;
if (predkosc_obrotowa < -100)
predkosc_obrotowa = -100;
if (wyjscia_Q->odczytaj_pamiec(3))
{
temperatura_wody = (temperatura_wody*(poziom_wody/10)+0.1f*temperatura_wody_doplywu)/((poziom_wody/10)+0.1f);
poziom_wody += 1;
}
if (wyjscia_Q->odczytaj_pamiec(4))
poziom_wody -= 2;
if (poziom_wody < 0)
poziom_wody = 0;
if (poziom_wody > 500)
poziom_wody = 500;
if (wyjscia_Q->odczytaj_pamiec(2))
if (poziom_wody > 0.1)
temperatura_wody += moc_grzalki / ((poziom_wody/10) * masa_piksla * cieplo_wlasciwe);
else
spalona_grzalka = TRUE;
wskazanie_temperatury_wody += (temperatura_wody-wskazanie_temperatury_wody)*0.01f;
if (wskazanie_temperatury_wody > 90)
wskazanie_temperatury_wody = 90;
if (wskazanie_temperatury_wody < 10)
wskazanie_temperatury_wody = 10;
if (temperatura_wody > 100)
spalona_grzalka = TRUE;
wejscia_AI->zapisz_pamiec((int)wskazanie_temperatury_wody, 1);
wejscia_AI->zapisz_pamiec((int)poziom_wody, 0);
wejscia_AI->zapisz_pamiec(nastaw_temperatury, 2);
}
lekcja::dzialaj();
}
void lekcja4::narysuj(HDC kontekst)
{
tlo.wyswietl(kontekst, 0, 0);
switch ((int)(kat_obrotu / 30))
{
case 0:
ubrania1.wyswietl(kontekst, 55, 116);
break;
case 1:
ubrania2.wyswietl(kontekst, 55, 116);
break;
case 2:
ubrania3.wyswietl(kontekst, 55, 116);
break;
case 3:
ubrania4.wyswietl(kontekst, 55, 116);
break;
case 4:
ubrania5.wyswietl(kontekst, 55, 116);
break;
case 5:
ubrania6.wyswietl(kontekst, 55, 116);
break;
case 6:
ubrania7.wyswietl(kontekst, 55, 116);
break;
case 7:
ubrania8.wyswietl(kontekst, 55, 116);
break;
case 8:
ubrania9.wyswietl(kontekst, 55, 116);
break;
case 9:
ubrania10.wyswietl(kontekst, 55, 116);
break;
case 10:
ubrania11.wyswietl(kontekst, 55, 116);
break;
case 11:
ubrania12.wyswietl(kontekst, 55, 116);
break;
}
if (wyjscia_Q->odczytaj_pamiec(2))
lampka_czerwona.wyswietl(kontekst, 25, 55);
else
lampka_zielona.wyswietl(kontekst, 25, 55);
if (wyjscia_Q->odczytaj_pamiec(3))
lampka_czerwona.wyswietl(kontekst, 135, 72);
else
lampka_zielona.wyswietl(kontekst, 135, 72);
if (wyjscia_Q->odczytaj_pamiec(4))
lampka_czerwona.wyswietl(kontekst, 135, 192);
else
lampka_zielona.wyswietl(kontekst, 135, 192);
int poziom = (int)poziom_wody/10;
woda.wyswietl(kontekst, 55, 116+50-poziom, 50, poziom, 0, 50-poziom);
RECT obszar;
obszar.left = 51+nastaw_temperatury;
obszar.right = obszar.left + 2;
obszar.top = 16;
obszar.bottom = 25;
HBRUSH pedzel = CreateSolidBrush(0xff);
FillRect(kontekst, &obszar, pedzel);
obszar.left = 20;
obszar.right = 25;
obszar.top = 100 + 80 - (int)wskazanie_temperatury_wody + 10;
obszar.bottom = 180;
FillRect(kontekst, &obszar, pedzel);
DeleteObject(pedzel);
if (spalona_grzalka)
{
LOGFONT lf;
memset(&lf, 0, sizeof(LOGFONT));
lf.lfHeight = 29;
lf.lfWeight = FW_NORMAL;
lf.lfCharSet = DEFAULT_CHARSET;
wcscpy(lf.lfFaceName, L"Arial");
lf.lfEscapement = lf.lfOrientation = 450;
HFONT stara = (HFONT)SelectObject(kontekst, CreateFontIndirect(&lf));
SetBkMode(kontekst, TRANSPARENT);
SetTextColor(kontekst, 0xff);
TextOut(kontekst, 20, 180, L"Spaliłeś grzałkę !!!", wcslen(L"Spaliłeś grzałkę !!!"));
DeleteObject(SelectObject(kontekst, stara));
}
}
| [
"[email protected]@2c618d7f-f323-8192-d80b-44f770db81a5"
]
| [
[
[
1,
223
]
]
]
|
ce02896a5e31d78952b2230364470cca80100cff | c82d009662b7b3da2707a577a3143066d128093a | /ftor/quinary_function.h | 96950a83e98cb33f46b3b01c11da53fe032524ac | []
| no_license | canilao/cpp_framework | 01a2c0787440d9fca64dbb0fb10c1175a4f7d198 | da5c612e8f15f6987be0c925f46e854b2e703d73 | refs/heads/master | 2021-01-10T13:26:39.376268 | 2011-02-04T16:26:26 | 2011-02-04T16:26:26 | 49,291,836 | 1 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 17,565 | h | /******************************************************************************/
//
/*! \file
\brief
\note
*******************************************************************************/
#ifndef QUINARY_OBJECT_FUNCTION_H
#define QUINARY_OBJECT_FUNCTION_H
// General dependencies.
#include "i_function.h"
#include "object_function.h"
#include "i_function_delegate.h"
#include "object_function_exception.h"
/******************************************************************************/
//
/*! \namespace Ftor
\brief Namespace containing the object function library.
*******************************************************************************/
namespace Ftor
{
/******************************************************************************/
//
/*! \class
\brief
*******************************************************************************/
template<class RETURN_TYPE,
class PARAM_1,
class PARAM_2,
class PARAM_3,
class PARAM_4,
class PARAM_5>
class IQuinaryFunction : public IFunction
{
public:
// Default constructor.
IQuinaryFunction() {}
// Copy constructor.
IQuinaryFunction(const IQuinaryFunction & orig) {}
// Destructor.
virtual ~IQuinaryFunction() {}
// Executes the function.
virtual RETURN_TYPE operator()(PARAM_1 value_1,
PARAM_2 value_2,
PARAM_3 value_3,
PARAM_4 value_4,
PARAM_5 value_5) const = 0;
};
/******************************************************************************/
//
/*! \class
\brief
*******************************************************************************/
template<class OBJECT_TYPE,
class FUNCTION_TYPE,
class RETURN_TYPE,
class PARAM_1,
class PARAM_2,
class PARAM_3,
class PARAM_4,
class PARAM_5>
class QuinaryObjectFunction :
public IQuinaryFunction<RETURN_TYPE,
PARAM_1,
PARAM_2,
PARAM_3,
PARAM_4,
PARAM_5>,
public ObjectFunction<OBJECT_TYPE, FUNCTION_TYPE>
{
public:
// Default constructor.
QuinaryObjectFunction() {}
// Constructor.
QuinaryObjectFunction(OBJECT_TYPE * pNewObj, FUNCTION_TYPE pNewFunc) :
ObjectFunction<OBJECT_TYPE, FUNCTION_TYPE>(pNewObj, pNewFunc) {}
// Copy constructor.
QuinaryObjectFunction(const QuinaryObjectFunction & orig) :
ObjectFunction<OBJECT_TYPE, FUNCTION_TYPE>(orig.GetObjFunc().pObj,
orig.GetObjFunc().pFunc){}
// Destructor.
virtual ~QuinaryObjectFunction() {}
// Allows the object to make a deep copy.
virtual IFunction * Clone() const
{
// If we are invalid, do not clone ourselves.
if(!IsValid()) return NULL;
IFunction * pPtr = new QuinaryObjectFunction<OBJECT_TYPE,
FUNCTION_TYPE,
RETURN_TYPE,
PARAM_1,
PARAM_2,
PARAM_3,
PARAM_4,
PARAM_5>(*this);
return pPtr;
}
// Checks to see if the pointers are clear.
virtual bool IsValid() const
{
return ObjectFunction<OBJECT_TYPE, FUNCTION_TYPE>::IsValid();
}
// Equality operator.
virtual bool operator==(const IFunction & rhs)
{
bool retVal = true;
// We need to check to see if it is one of ours.
const QuinaryObjectFunction * pSafe =
dynamic_cast<const QuinaryObjectFunction *>(&rhs);
// Only execute if they cast succeeded.
if(retVal &= (pSafe != NULL))
{
// Get the underlying pointers and check if they match with rhs.
retVal &= (this->GetObjFunc().pObj == pSafe->GetObjFunc().pObj);
retVal &= (this->GetObjFunc().pFunc == pSafe->GetObjFunc().pFunc);
}
return retVal;
}
// Executes the function.
RETURN_TYPE operator()(PARAM_1 value_1,
PARAM_2 value_2,
PARAM_3 value_3,
PARAM_4 value_4,
PARAM_5 value_5) const
{
// This is a situation where we cannot execute the function.
if(!this->GetObjFunc().IsValid()) throw ObjectFunctionException();
// Execute the function.
return (this->GetObjFunc().pObj->*(this->GetObjFunc().pFunc))(value_1,
value_2,
value_3,
value_4,
value_5);
}
};
/******************************************************************************/
//
/*! \class
\brief
*******************************************************************************/
template<class OBJECT_TYPE,
class RETURN_TYPE,
class PARAM_1,
class PARAM_2,
class PARAM_3,
class PARAM_4,
class PARAM_5>
class ConstQuinaryObjectFactory
{
public:
// Function pointer type.
typedef RETURN_TYPE (OBJECT_TYPE::*TFuncPtr)(PARAM_1,
PARAM_2,
PARAM_3,
PARAM_4,
PARAM_5) const;
// Unary object function templated type.
typedef QuinaryObjectFunction<OBJECT_TYPE,
TFuncPtr,
RETURN_TYPE,
PARAM_1,
PARAM_2,
PARAM_3,
PARAM_4,
PARAM_5> TFuncObj;
public:
// Constructor.
ConstQuinaryObjectFactory() {}
// Destructor.
virtual ~ConstQuinaryObjectFactory() {}
// Builds a function object.
TFuncObj Create(OBJECT_TYPE * pNewObj, TFuncPtr pNewFunc)
{
return TFuncObj(pNewObj, pNewFunc);
}
};
/******************************************************************************/
//
/*! \class
\brief
*******************************************************************************/
template<class OBJECT_TYPE,
class RETURN_TYPE,
class PARAM_1,
class PARAM_2,
class PARAM_3,
class PARAM_4,
class PARAM_5>
class QuinaryObjectFactory
{
public:
// Function pointer type.
typedef RETURN_TYPE (OBJECT_TYPE::*TFuncPtr)(PARAM_1,
PARAM_2,
PARAM_3,
PARAM_4,
PARAM_5);
// Unary object function templated type.
typedef QuinaryObjectFunction<OBJECT_TYPE,
TFuncPtr,
RETURN_TYPE,
PARAM_1,
PARAM_2,
PARAM_3,
PARAM_4,
PARAM_5> TFuncObj;
public:
// Constructor.
QuinaryObjectFactory() {}
// Destructor.
virtual ~QuinaryObjectFactory() {}
// Builds a function object.
TFuncObj Create(OBJECT_TYPE * pNewObj, TFuncPtr pNewFunc)
{
return TFuncObj(pNewObj, pNewFunc);
}
};
/******************************************************************************/
//
/*! \class
\brief
*******************************************************************************/
template<class RETURN_TYPE,
class PARAM_1,
class PARAM_2,
class PARAM_3,
class PARAM_4,
class PARAM_5>
class QuinaryStaticFunction :
public IQuinaryFunction<RETURN_TYPE,
PARAM_1,
PARAM_2,
PARAM_3,
PARAM_4,
PARAM_5>
{
public:
// Function pointer type.
typedef RETURN_TYPE (*TFuncPtr)(PARAM_1, PARAM_2, PARAM_3, PARAM_4, PARAM_5);
public:
// Constructor.
QuinaryStaticFunction(TFuncPtr pFunc)
{
pFunction = pFunc;
}
// Copy constructor.
QuinaryStaticFunction(const QuinaryStaticFunction & orig)
{
pFunction = orig.pFunction;
}
// Destructor.
virtual ~QuinaryStaticFunction() {}
// Allows the object to make a deep copy.
virtual IFunction * Clone() const
{
// If we are invalid, do not clone ourselves.
if(!IsValid()) return NULL;
IFunction * pPtr = new QuinaryStaticFunction<RETURN_TYPE,
PARAM_1,
PARAM_2,
PARAM_3,
PARAM_4,
PARAM_5>(*this);
return pPtr;
}
// Checks to see if the pointers are clear.
virtual bool IsValid() const
{
return true;
}
// Equality operator.
virtual bool operator==(const IFunction & rhs)
{
bool retVal = true;
// We need to check to see if it is one of ours.
const QuinaryStaticFunction * pSafe =
dynamic_cast<const QuinaryStaticFunction *>(&rhs);
// Only execute if they cast succeeded.
if(retVal &= (pSafe != NULL))
{
// Get the underlying pointers and check if they match with rhs.
retVal &= (pFunction == pSafe->pFunction);
}
return retVal;
}
// Executes the function.
virtual RETURN_TYPE operator()(PARAM_1 value_1,
PARAM_2 value_2,
PARAM_3 value_3,
PARAM_4 value_4,
PARAM_5 value_5) const
{
return (*pFunction)(value_1, value_2, value_3, value_4, value_5);
}
private:
// Default constructor.
QuinaryStaticFunction() {}
private:
// The function pointer.
TFuncPtr pFunction;
};
// Must forward declare the class type so that the actual template can deduce.
template <class Signature> class Delegate;
/******************************************************************************/
//
/*! \class
\brief
*******************************************************************************/
template<class RETURN_TYPE,
class PARAM_1,
class PARAM_2,
class PARAM_3,
class PARAM_4,
class PARAM_5>
class Delegate<RETURN_TYPE (PARAM_1, PARAM_2, PARAM_3, PARAM_4, PARAM_5)> :
public IFunctionDelegate< IQuinaryFunction<RETURN_TYPE,
PARAM_1,
PARAM_2,
PARAM_3,
PARAM_4,
PARAM_5> >
{
public:
// Constructor.
Delegate() {}
// Copy constructor.
Delegate(const typename IFunctionDelegate< IQuinaryFunction<RETURN_TYPE,
PARAM_1,
PARAM_2,
PARAM_3,
PARAM_4,
PARAM_5> >::
TFuncType & newFunc)
{
Add(newFunc);
}
// Static function constructor.
Delegate(RETURN_TYPE (*pFunc)(PARAM_1, PARAM_2, PARAM_3, PARAM_4, PARAM_5))
{
typedef QuinaryStaticFunction<RETURN_TYPE, PARAM_1, PARAM_2, PARAM_3,
PARAM_4, PARAM_5> TFunc;
TFunc obj = TFunc(pFunc);
Add(obj);
}
// Object function constructor.
template<class OBJECT_TYPE>
Delegate(OBJECT_TYPE * pObj,
RETURN_TYPE (OBJECT_TYPE::*pFunc)(PARAM_1, PARAM_2, PARAM_3,
PARAM_4,
PARAM_5))
{
typedef QuinaryObjectFactory<OBJECT_TYPE, RETURN_TYPE, PARAM_1, PARAM_2,
PARAM_3, PARAM_4, PARAM_5> TFact;
TFact fact;
typename TFact::TFuncObj obj = fact.Create(pObj, pFunc);
Add(obj);
}
// Object function constructor.
template<class OBJECT_TYPE>
Delegate(OBJECT_TYPE * pObj,
RETURN_TYPE (OBJECT_TYPE::*pFunc)(PARAM_1,
PARAM_2,
PARAM_3,
PARAM_4,
PARAM_5) const)
{
typedef ConstQuinaryObjectFactory<OBJECT_TYPE,
RETURN_TYPE,
PARAM_1,
PARAM_2,
PARAM_3,
PARAM_4,
PARAM_5> TFact;
TFact fact;
typename TFact::TFuncObj obj = fact.Create(pObj, pFunc);
Add(obj);
}
// Destructor.
virtual ~Delegate() {}
// Operator override.
RETURN_TYPE operator()(PARAM_1 value_1,
PARAM_2 value_2,
PARAM_3 value_3,
PARAM_4 value_4,
PARAM_5 value_5)
{
// Clean out invalids on Ftor calls.
this->CleanOutInvalids();
// Call this constant operator overload.
const Delegate<RETURN_TYPE (PARAM_1,
PARAM_2,
PARAM_3,
PARAM_4,
PARAM_5)> & obj = *this;
return obj(value_1, value_2, value_3, value_4, value_5);
}
// Operator override.
RETURN_TYPE operator()(PARAM_1 value_1,
PARAM_2 value_2,
PARAM_3 value_3,
PARAM_4 value_4,
PARAM_5 value_5) const
{
// Throw an error if we are empty.
if(this->size() == 0) throw ObjectFunctionException();
// Instantiate the iterator.
typename IFunctionDelegate< IQuinaryFunction<RETURN_TYPE,
PARAM_1,
PARAM_2,
PARAM_3,
PARAM_4,
PARAM_5> >::TFuncVector::
const_iterator iter;
// Call all of our contained functions.
for(iter = this->begin() ; iter != this->end() ; ++iter)
{
// Calculate the next iterator.
typename IFunctionDelegate< IQuinaryFunction<RETURN_TYPE,
PARAM_1,
PARAM_2,
PARAM_3,
PARAM_4,
PARAM_5> >::
TFuncVector::const_iterator nextIter = iter;
++nextIter;
if(nextIter == this->end())
{
break;
}
else
{
if((*iter)->IsValid())
{
(*(*iter))(value_1, value_2, value_3, value_4, value_5);
}
}
}
// Special situation where the very last function is invalid.
if(!(*iter)->IsValid())
{
// If this one is invalid we have to throw because we have
// nothing to return.
throw ObjectFunctionException();
}
// Calls the last function and returns its value.
return (*(*iter))(value_1, value_2, value_3, value_4, value_5);
}
};
}
#endif
| [
"canilao@55e5c601-11dd-bd4b-a960-93a593583956",
"Chris@55e5c601-11dd-bd4b-a960-93a593583956"
]
| [
[
[
1,
9
],
[
20,
26
],
[
29,
35
],
[
63,
69
],
[
169,
225
],
[
269,
275
],
[
378,
384
],
[
443,
464
],
[
478,
494
]
],
[
[
10,
19
],
[
27,
28
],
[
36,
62
],
[
70,
168
],
[
226,
268
],
[
276,
377
],
[
385,
442
],
[
465,
477
],
[
495,
547
]
]
]
|
4328ee3d53fda2028ac660d6282e32824256c7cd | 1599a23c594b6d9d19ecaef701d9aafdce17a7a3 | /source/plimdp/cpu/tracing/tracer.h | b5fa0ca1232817687b04053cb4b7aca7a4c317d3 | []
| no_license | pavelkryukov/plimdp-plus | 6c5a201cc8df2c7a1754320e7305040051d81441 | 953b378f771d22b3a52186e67c1d7eb74b10c71c | refs/heads/master | 2020-05-15T12:31:16.861244 | 2011-11-17T16:41:19 | 2011-11-17T16:41:19 | 32,184,827 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 470 | h | /*
* tracer.h
*
* PlimDP+ core trace
*
* Copyright 2009 (C) Boris Belousov
* Copyright 2011 (C) Pavel Kryukov (remastering)
*/
#ifndef COREDUMP_H
#define COREDUMP_H
#include <plimdp/generic/types.h>
namespace PlimDP {
namespace CPU {
class Executor;
class Tracer {
private:
const Executor* const parent;
public:
explicit Tracer(const Executor* core);
void running();
void core();
void end();
};
}
}
#endif | [
"[email protected]"
]
| [
[
[
1,
31
]
]
]
|
42bcd8394866467a397f85fba97fc9e9211cd3f4 | 155c4955c117f0a37bb9481cd1456b392d0e9a77 | /Tessa/TessaInstructions/SetSlotInstruction.cpp | e46863706a8e9a29dc2d9d1c09fad1aa4bc87c32 | []
| no_license | zwetan/tessa | 605720899aa2eb4207632700abe7e2ca157d19e6 | 940404b580054c47f3ced7cf8995794901cf0aaa | refs/heads/master | 2021-01-19T19:54:00.236268 | 2011-08-31T00:18:24 | 2011-08-31T00:18:24 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 2,128 | cpp |
#include "TessaInstructionHeader.h"
namespace TessaInstructions {
SetSlotInstruction::SetSlotInstruction(uint32_t slotNumber, int32_t slotOffset, TessaInstruction* receiverObject, TessaInstruction* valueToSet, Traits* slotTraits, TessaVM::BasicBlock* insertAtEnd)
: SlotAccessInstruction(slotNumber, slotOffset, receiverObject, insertAtEnd)
{
this->valueToSet = valueToSet;
this->slotTraits = slotTraits;
}
void SetSlotInstruction::print() {
char buffer[128];
VMPI_snprintf(buffer, sizeof(buffer), "%s SetSlot %s.slot %d (Offset %d) = %s (Type %s)", this->getPrintPrefix().c_str(),
getReceiverObject()->getOperandString().c_str(),
getSlotNumber(),
getSlotOffset(),
valueToSet->getOperandString().c_str(),
getType()->toString().data()
);
printf("%s\n", buffer);
}
void SetSlotInstruction::visit(TessaVisitorInterface* tessaVisitor) {
tessaVisitor->visit(this);
}
void SetSlotInstruction::setValueToSet(TessaInstruction* valueToset) {
this->valueToSet = valueToSet;
}
TessaInstruction* SetSlotInstruction::getValueToSet() {
return valueToSet;
}
Traits* SetSlotInstruction::getSlotTraits() {
return this->slotTraits;
}
SetSlotInstruction* SetSlotInstruction::clone(MMgc::GC *gc, MMgc::GCHashtable* originalToCloneMap, TessaVM::BasicBlock* insertCloneAtEnd) {
TessaInstruction* receiverClone = (TessaInstruction*) originalToCloneMap->get(this->getReceiverObject());
TessaInstruction* valueToSetClone = (TessaInstruction*) originalToCloneMap->get(this->getValueToSet());
SetSlotInstruction* setSlotClone = new (gc) SetSlotInstruction(this->getSlotNumber(), getSlotOffset(), receiverClone, valueToSetClone, slotTraits, insertCloneAtEnd);
setSlotClone->setType(this->getType());
return setSlotClone;
}
List<TessaValue*, LIST_GCObjects>* SetSlotInstruction::getOperands(MMgc::GC* gc) {
avmplus::List<TessaValue*, LIST_GCObjects>* operandList = new (gc) avmplus::List<TessaValue*, LIST_GCObjects>(gc);
operandList->add(getReceiverObject());
operandList->add(getValueToSet());
return operandList;
}
} | [
"[email protected]"
]
| [
[
[
1,
54
]
]
]
|
b003d38c5f6b973f784160e68218a2b9d295f11c | b999131a99dbbe85b256ed64700fc8651f69eb98 | /VNE_SOURCE/vne/deprecated/VNETexture.h | f561428ebdcd718cf426bc3f35808016bab0e010 | []
| no_license | liukan12/vne | 71ba2a63ade36b638107f2800ae6d9a3b3b56d52 | e896cc57af75c72ee5b52530ee9d9d1e7cfe73be | refs/heads/master | 2020-12-24T20:15:21.148998 | 2008-08-01T05:55:10 | 2008-08-01T05:55:10 | 56,172,273 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 516 | h | #ifndef VNETEXTURE
#define VNETEXTURE
#include <stdio.h>
#include <stdlib.h>
#include <windows.h>
#include <iostream>
#include <GL/gl.h>
#include <GL/glu.h>
#include <GL/glut.h>
#include "SOIL.h"
using namespace std;
class VNETexture
{
private:
GLuint tex_2d;
public:
~VNETexture();
VNETexture(const VNETexture& obj);
VNETexture& operator=(const VNETexture& rhs);
void CopyObj(const VNETexture& obj);
VNETexture(string fileName);
void bindTexture();
};
#endif | [
"karasevpa@60124b6e-824b-0410-a204-ab2e215a433f",
"freeradiobuckscounty@60124b6e-824b-0410-a204-ab2e215a433f"
]
| [
[
[
1,
21
],
[
27,
37
]
],
[
[
22,
26
]
]
]
|
d841a35bde1ce18925124277177c182a942bedc6 | 00b979f12f13ace4e98e75a9528033636dab021d | /branches/ziahttpd-mod/src/server/core.cc | bd8328f0bfa167777667d34ad8a2ae9379a9e3c3 | []
| no_license | BackupTheBerlios/ziahttpd-svn | 812e4278555fdd346b643534d175546bef32afd5 | 8c0b930d3f4a86f0622987776b5220564e89b7c8 | refs/heads/master | 2016-09-09T20:39:16.760554 | 2006-04-13T08:44:28 | 2006-04-13T08:44:28 | 40,819,288 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 6,116 | cc | //
// core.cc for in
//
// Made by texane
// Login <[email protected]>
//
// Started on Tue Oct 11 21:28:14 2005 texane
// Last update Thu Dec 01 22:33:38 2005 texane
//
#include <list>
#include <vector>
#include <string>
#include <iostream>
#include <server/core.hh>
#include <server/server.hh>
#include <server/modhelper.hh>
#include <sysapi/sysapi.hh>
#include <dataman/conf.hh>
#include <http/session.hh>
using std::cout;
using std::cerr;
using std::endl;
using std::string;
using std::vector;
using std::list;
using http::session;
// Singleton-like behaviour
server::core* server::core::instance_ = 0;
server::service* server::core::services_ = 0;
// - Construction, destruction
server::core::core()
{
reset();
sysapi::socket_in::init_subsystem();
instance_ = this;
services_ = new service;
ioman_ = new ioselect;
reload_conf();
}
server::core::core(int ac, char** av)
{
reset();
sysapi::socket_in::init_subsystem();
instance_ = this;
services_ = new service;
ioman_ = new ioselect;
reload_conf();
}
server::core::~core()
{
release();
sysapi::socket_in::release_subsystem();
}
bool server::core::reset()
{
services_ = 0;
instance_ = 0;
ioman_ = 0;
done_ = false;
initialized_ = false;
return true;
}
bool server::core::release()
{
if (ioman_)
delete ioman_;
return true;
}
bool server::core::reload_conf()
{
// Load modules
// Currently only bootstrap with hardcoded modules
// in the above array.
// Load the module list
{
vector<string> modules;
modules = conf_.GetListVector("modules");
vector<string>::iterator cur = modules.begin();
vector<string>::iterator end = modules.end();
while (cur != end)
{
// Normalize the module name
sysapi::file::normalize_name(*cur);
if (modman_.load_at_beginning(*cur) == false)
sysapi::error::stringify("Cannot load module");
++cur;
}
}
return true;
}
bool server::core::reload_conf(const string& confname)
{
return false;
}
// ?
// This is the running function of the server, threaded
// one. keep it comment until the ioselect manager
// has been tested.
// bool server::core::run()
// {
// // !
// // This is a temporary version of the network engine.
// // One thread implement request handling, in order to begin
// // modularization of the request processing flow.
// for (;;)
// {
// // Create the server connection, accepting incoming ones
// http::session* session = new http::session(conf_);
// sysapi::socket_in::handle_t hsock_srv;
// sysapi::socket_in::handle_t hsock_con;
// sysapi::socket_in::create_listening(&hsock_srv, 40000);
// session->hsock_srv() = hsock_srv;
// sysapi::socket_in::accept(&hsock_con, hsock_srv);
// session->hsock_con() = hsock_con;
// // Create the request processing thread
// sysapi::thread::handle_t hthread;
// sysapi::thread::create_and_exec(&hthread, server::core::process_request, reinterpret_cast<sysapi::thread::param_t>(session));
// sysapi::thread::wait_single(hthread);
// sysapi::thread::release(hthread);
// // Delete the session
// delete session;
// }
// return true;
// }
bool server::core::handle_default_termination(sysapi::socket_in::handle_t& hsock,
dataman::buffer*,
sysapi::socket_in::error_t&)
{
// ?
// Handle the default termination
return http::session_manager::remove(hsock);
}
bool server::core::handle_default_connection(sysapi::socket_in::handle_t& hsock,
dataman::buffer*,
sysapi::socket_in::error_t&)
{
// ?
// Handle default connections
// Registering a new session is matter
// of adding new connection
// Get the connection socket
sysapi::socket_in::handle_t hsock_con;
sysapi::socket_in::accept(&hsock_con, hsock);
// Continue looking for incoming connections
instance_->ioman_->read(hsock, handle_default_connection, 0);
// Register ioman entry for this socket
instance_->ioman_->register_sockhdl(hsock_con);
http::session_manager::add(hsock_con);
// Call hook for create_connection step, that register or
// not a hook for this one.
cout << "\t\t[? " << std::dec << (unsigned int)hsock << "]: new socket registered: " << (unsigned int)hsock_con << endl;
return true;
}
bool server::core::run()
{
// Here bootstrap the io manager
// by creating a listening socket
// on the port 40000.
// Put a creation callback that will
// be called, and will create session for
// the new connections.
// Bootstrap the server
// Here we should have a hook or
// module dedicated to
// handle connection listening
sysapi::socket_in::handle_t hsock_srv;
sysapi::socket_in::create_listening(&hsock_srv, 40000);
ioman_->register_sockhdl(hsock_srv);
ioman_->read(hsock_srv, handle_default_connection, 0);
// actually, do an accept
for (;;)
{
ioman_->handle_io();
http::session_manager::process();
}
return true;
}
server::core* server::core::instance()
{
return instance_;
}
sysapi::thread::retcode_t server::core::process_request(sysapi::thread::param_t param)
{
http::session* session = reinterpret_cast<http::session*>(param);
try
{
simulate_manager:
if (session->persistent() == true)
{
// Reset the session internals
if (session->reset_me_)
session->reset();
// Iterate over the processing stages
if (modman::instance()->call_hooks(core::instance(), session->stageid_, session) == true)
{
// Go to the next processing stage
modman::next_processing_stage(*session);
}
}
goto simulate_manager;
}
catch (exception::base& err)
{
err.report();
err.solve();
}
catch (...)
{
cerr << "<not-a-zia> exception caugth" << endl;
}
return 0;
}
| [
"texane@754ce95b-6e01-0410-81d0-8774ba66fe44"
]
| [
[
[
1,
267
]
]
]
|
d211474a770143ed709d591e1753b18ad36d59bc | b8ac0bb1d1731d074b7a3cbebccc283529b750d4 | /Code/controllers/RecollectionBenchmark/robotapi/real/RealTrashBin.cpp | 240968b5d8deea41c8bc6d212264ad7279d70163 | []
| no_license | dh-04/tpf-robotica | 5efbac38d59fda0271ac4639ea7b3b4129c28d82 | 10a7f4113d5a38dc0568996edebba91f672786e9 | refs/heads/master | 2022-12-10T18:19:22.428435 | 2010-11-05T02:42:29 | 2010-11-05T02:42:29 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 661 | cpp | #include "RealTrashBin.h"
namespace robotapi {
namespace real {
RealTrashBin::RealTrashBin(protocol::handlers::TrashBinBoardPacketHandler * tbbph,std::string name)
: RealDevice(&name){
this->boardHandler = tbbph;
}
int RealTrashBin::enable(int ms){
return 0;
}
int RealTrashBin::disable(){
return 0;
}
int RealTrashBin::getValue(){
return this->boardHandler->getValue();
}
bool RealTrashBin::isFull(){
return this->boardHandler->isFull();
}
void RealTrashBin::setFullBias(double bias){
return this->boardHandler->setFullBias(bias);
}
} /* End of namespace robotapi::real */
} /* End of namespace robotapi */
| [
"guicamest@d69ea68a-f96b-11de-8cdf-e97ad7d0f28a"
]
| [
[
[
1,
32
]
]
]
|
3f108a508db212a164dac8978cf0d5159289d057 | 6581dacb25182f7f5d7afb39975dc622914defc7 | /QQHideWnd/StdAfx.cpp | c3c44e2c357d44ffbcc69cc241be77caaab51bd6 | []
| no_license | dice2019/alexlabonline | caeccad28bf803afb9f30b9e3cc663bb2909cc4f | 4c433839965ed0cff99dad82f0ba1757366be671 | refs/heads/master | 2021-01-16T19:37:24.002905 | 2011-09-21T15:20:16 | 2011-09-21T15:20:16 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 211 | cpp | // stdafx.cpp : source file that includes just the standard includes
// QQHideWnd.pch will be the pre-compiled header
// stdafx.obj will contain the pre-compiled type information
#include "stdafx.h"
| [
"damoguyan8844@3a4e9f68-f5c2-36dc-e45a-441593085838"
]
| [
[
[
1,
8
]
]
]
|
e9b3f14190b4253d993d5180cc00389227163639 | ef23e388061a637f82b815d32f7af8cb60c5bb1f | /src/emu/state.h | 36523ba069b6d51aa049fee35e62d46ecf76f8fc | []
| no_license | marcellodash/psmame | 76fd877a210d50d34f23e50d338e65a17deff066 | 09f52313bd3b06311b910ed67a0e7c70c2dd2535 | refs/heads/master | 2021-05-29T23:57:23.333706 | 2011-06-23T20:11:22 | 2011-06-23T20:11:22 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 11,767 | h | /***************************************************************************
state.h
Save state management functions.
****************************************************************************
Copyright Aaron Giles
All rights reserved.
Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions are
met:
* Redistributions of source code must retain the above copyright
notice, this list of conditions and the following disclaimer.
* Redistributions in binary form must reproduce the above copyright
notice, this list of conditions and the following disclaimer in
the documentation and/or other materials provided with the
distribution.
* Neither the name 'MAME' nor the names of its contributors may be
used to endorse or promote products derived from this software
without specific prior written permission.
THIS SOFTWARE IS PROVIDED BY AARON GILES ''AS IS'' AND ANY EXPRESS OR
IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
DISCLAIMED. IN NO EVENT SHALL AARON GILES BE LIABLE FOR ANY DIRECT,
INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
(INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT,
STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING
IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
POSSIBILITY OF SUCH DAMAGE.
***************************************************************************/
#pragma once
#ifndef __EMU_H__
#error Dont include this file directly; include emu.h instead.
#endif
#ifndef __STATE_H__
#define __STATE_H__
//**************************************************************************
// CONSTANTS
//**************************************************************************
enum state_save_error
{
STATERR_NONE,
STATERR_ILLEGAL_REGISTRATIONS,
STATERR_INVALID_HEADER,
STATERR_READ_ERROR,
STATERR_WRITE_ERROR
};
//**************************************************************************
// MACROS
//**************************************************************************
// macros to declare presave/postload functions with the appropriate parameters
#define STATE_PRESAVE(name) void name(running_machine &machine, void *param)
#define STATE_POSTLOAD(name) void name(running_machine &machine, void *param)
// templates to assume the 'param' of a presave/postload function is a class pointer
template<class T, void (T::*func)()>
void state_presave_stub(running_machine &machine, void *param)
{
T *target = reinterpret_cast<T *>(param);
(target->*func)();
}
template<class T, void (T::*func)()>
void state_postload_stub(running_machine &machine, void *param)
{
T *target = reinterpret_cast<T *>(param);
(target->*func)();
}
// use this to declare a given type is a simple, non-pointer type that can be
// saved; in general, this is intended only to be used for specific enum types
// defined by your device
#define ALLOW_SAVE_TYPE(TYPE) template<> struct state_manager::type_checker<TYPE> { static const bool is_atom = true; static const bool is_pointer = false; }
// register items with explicit tags
#define state_save_register_item(_mach, _mod, _tag, _index, _val) \
(_mach).state().save_item(_mod, _tag, _index, _val, #_val)
#define state_save_register_item_pointer(_mach, _mod, _tag, _index, _val, _count) \
(_mach).state().save_pointer(_mod, _tag, _index, _val, #_val, _count)
#define state_save_register_item_array(_mach, _mod, _tag, _index, _val) \
(_mach).state().save_item(_mod, _tag, _index, _val, #_val)
#define state_save_register_item_2d_array(_mach, _mod, _tag, _index, _val) \
(_mach).state().save_item(_mod, _tag, _index, _val, #_val)
#define state_save_register_item_bitmap(_mach, _mod, _tag, _index, _val) \
(_mach).state().save_item(_mod, _tag, _index, *(_val), #_val)
// register global items
#define state_save_register_global(_mach, _val) \
(_mach).state().save_item(_val, #_val)
#define state_save_register_global_pointer(_mach, _val, _count) \
(_mach).state().save_pointer(_val, #_val, _count)
#define state_save_register_global_array(_mach, _val) \
(_mach).state().save_item(_val, #_val)
#define state_save_register_global_2d_array(_mach, _val) \
(_mach).state().save_item(_val, #_val)
#define state_save_register_global_bitmap(_mach, _val) \
(_mach).state().save_item(*(_val), #_val)
//**************************************************************************
// TYPE DEFINITIONS
//**************************************************************************
class state_manager
{
// type_checker is a set of templates to identify valid save types
template<typename T> struct type_checker { static const bool is_atom = false; static const bool is_pointer = false; };
template<typename T> struct type_checker<T*> { static const bool is_atom = false; static const bool is_pointer = true; };
public:
typedef void (*prepost_func)(running_machine &machine, void *param);
// construction/destruction
state_manager(running_machine &machine);
// getters
int registration_count() const { return m_entry_list.count(); }
bool registration_allowed() const { return m_reg_allowed; }
// registration control
void allow_registration(bool allowed = true);
const char *indexed_item(int index, void *&base, UINT32 &valsize, UINT32 &valcount) const;
// function registration
void register_presave(prepost_func func, void *param);
void register_postload(prepost_func func, void *param);
// generic memory registration
void save_memory(const char *module, const char *tag, UINT32 index, const char *name, void *val, UINT32 valsize, UINT32 valcount = 1);
// templatized wrapper for general objects
template<typename T>
void save_item(const char *module, const char *tag, int index, T &value, const char *valname)
{
if (type_checker<T>::is_pointer) throw emu_fatalerror("Called save_item on a pointer with no count!");
if (!type_checker<T>::is_atom) throw emu_fatalerror("Called save_item on a non-fundamental type!");
save_memory(module, tag, index, valname, &value, sizeof(value));
}
// templatized wrapper for 1-dimensional arrays
template<typename T, std::size_t N>
void save_item(const char *module, const char *tag, int index, T (&value)[N], const char *valname)
{
if (!type_checker<T>::is_atom) throw emu_fatalerror("Called save_item on a non-fundamental type!");
save_memory(module, tag, index, valname, &value[0], sizeof(value[0]), N);
}
// templatized wrapper for 2-dimensional arrays
template<typename T, std::size_t M, std::size_t N>
void save_item(const char *module, const char *tag, int index, T (&value)[M][N], const char *valname)
{
if (!type_checker<T>::is_atom) throw emu_fatalerror("Called save_item on a non-fundamental type!");
save_memory(module, tag, index, valname, &value[0][0], sizeof(value[0][0]), M * N);
}
// templatized wrapper for pointers
template<typename T>
void save_pointer(const char *module, const char *tag, int index, T *value, const char *valname, UINT32 count)
{
if (!type_checker<T>::is_atom) throw emu_fatalerror("Called save_item on a non-fundamental type!");
save_memory(module, tag, index, valname, value, sizeof(*value), count);
}
// global memory registration
template<typename T>
void save_item(T &value, const char *valname, int index = 0) { save_item("global", NULL, index, value, valname); }
template<typename T>
void save_pointer(T *value, const char *valname, UINT32 count, int index = 0) { save_pointer("global", NULL, index, value, valname, count); }
// file processing
static state_save_error check_file(running_machine &machine, emu_file &file, const char *gamename, void (CLIB_DECL *errormsg)(const char *fmt, ...));
state_save_error write_file(emu_file &file);
state_save_error read_file(emu_file &file);
private:
// internal helpers
UINT32 signature() const;
void dump_registry() const;
static state_save_error validate_header(const UINT8 *header, const char *gamename, UINT32 signature, void (CLIB_DECL *errormsg)(const char *fmt, ...), const char *error_prefix);
// state callback item
class state_callback
{
public:
// construction/destruction
state_callback(prepost_func callback, void *param);
// getters
state_callback *next() const { return m_next; }
// state
state_callback * m_next; // pointer to next entry
void * m_param; // function parameter
prepost_func m_func; // pointer to the function
};
class state_entry
{
public:
// construction/destruction
state_entry(void *data, const char *name, UINT8 size, UINT32 count);
// getters
state_entry *next() const { return m_next; }
// helpers
void flip_data();
// state
state_entry * m_next; // pointer to next entry
void * m_data; // pointer to the memory to save/restore
astring m_name; // full name
UINT8 m_typesize; // size of the raw data type
UINT32 m_typecount; // number of items
UINT32 m_offset; // offset within the final structure
};
// internal state
running_machine & m_machine; // reference to our machine
bool m_reg_allowed; // are registrations allowed?
int m_illegal_regs; // number of illegal registrations
simple_list<state_entry> m_entry_list; // list of reigstered entries
simple_list<state_callback> m_presave_list; // list of pre-save functions
simple_list<state_callback> m_postload_list; // list of post-load functions
static const char s_magic_num[8]; // magic number for header
};
// template specializations to enumerate the fundamental atomic types you are allowed to save
ALLOW_SAVE_TYPE(bool);
ALLOW_SAVE_TYPE(INT8);
ALLOW_SAVE_TYPE(UINT8);
ALLOW_SAVE_TYPE(INT16);
ALLOW_SAVE_TYPE(UINT16);
ALLOW_SAVE_TYPE(INT32);
ALLOW_SAVE_TYPE(UINT32);
ALLOW_SAVE_TYPE(INT64);
ALLOW_SAVE_TYPE(UINT64);
ALLOW_SAVE_TYPE(PAIR);
ALLOW_SAVE_TYPE(PAIR64);
ALLOW_SAVE_TYPE(float);
ALLOW_SAVE_TYPE(double);
ALLOW_SAVE_TYPE(endianness_t);
//**************************************************************************
// INLINE FUNCTIONS
//**************************************************************************
//-------------------------------------------------
// save_item - specialized save_item for bitmaps
//-------------------------------------------------
template<>
inline void state_manager::save_item(const char *module, const char *tag, int index, bitmap_t &value, const char *name)
{
save_memory(module, tag, index, name, value.base, value.bpp / 8, value.rowpixels * value.height);
}
//-------------------------------------------------
// save_item - specialized save_item for attotimes
//-------------------------------------------------
template<>
inline void state_manager::save_item(const char *module, const char *tag, int index, attotime &value, const char *name)
{
astring tempstr(name, ".attoseconds");
save_memory(module, tag, index, tempstr, &value.attoseconds, sizeof(value.attoseconds));
tempstr.cpy(name).cat(".seconds");
save_memory(module, tag, index, tempstr, &value.seconds, sizeof(value.seconds));
}
#endif /* __STATE_H__ */
| [
"Mike@localhost"
]
| [
[
[
1,
312
]
]
]
|
5064604c0f76d862bd389b5b97b7036d1bc3f880 | e7c45d18fa1e4285e5227e5984e07c47f8867d1d | /Application/SysCAD/ScdAppTag.cpp | e4e917b8444922d6bee07c91f3e097247d9708cc | []
| no_license | abcweizhuo/Test3 | 0f3379e528a543c0d43aad09489b2444a2e0f86d | 128a4edcf9a93d36a45e5585b70dee75e4502db4 | refs/heads/master | 2021-01-17T01:59:39.357645 | 2008-08-20T00:00:29 | 2008-08-20T00:00:29 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 626 | cpp | // ScdAppTag.cpp : Implementation of CScppdATag
#include "stdafx.h"
#include "SysCAD_i.h"
#include "ScdAppTag.h"
/////////////////////////////////////////////////////////////////////////////
// CScdAppTag
STDMETHODIMP CScdAppTag::InterfaceSupportsErrorInfo(REFIID riid)
{
static const IID* arr[] =
{
&IID_IScdAppTag
};
for (int i=0; i < sizeof(arr) / sizeof(arr[0]); i++)
{
if (InlineIsEqualGUID(*arr[i],riid))
return S_OK;
}
return S_FALSE;
}
void CScdAppTag::FireTheEvent(long Evt, long Data)
{
switch (Evt)
{
case ComCmd_NULL : /*Fire_On...*/ ; break;
};
};
| [
"[email protected]"
]
| [
[
[
1,
29
]
]
]
|
e199e0c208565cc1a764bb376438903e5d85522a | 4d5ee0b6f7be0c3841c050ed1dda88ec128ae7b4 | /extern/tclap/HelpVisitor.h | c3c52dd94d587429a115ecaeeefe46a12d7c67fa | []
| no_license | saggita/nvidia-mesh-tools | 9df27d41b65b9742a9d45dc67af5f6835709f0c2 | a9b7fdd808e6719be88520e14bc60d58ea57e0bd | refs/heads/master | 2020-12-24T21:37:11.053752 | 2010-09-03T01:39:02 | 2010-09-03T01:39:02 | 56,893,300 | 0 | 1 | null | null | null | null | UTF-8 | C++ | false | false | 1,853 | h |
/******************************************************************************
*
* file: HelpVisitor.h
*
* Copyright (c) 2003, Michael E. Smoot .
* All rights reverved.
*
* See the file COPYING in the top directory of this distribution for
* more information.
*
* THE SOFTWARE IS PROVIDED _AS IS_, WITHOUT WARRANTY OF ANY KIND, EXPRESS
* OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL
* THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
* FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
* DEALINGS IN THE SOFTWARE.
*
*****************************************************************************/
#ifndef TCLAP_HELP_VISITOR_H
#define TCLAP_HELP_VISITOR_H
#include <tclap/CmdLineInterface.h>
#include <tclap/CmdLineOutput.h>
#include <tclap/Visitor.h>
namespace TCLAP {
/**
* A Visitor object that calls the usage method of the given CmdLineOutput
* object for the specified CmdLine object.
*/
class HelpVisitor: public Visitor
{
protected:
/**
* The CmdLine the output will be generated for.
*/
CmdLineInterface* _cmd;
/**
* The output object.
*/
CmdLineOutput** _out;
public:
/**
* Constructor.
* \param cmd - The CmdLine the output will be generated for.
* \param out - The type of output.
*/
HelpVisitor(CmdLineInterface* cmd, CmdLineOutput** out)
: Visitor(), _cmd( cmd ), _out( out ) { }
/**
* Calls the usage method of the CmdLineOutput for the
* specified CmdLine.
*/
void visit() { (*_out)->usage(*_cmd); exit(0); }
};
}
#endif
| [
"castano@0f2971b0-9fc2-11dd-b4aa-53559073bf4c"
]
| [
[
[
1,
69
]
]
]
|
2c4f74e42b48f0e448da03e8db14f5fdb8825606 | b22c254d7670522ec2caa61c998f8741b1da9388 | /dependencies/OpenSceneGraph/include/osgParticle/Export | 4ed571f2716782e250806e0441057079ec43a211 | []
| no_license | ldaehler/lbanet | 341ddc4b62ef2df0a167caff46c2075fdfc85f5c | ecb54fc6fd691f1be3bae03681e355a225f92418 | refs/heads/master | 2021-01-23T13:17:19.963262 | 2011-03-22T21:49:52 | 2011-03-22T21:49:52 | 39,529,945 | 0 | 1 | null | null | null | null | UTF-8 | C++ | false | false | 1,706 | /* -*-c++-*- OpenSceneGraph - Copyright (C) 1998-2006 Robert Osfield
*
* This library is open source and may be redistributed and/or modified under
* the terms of the OpenSceneGraph Public License (OSGPL) version 0.0 or
* (at your option) any later version. The full license is in LICENSE file
* included with this distribution, and on the openscenegraph.org website.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* OpenSceneGraph Public License for more details.
*/
//osgParticle - Copyright (C) 2002 Marco Jez
#ifndef OSGPARTICLE_EXPORT_
#define OSGPARTICLE_EXPORT_ 1
#if defined(WIN32) && !(defined(__CYGWIN__) || defined(__MINGW32__))
#pragma warning( disable : 4244 )
#pragma warning( disable : 4251 )
#pragma warning( disable : 4275 )
#pragma warning( disable : 4786 )
#pragma warning( disable : 4290 )
#pragma warning( disable : 4305 )
#pragma warning( disable : 4996 )
#endif
#if defined(_MSC_VER) || defined(__CYGWIN__) || defined(__MINGW32__) || defined( __BCPLUSPLUS__) || defined( __MWERKS__)
# if defined( OSG_LIBRARY_STATIC )
# define OSGPARTICLE_EXPORT
# elif defined( OSGPARTICLE_LIBRARY )
# define OSGPARTICLE_EXPORT __declspec(dllexport)
# else
# define OSGPARTICLE_EXPORT __declspec(dllimport)
# endif
#else
# define OSGPARTICLE_EXPORT
#endif
/**
\namespace osgParticle
The osgParticle library is a NodeKit that extends the core scene graph to support particle effects.
*/
#endif
| [
"vdelage@3806491c-8dad-11de-9a8c-6d5b7d1e4d13"
]
| [
[
[
1,
49
]
]
]
|
|
ff45b32a1709e68c8eaf08e294a3dc64d29cd47c | 102b11022aa5e7b2be4736b9d1be1162e7bf418f | /project_1/gamepad_test/main.cpp | bda770ebdfbda44f64c52e12149553f337565e1f | []
| no_license | daudet/seng466-2011-hovercraft | 52df9639a62c4a67c9129001fe959b11f36ebd09 | 46da8d0669de9dae71aa890f9349787a8756c3ad | refs/heads/master | 2021-03-12T20:42:45.030618 | 2011-04-19T05:14:55 | 2011-04-19T05:14:55 | 32,120,852 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,685 | cpp | /*
* main.cpp
*
* Created on: Jan 23, 2011
* Author: daudet
*/
#include "include/WProgram.h"
#include "include/wiring.h"
extern "C" void __cxa_pure_virtual(){
for(;;);
}
int main(void){
init();
TCCR3B |= _BV(CS30);
TCCR3B &= ~_BV(CS32);
TCCR3B &= ~_BV(CS31);
pinMode(2, OUTPUT);
pinMode(3, OUTPUT);
//Motor directions
pinMode(8, OUTPUT);
pinMode(9, OUTPUT);
pinMode(10, OUTPUT);
pinMode(11, OUTPUT);
digitalWrite(8, LOW);
digitalWrite(9, HIGH);
digitalWrite(10, LOW);
digitalWrite(11, HIGH);
digitalWrite(2, LOW);
digitalWrite(3,LOW);
Serial.begin(38400);
int8_t data[18];
uint8_t i = 0;
for(i = 0; i < 18; i++){
data[i] = 0;
}
pinMode(13, OUTPUT);
for(;;){
// wait until a full packet has been buffered
while (Serial.available() < 18);
//fill the buffer with the 20 bytes received
for (i = 0; i < 18 ; i++)
data[i] = Serial.read();
Serial.flush();
//RIGHTSIDE
if(data[15] < 0){ //UP
digitalWrite(8, LOW);
digitalWrite(9, HIGH);
analogWrite(2, abs(data[15])<<1);
}
else if(data[15] > 0){ //DOWN
digitalWrite(8, HIGH);
digitalWrite(9, LOW);
analogWrite(2, abs(data[15])<<1);
}
else{
digitalWrite(2, LOW);
}
//LEFTSIDE
if(data[13] < 0){//UP
digitalWrite(10, LOW);
digitalWrite(11, HIGH);
analogWrite(3, abs(data[13])<<1);
}
else if(data[13] > 0){//DOWN
digitalWrite(10, HIGH);
digitalWrite(11, LOW);
analogWrite(3, abs(data[13])<<1);
}
else{
digitalWrite(3, LOW);
}
}
//ensure that main never returns and runs arbitrary code
for(;;);
return 0;
}
| [
"david@b282a14c-f844-f624-09bc-e1946d22bf1e"
]
| [
[
[
1,
96
]
]
]
|
8d99bc46fbfb31c979604adf1514101feda1f886 | 6cd9ca7aa981e8fc04fd93daa1b9c8c938bc89ad | /Code/Tests/Flash/Flash.cpp | 78a044b6519ee6ffa11600909e066cec27af4316 | [
"MIT"
]
| permissive | imaginationac/Monocle-Engine | a80c5c71797174f2c29974220a6574bc7df8da43 | c1d396a3cb133295a888b0765bc30d5f8dff5391 | refs/heads/master | 2021-01-19T04:41:13.930872 | 2011-04-18T17:53:32 | 2011-04-18T17:53:32 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 19,034 | cpp | #include "Flash.h"
#include "../../XML/tinyxml.h"
#include <math.h>
#include <algorithm>
// this puppy will be cleaned up and refactored to the max later
namespace Flash
{
Texture* TextureSheet::GetTextureByName(const std::string &name)
{
for (std::vector<Texture>::iterator i = textures.begin(); i != textures.end(); ++i)
{
Texture *texture = (Texture*)(&(*i)); // <- haHA! take that, Bjarne
if (texture->name == name)
{
return texture;
}
}
return NULL;
}
int Animation::GetMaxFrames()
{
int max = -1;
for (int i = 0; i < parts.size(); i++)
{
if (max == -1 || parts[i].frames.size() > max)
{
max = parts[i].frames.size();
}
}
return max;
}
void Part::CloneNewEndFrame()
{
std::vector<Frame> newFrames;
newFrames.resize(frames.size()+1);
for (int i = 0; i < frames.size(); i++)
{
newFrames[i] = frames[i];
}
newFrames[newFrames.size()-1] = frames[frames.size()-1];
frames = newFrames;
}
Entity* Part::CreateEntity(TextureSheet &textureSheet)
{
Texture *texture = textureSheet.GetTextureByName(name);
if (texture != NULL)
{
Entity *entity = new Entity();
Sprite *sprite = new Sprite(Assets::GetContentPath() + textureSheet.name + "/" + name + ".png");
sprite->position = (texture->registrationPoint * -1) + Vector2(sprite->width, sprite->height)*0.5f;
//sprite->position = texture->registrationPoint * -1;
entity->SetGraphic(sprite);
entity->SetLayer(-texture->zIndex); // layers are reversed compared to zIndex
//printf("size (%d, %d)", (int)sprite->width, (int)sprite->height);
//hackish
if (this->sprite == NULL)
{
this->sprite = sprite;
}
return entity;
}
else
{
Debug::Log("Error: Part could not CreateEntity, Part named: " + name + " not found in TextureSheet. Did you remember to load the TextureSheet?");
}
return NULL;
}
void Part::Update(float f)
{
int frame = int(f);
if (frame >= 0 && frame < frames.size())
{
// lerp!
if (frame < frames.size()-1)
{
float p = f - (float)frame;
//printf("frame: %d\nf: %f\n p: %f\n", frame, f, p);
entity->position = frames[frame].pos + (p * (frames[frame+1].pos - frames[frame].pos));
entity->scale = frames[frame].scale + (p * (frames[frame+1].scale - frames[frame].scale));
entity->rotation = frames[frame].rotation + (p * (frames[frame+1].rotation - frames[frame].rotation));
entity->color.a = frames[frame].alpha + (p * (frames[frame+1].alpha - frames[frame].alpha));
//printf("part: %s frame: %d pos(%d, %d) size(%d, %d) a: %f\n", name.c_str(), frame, (int)entity->position.x, (int)entity->position.y, (int)sprite->width, (int)sprite->height, entity->color.a);
}
else
{
ApplyFrameToEntity(frame, entity);
}
}
}
void Part::ApplyFrameToEntity(int frame, Entity *passed)
{
// if entity passed in isn't set
if (passed == NULL)
{
// set it to our entity pointer
passed = this->entity;
}
if (passed != NULL)
{
passed->position = frames[frame].pos;
passed->scale = frames[frame].scale;
passed->color.a = frames[frame].alpha;
passed->rotation = frames[frame].rotation;
}
else
{
Debug::Log("ApplyFrameToEntity... entity is NULL");
}
}
void TestScene::LoadAnimation(const std::string &filename)
{
// load the xml file
TiXmlDocument xml(filename);
bool isLoaded = xml.LoadFile();
if (isLoaded)
{
TiXmlElement* eAnimations = xml.FirstChildElement("Animations");
if (eAnimations)
{
TiXmlElement* eAnimation = eAnimations->FirstChildElement("Animation");
while (eAnimation)
{
Animation animation(XMLReadString(eAnimation, "name"), XMLReadInt(eAnimation, "frameCount"));
TiXmlElement* ePart = eAnimation->FirstChildElement("Part");
while (ePart)
{
Part part(ePart->Attribute("name"));
TiXmlElement* eFrame = ePart->FirstChildElement("Frame");
while (eFrame)
{
Frame frame;
frame.pos = Vector2(XMLReadFloat(eFrame, "x"), XMLReadFloat(eFrame, "y"));
if (eFrame->Attribute("scaleX"))
{
frame.scale.x = XMLReadFloat(eFrame, "scaleX");
}
if (eFrame->Attribute("scaleY"))
{
frame.scale.y = XMLReadFloat(eFrame, "scaleY");
}
if (eFrame->Attribute("alpha") != NULL)
{
frame.alpha = atof(eFrame->Attribute("alpha"));
}
if (eFrame->Attribute("rotation") != NULL)
{
frame.rotation = XMLReadFloat(eFrame, "rotation");
}
part.frames.push_back(frame);
eFrame = eFrame->NextSiblingElement("Frame");
}
animation.parts.push_back(part);
ePart = ePart->NextSiblingElement("Part");
}
animations.push_back(animation);
eAnimation = eAnimation->NextSiblingElement("Animation");
}
}
}
else
{
Debug::Log("Error: could not load animations from: " + filename + " - " + xml.ErrorDesc());
}
}
void TestScene::LoadTextureSheet(const std::string &filename)
{
// load the xml file
TiXmlDocument xml(filename);
bool isLoaded = xml.LoadFile();
if (isLoaded)
{
TiXmlElement* eTextures = xml.FirstChildElement("Textures");
if (eTextures)
{
TiXmlElement* eTextureSheet = eTextures->FirstChildElement("TextureSheet");
while (eTextureSheet)
{
textureSheet.name = XMLReadString(eTextureSheet, "name");
TiXmlElement* eTexture = eTextureSheet->FirstChildElement("Texture");
while (eTexture)
{
Texture texture;
texture.name = eTexture->Attribute("name");
texture.width = XMLReadInt(eTexture, "width");
texture.height = XMLReadInt(eTexture, "height");
texture.registrationPoint.x = XMLReadFloat(eTexture, "registrationPointX");
texture.registrationPoint.y = XMLReadFloat(eTexture, "registrationPointY");
if (eTexture->Attribute("zIndex") != NULL)
{
texture.zIndex = XMLReadInt(eTexture, "zIndex");
}
else
{
texture.zIndex = 0;
}
textureSheet.textures.push_back(texture);
eTexture = eTexture->NextSiblingElement("Texture");
}
std::sort(textureSheet.textures.begin(), textureSheet.textures.end());
eTextureSheet = eTextureSheet->NextSiblingElement("TextureSheet");
}
}
}
else
{
Debug::Log("Error: could not load textureSheet from: " + filename + " - " + xml.ErrorDesc());
}
}
//#define ANIM_MONOCLE_LOGO
#define ANIM_MONOCLE_MAN
//#define ANIM_TEST
void TestScene::Begin()
{
Scene::Begin();
Graphics::SetBackgroundColor(Color::black);
Assets::SetContentPath(Assets::GetContentPath()+"/Flash/");
const std::string cp = Assets::GetContentPath();
editPart = NULL;
selectedPartIndex = 0;
isRecording = false;
isPlaying = false;
currentAnimation = NULL;
isEditing = false;
#ifdef ANIM_MONOCLE_LOGO
LoadAnimation(cp+"animations-monoclelogo.xml");
LoadTextureSheet(cp+"sheets-monoclelogo.xml");
#endif
#ifdef ANIM_MONOCLE_MAN
LoadAnimation(cp+"animations-monocleman.xml");
LoadTextureSheet(cp+"sheets-monocleman.xml");
#endif
#ifdef ANIM_TEST
LoadAnimation(cp+"animations-test.xml");
#endif
eAnimation = new Entity();
eAnimation->position = Vector2(400,300);
Add(eAnimation);
InitAnimation(&animations[0], eAnimation);
Play(&animations[0], 30.0f);
// fudging:
//eAnimation->position.x += 40;
eAnimation->scale = Vector2(800.0f/640.0f, 600.0f/480.0f);
//editor
//Pause();
//isEditing = true;
//isRecording = true;
//Debug::showBounds = true;
}
void TestScene::SelectPrevPart()
{
int oldSelectedPartIndex = selectedPartIndex;
selectedPartIndex --;
if (selectedPartIndex < 0)
{
selectedPartIndex = 0;
}
if (selectedPartIndex != oldSelectedPartIndex)
{
DeleteOnionSkins();
CreateOnionSkins();
StoreBackupPartFrame();
}
editPart = ¤tAnimation->parts[selectedPartIndex];
}
void TestScene::SelectNextPart()
{
int oldSelectedPartIndex = selectedPartIndex;
selectedPartIndex ++;
if (selectedPartIndex > currentAnimation->parts.size()-1)
{
selectedPartIndex = currentAnimation->parts.size()-1;
}
if (selectedPartIndex != oldSelectedPartIndex)
{
DeleteOnionSkins();
CreateOnionSkins();
StoreBackupPartFrame();
}
editPart = ¤tAnimation->parts[selectedPartIndex];
}
void TestScene::UpdateFrameNumberDisplay()
{
if (currentAnimation)
printf("moved to frame: %d/%d\n", (int)(animationFrame), (int)currentAnimation->GetMaxFrames()-1);
else
printf("no animation\n");
}
Part *TestScene::GetPartForEntity(Entity *entity)
{
if (currentAnimation)
{
for (int i = 0; i < currentAnimation->parts.size(); i++)
{
if (currentAnimation->parts[i].entity == entity)
{
return ¤tAnimation->parts[i];
}
}
}
return NULL;
}
void TestScene::Update()
{
Scene::Update();
if (currentAnimation)
{
if (isPlaying)
{
UpdateAnimation(currentAnimation);
}
}
if (isEditing)
{
if (isPlaying)
{
if (Input::IsKeyPressed(KEY_SPACE))
{
Pause();
}
}
else if (!isPlaying)
{
if (Input::IsMouseButtonPressed(MOUSE_BUTTON_RIGHT))
{
Entity *clickedEntity = GetEntityAtPosition(Input::GetMousePosition(), SEARCH_RECURSIVE);
if (clickedEntity)
{
Debug::Log("clicked entity!");
editPart = GetPartForEntity(clickedEntity);
}
}
if (Input::IsKeyPressed(KEY_LEFTBRACKET))
{
SelectPrevPart();
}
if (Input::IsKeyPressed(KEY_RIGHTBRACKET))
{
SelectNextPart();
}
Entity *editEntity = NULL;
Sprite *editSprite = NULL;
if (editPart)
{
editEntity = editPart->entity;
editSprite = editPart->sprite;
}
if (Input::IsMouseButtonPressed(MOUSE_BUTTON_LEFT))
{
if (editEntity)
{
state = "moving";
offset = editEntity->position - Input::GetMousePosition();
}
}
if (Input::IsMouseButtonReleased(MOUSE_BUTTON_LEFT))
{
state = "";
}
if (state == "moving")
{
editEntity->position = Input::GetMousePosition() + offset;
}
Debug::selectedEntity = editEntity;
if (Input::IsKeyPressed(KEY_LEFT))
{
state = "";
GoPrevFrame();
UpdateFrameNumberDisplay();
}
if (Input::IsKeyPressed(KEY_RIGHT))
{
state = "";
GoNextFrame();
UpdateFrameNumberDisplay();
}
if (Input::IsKeyPressed(KEY_UP))
{
state = "";
CloneNewEndFrame();
UpdateFrameNumberDisplay();
}
const float moveSpeed = 40.0f;
float moveAmount = moveSpeed * Monocle::deltaTime;
const float rotateSpeed = 25.0f;
float rotateAmount = rotateSpeed * Monocle::deltaTime;
const float scaleSpeed = 0.5f;
float scaleAmount = scaleSpeed * Monocle::deltaTime;
if (Input::IsKeyHeld(KEY_LSHIFT))
{
moveAmount *= 4.0f;
rotateAmount *= 5.0f;
scaleAmount *= 4.0f;
}
if (editEntity)
{
if (Input::IsKeyHeld(KEY_A))
{
editEntity->position.x -= moveAmount;
}
if (Input::IsKeyHeld(KEY_D))
{
editEntity->position.x += moveAmount;
}
if (Input::IsKeyHeld(KEY_W))
{
editEntity->position.y -= moveAmount;
}
if (Input::IsKeyHeld(KEY_S))
{
editEntity->position.y += moveAmount;
}
if (Input::IsKeyHeld(KEY_Q))
{
editEntity->rotation -= rotateAmount;
}
if (Input::IsKeyHeld(KEY_E))
{
editEntity->rotation += rotateAmount;
}
// flip when rotation is in certain quadrants
if (Input::IsKeyHeld(KEY_J))
{
editEntity->scale.x -= scaleAmount;
}
if (Input::IsKeyHeld(KEY_L))
{
editEntity->scale.x += scaleAmount;
}
if (Input::IsKeyHeld(KEY_I))
{
editEntity->scale.y += scaleAmount;
}
if (Input::IsKeyHeld(KEY_K))
{
editEntity->scale.y -= scaleAmount;
}
}
// store part's frame when we switch frames/parts
// restore to that if hit a key
if (Input::IsKeyPressed(KEY_BACKSPACE))
{
RevertToBackupPartFrame();
}
// apply the previous frame data to this one
if (Input::IsKeyPressed(KEY_MINUS))
{
ApplyPrevPartFrame();
}
// apply the next frame data to this one
if (Input::IsKeyPressed(KEY_EQUALS))
{
ApplyNextPartFrame();
}
if (isRecording)
{
if (editPart)
{
int currentFrame = int(animationFrame);
editPart->frames[currentFrame].pos = editEntity->position;
editPart->frames[currentFrame].scale = editEntity->scale;
editPart->frames[currentFrame].rotation = editEntity->rotation;
}
}
if (Input::IsKeyPressed(KEY_SPACE))
{
Resume();
}
}
}
}
void TestScene::ApplyPrevPartFrame()
{
if (currentAnimation)
{
int currentFrame = int(animationFrame);
int prevFrame = SafeFrameRange(currentFrame-1);
///TODO: build functions to make this prettier
if (editPart)
{
editPart->frames[currentFrame] = editPart->frames[prevFrame];
editPart->ApplyFrameToEntity(currentFrame, editPart->entity);
}
}
}
void TestScene::ApplyNextPartFrame()
{
if (currentAnimation)
{
int currentFrame = int(animationFrame);
int nextFrame = SafeFrameRange(currentFrame+1);
///TODO: build functions to make this prettier
if (editPart)
{
editPart->frames[currentFrame] = editPart->frames[nextFrame];
editPart->ApplyFrameToEntity(currentFrame, editPart->entity);
}
}
}
void TestScene::RevertToBackupPartFrame()
{
Debug::Log("RevertToBackupPartFrame");
if (editPart)
{
int currentFrame = int(animationFrame);
editPart->frames[currentFrame] = backupPartFrame;
editPart->ApplyFrameToEntity(currentFrame);
}
}
void TestScene::StoreBackupPartFrame()
{
Debug::Log("StoreBackupPartFrame");
if (editPart)
{
backupPartFrame = editPart->frames[int(animationFrame)];
}
}
void TestScene::CloneNewEndFrame()
{
for (int i = 0; i < currentAnimation->parts.size(); i++)
{
currentAnimation->parts[i].CloneNewEndFrame();
}
GoNextFrame(currentAnimation->GetMaxFrames());
}
// create objects required to make the animation in the entity eParent
// if eParent is NULL, add to the scene instead
void TestScene::InitAnimation(Animation *animation, Entity *eParent)
{
for (int i = 0; i < animation->parts.size(); i++)
{
Entity *entity = animation->parts[i].CreateEntity(textureSheet);
if (entity)
{
animation->parts[i].entity = entity;
if (eParent)
eParent->Add(entity);
else
Add(entity);
}
}
}
void TestScene::Play(Animation *animation, float fps)
{
this->fps = fps;
currentAnimation = animation;
animationFrame = 0.0f;
isPlaying = true;
ApplyFrame();
}
void TestScene::Pause()
{
isPlaying = false;
}
void TestScene::Resume()
{
isPlaying = true;
}
void TestScene::GoNextFrame(int num)
{
DeleteOnionSkins();
animationFrame = int(animationFrame) + num;
if (animationFrame > currentAnimation->GetMaxFrames()-1)
{
animationFrame = currentAnimation->GetMaxFrames()-1;
}
ApplyFrame();
CreateOnionSkins();
StoreBackupPartFrame();
}
void TestScene::GoPrevFrame(int num)
{
DeleteOnionSkins();
animationFrame = int(animationFrame) - num;
if (animationFrame < 0)
{
animationFrame = 0;
}
ApplyFrame();
CreateOnionSkins();
StoreBackupPartFrame();
}
void TestScene::OffsetFramesBy(const Vector2 &offset)
{
for (int a = 0; a < animations.size(); a++)
{
for (int i = 0; i < animations[a].parts.size(); i++)
{
for (int j = 0; j < animations[a].parts[i].frames.size(); j++)
{
animations[a].parts[i].frames[j].pos += offset;
}
}
}
}
void TestScene::UpdateAnimation(Animation *animation)
{
if (isPlaying)
{
animationFrame += Monocle::deltaTime * fps;
if (animationFrame > animation->GetMaxFrames()-1)
{
animationFrame = animation->GetMaxFrames()-1;
Pause();
}
ApplyFrame();
}
}
void TestScene::ApplyFrame()
{
if (currentAnimation != NULL)
{
for (int i = 0; i < currentAnimation->parts.size(); i++)
{
currentAnimation->parts[i].Update(animationFrame);
}
}
}
void TestScene::CreateOnionSkins()
{
// current part
Part *editPart = ¤tAnimation->parts[selectedPartIndex];
if (editPart)
{
Entity *editEntity = editPart->entity;
Sprite *editSprite = editPart->sprite;
int currentFrame = int(animationFrame);
const int numFramesToPreview = 5;
for (int i = 0; i < numFramesToPreview; i++)
{
int prevFrame = SafeFrameRange(currentFrame - i);
int nextFrame = SafeFrameRange(currentFrame + i);
const float dyeP = 0.25f;
if (prevFrame != currentFrame)
{
Entity *entity = editPart->CreateEntity(textureSheet);
eAnimation->Add(entity);
editPart->ApplyFrameToEntity(prevFrame, entity);
onionSkins.push_back(entity);
float oldA = entity->color.a;
entity->color = entity->color * (1.0f-dyeP) + Color::blue * dyeP;
entity->color.a = oldA * (0.25f - 0.05f*i);
}
if (nextFrame != currentFrame)
{
// spawn part at next frame
Entity *entity = editPart->CreateEntity(textureSheet);
eAnimation->Add(entity);
editPart->ApplyFrameToEntity(nextFrame, entity);
onionSkins.push_back(entity);
float oldA = entity->color.a;
entity->color = entity->color * (1.0f-dyeP) + Color::red * dyeP;
entity->color.a = oldA * (0.25f - 0.05f*i);
}
}
}
}
void TestScene::DeleteOnionSkins()
{
for (std::vector<Entity*>::iterator i = onionSkins.begin(); i != onionSkins.end(); ++i)
{
//HACK: leak memory like an IDIOT.
eAnimation->Remove((*i)); // <- need to enqueue for deletion here
// for now delete right away, later (after changes made to Remove) this probably won't work
delete *i;
}
onionSkins.clear();
}
int TestScene::SafeFrameRange(int frame)
{
if (currentAnimation)
{
if (frame > currentAnimation->GetMaxFrames()-1)
frame = currentAnimation->GetMaxFrames()-1;
if (frame < 0)
return 0;
}
return frame;
}
}
| [
"[email protected]"
]
| [
[
[
1,
797
]
]
]
|
a14db054fce1d3dd29d4be313a7c5f7ecd2c2a4a | c86f787916e295d20607cbffc13c524018888a0f | /tp1/CD/ejercicio2/src/Camion.h | 8eb7c55f84ceb4677187204aadf709bcb72404b1 | []
| no_license | federicoemartinez/algo3-2008 | 0039a4bc6d83ab8005fa2169b919e6c03524bad5 | 3b04cbea4583d76d7a97f2aee72493b4b571a77b | refs/heads/master | 2020-06-05T05:56:20.127248 | 2008-08-04T04:59:32 | 2008-08-04T04:59:32 | 32,117,945 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 363 | h | #ifndef _camion_h
#define _camion_h
#include <list>
#include <iostream>
#include "Cosa.h"
class Camion {
public:
unsigned cantCosas;
unsigned capacidad;
Cosa* cosas;
Camion(Cosa* cs, unsigned cap,unsigned cant);
friend std::ostream& operator<< (ostream&, const Camion&);
};
#endif /*_camion_h*/
| [
"federicoemartinez@bfd18afd-6e49-0410-abef-09437ef2666c"
]
| [
[
[
1,
19
]
]
]
|
3490f40e27ed514d6c67d6441d525f4032bbd817 | 1493997bb11718d3c18c6632b6dd010535f742f5 | /tests/microsoft/cardgame_design_test.cpp | f675b46f1ccd64dee28018d3c2378a12bea300c6 | []
| no_license | kovrov/scrap | cd0cf2c98a62d5af6e4206a2cab7bb8e4560b168 | b0f38d95dd4acd89c832188265dece4d91383bbb | refs/heads/master | 2021-01-20T12:21:34.742007 | 2010-01-12T19:53:23 | 2010-01-12T19:53:23 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 4,199 | cpp | /* Q:
Come up with a suitable object oriented design for designing a set of
"playing card" games. Assume standard deck of cards; multiple people
participating in games; and a neutral dealer.
Note: This is a design question and is meant to be little vague. Use
your imagination and write about 1/2 to 1 page (avoid too much detail)
of ideas on class design, hierarchy and some class variables. There
is no right or wrong answer and you will be evaluated for your
imagination and object oriented concepts.
*/
/* A:
I would go with set of game entities like Card, Player, Dealer(?) classes.
There is no use of heirarchy(-ies) at this point, except perhaps to
refactor some common properties or interfaces (eg, Players and dealer could
have somthing common). But basically they are POD types (structs)
The most important class is Game - here incapsulated game logic and state
(of specific game, BlackJack, etc..), providing convinient interface.
Underlying mechanism would be a state machine (generic) and it's config
(set of states, tansitions etc. for a specific game). Reason for using
FSM is that all board games esetualy are state machines. But this is
rather implementation details.
*/
struct Card
{
suit /* HEARTS, DIAMONDS, CLUBS, SPADES */
rank /* ACE, KING, QUEEN, JACK, 10 - 2? */
};
/* this is esentially a wrapper for a handle to the player of particular hame
handle is generic to all games, so the Player class/struct.
Other than handle it may hold methadata not strictly relevant for
specific game, such as credits/money, etc.. which may or may not affect
game logic of a specific game */
struct Player
{
handle // is unique for game instance, and set by game instance
/* why use handle to identify player? because Player instance memory address may change. */
credits //money
};
/* Honestly I don't know if there is a point to have a Dealer class.
If there is NO game type where dealer have to decide anything (not just draw
cards if player asks) - there is no need for the dealer class. Because all
the game "logic" (rules) and state are elswere (in *Game classes). I this
case the real dealer and (with the desk with cards) is real world card game
application analog.
I for game type where dealer may make any decitions, there would be
a game-specific AI (or human) dealer implementation. This could be useful
to decouple AI (human/network interface) implementation from game logic.
Again, if there is any. */
// Specific game class. For sake of example let it be a BlackJack game.
// BlackJackGame probably would be derived from a CardGame interface (if we
// have more than one game in one application)
class BlackJackGame : public CardGame
{
// game specific methos if called in wrong state will throw
/* depending on how players join and leaving game there will be
corresponding methonds to bind player handles to Player instances. */
addPlayer(Player* player); // uses handle
// we need some way to acually play game
placeBet(Player* player); // uses handle and credits/money
takeCard(Player* player); // uses handle and affect game state
// etc...
/* why not move (some of) this methods to Player class?
because than we'd have lot of game specific Player classes
hard coupled to *Game classes implementations. */
// we may need to introspect game in progress.
/* these methods may or may not be needed - if for exaplme we have some
sort of callbacks for game state changes, application could track
this information on its own */
getState(); // PLACING_BETS, WAITING_FOR_PLAYER_TO...
getPlayers(); // return array of player instances (handles)
playerCards(Player* player); // what cards specific player holds
dealerCards() // see rationale for (not)having dealer instances.
wichPlayersTurn() // to see who has to do something right now.
// etc...
};
/* interface for application to handle any of games in generic way,
eg. abort game on application exit. */
class CardGame
{
abort() // why not just delete istance and have a cleanup in destructor? I downt know =) need more use cases
save() // (?)
// etc..
};
| [
"[email protected]"
]
| [
[
[
1,
100
]
]
]
|
bc0c06bb45497e9afaa67adf9a434bb45f34d322 | bd89d3607e32d7ebb8898f5e2d3445d524010850 | /adaptationlayer/tsy/simatktsy_dll/src/satmesshandler.cpp | 3f7b895197297ced2f0326ab05dfe69fcd6e960d | []
| no_license | wannaphong/symbian-incubation-projects.fcl-modemadaptation | 9b9c61ba714ca8a786db01afda8f5a066420c0db | 0e6894da14b3b096cffe0182cedecc9b6dac7b8d | refs/heads/master | 2021-05-30T05:09:10.980036 | 2010-10-19T10:16:20 | 2010-10-19T10:16:20 | null | 0 | 0 | null | null | null | null | WINDOWS-1250 | C++ | false | false | 211,275 | cpp | /*
* Copyright (c) 2007-2010 Nokia Corporation and/or its subsidiary(-ies).
* All rights reserved.
* This component and the accompanying materials are made available
* under the terms of the License "Eclipse Public License v1.0"
* which accompanies this distribution, and is available
* at the URL "http://www.eclipse.org/legal/epl-v10.html".
*
* Initial Contributors:
* Nokia Corporation - initial contribution.
*
* Contributors:
*
* Description:
*
*/
// INCLUDE FILES
#include "satmesshandler.h" // sat message handler class
#include "satmessaging.h" // sat messaging class
#include "sattimer.h" // sat timer class
#include "sateventdownload.h" // sat event download class
#include "satdatadownload.h" // sat data download class
#include "saticon.h" // sat icon class
#include "satmosmsctrl.h" // sat mo sms control class
#include "satnotifications.h" // sat notifications class
#include "ber_tlv.h" // sat ber-tlv classes
#include "satutil.h" // sat utility class
#include "cmmphonetsender.h" // phonet sender
#include "terminalprofile.h" // terminal profile
#include "satflightmodestatus.h"// flight mode status
#include <pn_const.h> // server id constants
#include <tisi.h> // isi message
#include <ss_wmisi.h> // ss server
#include <infoisi.h> // info server
#include <net_modemisi.h> // net server
#include <gssisi.h> // gss server
#include <call_modemisi.h> // Call Modem server
#include <smsisi.h> // sms server
#include <uiccisi.h> // UICC server
#include <gpdsisi.h> // GPDS server
#include <call_sharedisi.h>
#include <info_sharedisi.h>
#include "OstTraceDefinitions.h"
#ifdef OST_TRACE_COMPILER_IN_USE
#include "satmesshandlerTraces.h"
#endif
// CONSTANTS
const TUint8 KOneByteLengthLimit = 0x7F;
// Maximum value for get input string
const TUint8 KGetInputStringMaxSize = 0xEF;
// No transaction ongoing
const TInt KNoTransactionOngoing = -1;
// Time zone not available
const TUint8 KTimeZoneNotAvailable = 0xFF;
// Access Technology unknown
const TUint8 KAccTechUnknown = 0xFF;
// Maximum polling interval of legacy phones
const TUint8 KMaxLegacyPollInterval = 0x19; // 25 decimal
// Size of one clut entry in bytes
const TUint16 KClutEntrySize = 3;
// Padding bytes for UICC messages
const TUint8 KUiccPadding = 0x00;
// Size of terminal profile subblock
const TUint8 KSizeOfTerminalProfileSb = 40;
// Offset of UICC_APPL_CMD_REQ message for adding subblocks
const TUint8 KUiccApplCmdReqOffset(
ISI_HEADER_SIZE + SIZE_UICC_APPL_CMD_REQ );
// Size of UICC_SB_APPL_PATH
const TUint8 KUiccSbApplPathSize(
SIZE_UICC_SB_APPL_PATH + KUiccFilePathLength );
// UICC file IDs
const TUint16 KUiccMasterFileId( 0x3F00 );
const TUint16 KUiccElemFileServiceTable( 0x6F38 );
const TUint16 KUiccDedicatedFileTelecom( 0x7F10 );
const TUint16 KUiccDedicatedFileGraphics( 0x5F50 );
const TUint16 KUiccElemFileImg( 0x4F20 );
const TUint8 KUiccSfiServiceTable( 4 );
// Number of subblocks in UICC_APPL_CMD_REQ
const TUint8 KNumOfSbsInUiccApplCmdReq( 3 );
// Max size of UICC_SB_TERMINAL_PROFILE
const TUint16 KMaxSizeOfUiccSbTerminalResponse( 264 );
// Length of device identity TLV data object
const TUint8 KTlvDeviceIdentityLength( 2 );
// Max length of UICC_SB_AID
const TUint16 KMaxLengthUiccSbAid( 260 );
// Elementary file ID length
const TUint8 KUiccFileIdLength( 2 );
// Maximum size of envelope
const TUint16 KMaxSizeOfEnvelope( 256 );
// ==================== MEMBER FUNCTIONS ====================================
// -----------------------------------------------------------------------------
// CSatMessHandler::CSatMessHandler
// C++ default constructor can NOT contain any code, that
// might leave.
// -----------------------------------------------------------------------------
//
CSatMessHandler::CSatMessHandler
(
CTsySatMessaging* aTsySatMessaging,
CMmPhoNetSender* aPnSend
)
:
iTsySatMessaging( aTsySatMessaging ),
iPnSend( aPnSend )
{
OstTrace0( TRACE_NORMAL, CSATMESSHANDLER_CSATMESSHANDLER_TD, "CSatMessHandler::CSatMessHandler" );
// >= 0 if there is ongoing transaction
iTerminalRespTraId = KNoTransactionOngoing;
iGetIconSimReadFieldTraId = KNoTransactionOngoing;
iDataDownloadSimReadFieldTraId = KNoTransactionOngoing;
iCbRoutingReqTraId = KNoTransactionOngoing;
iCardId = KZero;
iImeiAvailable = EFalse;
iImeiSvAvailable = EFalse;
// By default, there's no need to request routing from SMS server
iSmsCbRoutingComplete = ETrue;
iRefreshRequestIsOn = EFalse;
iTimingAdvance = GSS_TIMING_ADVANCE_NOT_AVAILABLE;
iTaStatus = GSS_TIMING_ADVANCE_NOT_VALID;
iTimeZone = KTimeZoneNotAvailable;
iSimServerObjectId = KZero;
iCurrentAccTech = KAccTechUnknown;
// Set polling status to the use of the default value (25 sec.)
iPollingOff = ETrue;
iSsStatus = ENotBusy;
// No long poll interval requests yet
iLongPollIntervalReq = EFalse;
#ifdef INFO_PP_ATK_MO_SM_CONTROL
// MO SMS support not yet read from product profile
iMoSmsSupportedInPp = EFalse;
#endif // INFO_PP_ATK_MO_SM_CONTROL
#ifdef INFO_PP_ENHANCED_NETWORK_SELECTION
// ENS support not yet read from product profile
iEnsSupportedInPp = EFalse;
// SET UP EVENT LIST TR not yet sent
iSetUpEventListTrSent = EFalse;
#endif // INFO_PP_ENHANCED_NETWORK_SELECTION
// Init location info structure
iLocInfo.iOperatorCode.FillZ( iLocInfo.iOperatorCode.MaxLength() );
iLocInfo.iLac.FillZ( iLocInfo.iLac.MaxLength() );
iLocInfo.iCellId.FillZ( iLocInfo.iCellId.MaxLength() );
iLocInfo.iRegStatus = NET_NO_COVERAGE;
// Init IMEI of the ME
iIMEI.FillZ( 16 ); // KSerialNumberLength + 1
// Clear NMR (Network Measurement result)
iNMR.Zero();
// Clear BCCH channel list
iBCCHChannelList.Zero();
// Clear UTRAN measurement result
iUtranNMR.Set( KNullDesC8 );
// ME is not yet in service during startup
iPreviousRegistrationStatus = NET_REG_STATUS_NOSERV_SEARCHING;
// INFO_PP_SIM_OLD_POLL_INTERVAL flag not read yet
iOldPollIntervalSupportedInPp = ETrue;
}
// -----------------------------------------------------------------------------
// CSatMessHandler::~CSatMessHandler
// Destructor.
// -----------------------------------------------------------------------------
//
CSatMessHandler::~CSatMessHandler()
{
OstTrace0( TRACE_NORMAL, DUP1_CSATMESSHANDLER_CSATMESSHANDLER_TD, "CSatMessHandler::~CSatMessHandler" );
}
// -----------------------------------------------------------------------------
// CSatMessHandler::NewL
// Two-phased constructor.
// -----------------------------------------------------------------------------
//
CSatMessHandler* CSatMessHandler::NewL
(
CTsySatMessaging* aTsySatMessaging,
CMmPhoNetSender* aPnSend
)
{
OstTrace0( TRACE_NORMAL, CSATMESSHANDLER_NEWL_TD, "CSatMessHandler::NewL" );
TFLOGSTRING("TSY:CSatMessHandler::NewL");
CSatMessHandler* self = new( ELeave ) CSatMessHandler( aTsySatMessaging,
aPnSend );
CleanupStack::PushL( self );
self->ConstructL();
CleanupStack::Pop( self );
return self;
}
// -----------------------------------------------------------------------------
// CSatMessHandler::ConstructL
// Symbian 2nd phase constructor can leave
// -----------------------------------------------------------------------------
//
void CSatMessHandler::ConstructL()
{
TFLOGSTRING("TSY:CSatMessHandler::ConstructL");
OstTrace0( TRACE_NORMAL, CSATMESSHANDLER_CONSTRUCTL_TD, "CSatMessHandler::ConstructL" );
// This flag is set to 'true' when indication ESatUsatClientReadyIndication
// is received from SAT server. CAT can be enabled when the state of this
// flag is 'true' and also UICC server is ready.
iSatReady = EFalse;
// Application ID will be set when UICC_APPLICATION_IND is received
iApplicationId = 0xFF;
// UICC client ID will be set when UICC_APPLICATION_RESP is received
iUiccClientId = 0;
// Terminal profile status flag is set 'true' when terminal profile has been
// sent to prevent CAT enabling request to be sent before terminal profile
iTerminalProfileSent = EFalse;
// Card type is not known yet
iCardType = UICC_CARD_TYPE_UNKNOWN;
// Application file id is initialize to 'FFFF'
TBuf8<2> unknownFileId;
unknownFileId.Append( 0xFF );
unknownFileId.Append( 0xFF );
iApplFileId.Copy( unknownFileId );
iPollingInterval = KDefaultPollInterval;
iImageCodingScheme = KBlackAndWhite;
}
// -----------------------------------------------------------------------------
// CSatMessHandler::ProactiveProcedureMessageReceivedL
// Called SatMessHandler::ReceivedL, handles Event download,
// Call control, Data Download and MO-SMS Control related messages
// -----------------------------------------------------------------------------
//
void CSatMessHandler::ProactiveProcedureMessageReceivedL
(
const TIsiReceiveC& aIsiMessage
)
{
OstTrace0( TRACE_NORMAL, CSATMESSHANDLER_PROACTIVEPROCEDUREMESSAGERECEIVEDL_TD, "CSatMessHandler::ProactiveProcedureMessageReceivedL" );
TFLOGSTRING("TSY:CSatMessHandler::ProactiveProcedureMessageReceivedL");
// handle event download and related messages
iTsySatMessaging->EventDownloadReceived( aIsiMessage );
// handle call control and releated messages
iTsySatMessaging->CallControlReceivedL( aIsiMessage );
// handle Data Download and related messages
iTsySatMessaging->DataDownloadReceivedL( aIsiMessage );
// handle MO-SMS Control related messages
iTsySatMessaging->MoSmsControlReceivedL( aIsiMessage );
}
// -----------------------------------------------------------------------------
// CSatMessHandler::NetServerMessageReceived
// Called from SatMessHandler::ReceivedL, handles Net Server related messages
// -----------------------------------------------------------------------------
//
void CSatMessHandler::NetServerMessageReceived
(
const TIsiReceiveC& aIsiMessage // ISI message
)
{
OstTrace0( TRACE_NORMAL, CSATMESSHANDLER_NETSERVERMESSAGERECEIVED_TD, "CSatMessHandler::NetServerMessageReceived" );
TFLOGSTRING("TSY:CSatMessHandler::NetServerMessageReceived");
TInt messageId( aIsiMessage.Get8bit( ISI_HEADER_OFFSET_MESSAGEID ) );
switch ( messageId )
{
case NET_CELL_INFO_IND:
{
StoreNetServiceStatus( aIsiMessage );
// If SMS CB routing is still pending, regenerate routing request.
// This might be the case if CS was inactive or SIM is not ready
// during the first request.
if ( !iSmsCbRoutingComplete )
{
TFLOGSTRING("TSY:CSatMessHandler::NetServerMessageReceived \
Sending delayed SMS CB routing request.");
OstTrace0( TRACE_NORMAL, DUP1_CSATMESSHANDLER_NETSERVERMESSAGERECEIVED_TD, "CSatMessHandler::NetServerMessageReceived Sending delayed SMS CB routing request." );
SmsCbRoutingReq(
iTsySatMessaging->GetTransactionId(), SMS_ROUTING_SET );
}
break;
}
case NET_NEIGHBOUR_CELLS_RESP:
{
NetNeighbourCellResp( aIsiMessage );
break;
}
case NET_CELL_INFO_GET_RESP:
{
NetCellInfoGetResp( aIsiMessage );
break;
}
case NET_TIME_IND:
{
NetTimeInd( aIsiMessage );
break;
}
case NET_RAT_IND:
{
NetRatInd( aIsiMessage );
break;
}
default:
{
// Do nothing
break;
}
}
}
// -----------------------------------------------------------------------------
// CSatMessHandler::PhoneInfoMessageReceivedL
// Called from SatMessHandler::ReceivedL, handles Phone Info related messages
// -----------------------------------------------------------------------------
//
/*void CSatMessHandler::PhoneInfoMessageReceivedL
(
const TIsiReceiveC& aIsiMessage // ISI message
)
{
OstTrace0( TRACE_NORMAL, CSATMESSHANDLER_PHONEINFOMESSAGERECEIVEDL_TD, "CSatMessHandler::PhoneInfoMessageReceivedL" );
TFLOGSTRING("TSY:CSatMessHandler::PhoneInfoMessageReceivedL");
TInt messageId( aIsiMessage.Get8bit( ISI_HEADER_OFFSET_MESSAGEID ) );
switch ( messageId )
{
case INFO_SERIAL_NUMBER_READ_RESP:
{
InfoSerialNumberReadResp( aIsiMessage );
break;
}
case INFO_PP_READ_RESP:
{
InfoPpReadRespL( aIsiMessage );
break;
}
default:
{
// do nothing
break;
}
}
}*/
// -----------------------------------------------------------------------------
// CSatMessHandler::UiccServerMessageReceived
// Called from SatMessHandler::ReceivedL, handles UICC Server messages
// -----------------------------------------------------------------------------
//
TBool CSatMessHandler::UiccServerMessageReceivedL(
const TIsiReceiveC& aIsiMessage )
{
TUint8 messageId( aIsiMessage.Get8bit( ISI_HEADER_OFFSET_MESSAGEID ) );
OstTraceExt1( TRACE_NORMAL, DUP3_CSATMESSHANDLER_UICCSERVERMESSAGERECEIVEDL_TD, "CSatMessHandler::UiccServerMessageReceived;messageId=%hhu", messageId );
TFLOGSTRING2("TSY:CSatMessHandler::UiccServerMessageReceivedL, message ID: %d", messageId );
TBool handled( EFalse );
switch ( messageId )
{
case UICC_CAT_IND:
{
UiccCatIndL( aIsiMessage );
break;
}
case UICC_CAT_RESP:
{
TUint8 serviceType(
aIsiMessage.Get8bit(
ISI_HEADER_SIZE + UICC_CAT_RESP_OFFSET_SERVICETYPE ) );
TUint8 status(
aIsiMessage.Get8bit(
ISI_HEADER_SIZE + UICC_CAT_RESP_OFFSET_STATUS ) );
TFLOGSTRING3("TSY:CSatMessHandler:: KUiccCatResp: service type %d, status %d", serviceType, status);
OstTraceExt2( TRACE_NORMAL, DUP2_CSATMESSHANDLER_UICCSERVERMESSAGERECEIVEDL_TD, "CSatMessHandler::KUiccCatResp;serviceType=%hhu;status=%hhu", serviceType, status );
// If terminal profile was sent succesfully and SAT is ready,
// start fetching proactive commands
if ( UICC_CAT_TERMINAL_PROFILE == serviceType &&
UICC_STATUS_OK == status )
{
// If SAT is not ready, CAT enable request cannot be sent yet.
// When indication of SAT ready is received by satmessaging,
// CAT enable request is sent if this flag is set to 'true'.
iTerminalProfileSent = ETrue;
// Enable or disable proactive command fetching depending on
// flight mode status
if ( iSatReady )
{
// Get instance of CSatFlightModeStatus for flight mode
// status
CSatFlightModeStatus* satFlightModeStatus(
iTsySatMessaging->GetSatFlightModeStatus() );
if ( ! satFlightModeStatus->FlightModeStatusValue() )
{
UiccCatReq( UICC_CAT_ENABLE );
}
else
{
UiccCatReq( UICC_CAT_DISABLE );
}
}
}
// Response for refresh command
else if ( UICC_CAT_REFRESH == serviceType )
{
RefreshResultL( status );
}
// Response for polling set command
else if ( UICC_CAT_POLLING_SET == serviceType )
{
SetPollingResult(
status,
aIsiMessage.Get8bit( ISI_HEADER_OFFSET_TRANSID ),
iPollingInterval );
}
// Response for envelope
else if ( UICC_CAT_ENVELOPE == serviceType )
{
handled = UiccCatRespEnvelope( aIsiMessage );
}
// Response for terminal response
else if ( UICC_CAT_TERMINAL_RESPONSE == serviceType )
{
handled = UiccCatRespTerminalResponse( aIsiMessage );
}
break;
}
case UICC_APPLICATION_RESP:
{
TUint uiccSbClientOffset( 0 );
if ( KErrNone == aIsiMessage.FindSubBlockOffsetById(
ISI_HEADER_SIZE + SIZE_UICC_APPLICATION_RESP,
UICC_SB_CLIENT,
EIsiSubBlockTypeId16Len16,
uiccSbClientOffset ) )
{
iUiccClientId = aIsiMessage.Get8bit(
uiccSbClientOffset + UICC_SB_CLIENT_OFFSET_CLIENTID );
}
break;
}
case UICC_APPLICATION_IND:
{
// Application ID is needed when reading data from UICC
iApplicationId = aIsiMessage.Get8bit(
ISI_HEADER_SIZE + UICC_APPLICATION_IND_OFFSET_APPLID );
// Access to UICC files is possible when application is active
TUint8 serviceType( aIsiMessage.Get8bit(
ISI_HEADER_SIZE + UICC_APPLICATION_IND_OFFSET_SERVICETYPE ) );
if ( UICC_APPL_ACTIVATED == serviceType )
{
TInt ret( KErrNone );
if ( UICC_CARD_TYPE_UICC == iCardType )
{
// USIM: Read SMS-PP DD, Call Control and MO-SMS control from byte 4.
ret = UiccReadServiceTableReq( KUiccTrIdServiceTableByte4, 3 );
User::LeaveIfError( ret );
// USIM: Read call control GPRS from byte 7
ret = UiccReadServiceTableReq( KUiccTrIdServiceTableByte7, 6 );
User::LeaveIfError( ret );
}
else if ( UICC_CARD_TYPE_ICC == iCardType )
{
// SIM: Read MO-SMS control from byte 10
ret = UiccReadServiceTableReq( KUiccTrIdServiceTableByte10, 9 );
User::LeaveIfError( ret );
// SIM: Read SMS-PP DD and Call Control from byte 7
ret = UiccReadServiceTableReq( KUiccTrIdServiceTableByte7, 6 );
User::LeaveIfError( ret );
// SIM: Read Call control in USSD from byte 11. This is supported only in SIM
ret = UiccReadServiceTableReq( KUiccTrIdServiceTableByte11, 10 );
User::LeaveIfError( ret );
}
}
break;
}
case UICC_APPL_CMD_RESP:
{
UiccApplCmdResp( aIsiMessage );
}
} // End of switch ( messageId )
return handled;
}
// -----------------------------------------------------------------------------
// CSatMessHandler::SmsServerMessageReceived
// Called from SatMessHandler::ReceivedL, handles SMS Server messages
// -----------------------------------------------------------------------------
//
void CSatMessHandler::SmsServerMessageReceived
(
const TIsiReceiveC& aIsiMessage // ISI message from SMS server
)
{
OstTrace0( TRACE_NORMAL, CSATMESSHANDLER_SMSSERVERMESSAGERECEIVED_TD, "CSatMessHandler::SmsServerMessageReceived" );
TFLOGSTRING("TSY:CSatMessHandler::SmsServerMessageReceived");
TInt messageId( aIsiMessage.Get8bit( ISI_HEADER_OFFSET_MESSAGEID ) );
switch ( messageId )
{
case SMS_CB_ROUTING_RESP:
{
SmsCbRoutingResp( aIsiMessage );
break;
}
case SMS_RESOURCE_CONF_IND:
{
SmsResourceConfInd( aIsiMessage );
break;
}
case SMS_RESOURCE_CONF_RESP:
{
// Take a log because result is always ok
TFLOGSTRING("TSY:CSatMoSmsCtrl::SmsResourceConfRespReceived: Response for Resource confoguration Req, Receive response from SMS server");
OstTrace0( TRACE_NORMAL, DUP1_CSATMOSMSCTRL_SMSRESOURCECONFRESPRECEIVED_TD, "CSatMoSmsCtrl::SmsResourceRespReceived: Response for Resource Configuration Req, Receive response from SMS server" );
break;
}
default:
// do nothing
break;
}
}
// -----------------------------------------------------------------------------
// CSatMessHandler::SsServerMessageReceived
// Called from SatMessHandler::ReceivedL, handles SS Server messages
// -----------------------------------------------------------------------------
//
void CSatMessHandler::SsServerMessageReceived
(
const TIsiReceiveC& aIsiMessage // ISI message
)
{
OstTrace0( TRACE_NORMAL, CSATMESSHANDLER_SSSERVERMESSAGERECEIVED_TD, "CSatMessHandler::SsServerMessageReceived" );
TFLOGSTRING("TSY:CSatMessHandler::SsServerMessageReceived");
TInt messageId( aIsiMessage.Get8bit( ISI_HEADER_OFFSET_MESSAGEID ) );
switch ( messageId )
{
case SS_STATUS_IND:
{
SsStatusInd( aIsiMessage );
break;
}
default:
// do nothing
break;
}
}
// -----------------------------------------------------------------------------
// CSatMessHandler::GsmStackServerMessageReceived
// Called from SatMessHandler::ReceivedL, handles GSM Stack Server messages
// -----------------------------------------------------------------------------
//
void CSatMessHandler::GsmStackServerMessageReceived
(
const TIsiReceiveC& aIsiMessage // ISI message
)
{
OstTrace0( TRACE_NORMAL, CSATMESSHANDLER_GSMSTACKSERVERMESSAGERECEIVED_TD, "CSatMessHandler::GsmStackServerMessageReceived" );
TFLOGSTRING("TSY:CSatMessHandler::GsmStackServerMessageReceived");
switch ( aIsiMessage.Get8bit( ISI_HEADER_OFFSET_MESSAGEID ) )
{
case GSS_CS_SERVICE_RESP:
{
GssCsServiceResp( aIsiMessage );
break;
}
case GSS_CS_SERVICE_FAIL_RESP:
{
GssCsServiceFailResp( aIsiMessage );
break;
}
default:
{
// do nothing
break;
}
}
}
// -----------------------------------------------------------------------------
// CSatMessHandler::DisplayTextTerminalResp
// Constructs DisplayText specific part of terminal
// response and calls SendTerminalResponse to send the terminal response.
// -----------------------------------------------------------------------------
//
TInt CSatMessHandler::DisplayTextTerminalResp
(
TUint8 aTransId, // Transaction id
TDes8& aCommandDetails, // PCmd number
TUint8 aGeneralResult, // General Result
TUint8 aAdditionalInfo // Additional info
)
{
OstTrace0( TRACE_NORMAL, CSATMESSHANDLER_DISPLAYTEXTTERMINALRESP_TD, "CSatMessHandler::DisplayTextTerminalResp" );
TFLOGSTRING("TSY:CSatMessHandler::DisplayTextTerminalResp");
TTlv tlvSpecificData;
// Create General Result TLV here
tlvSpecificData.AddTag( KTlvResultTag );
// General result
tlvSpecificData.AddByte( aGeneralResult );
if ( KMeCurrentlyUnableToProcessCommand == aGeneralResult )
{
tlvSpecificData.AddByte( aAdditionalInfo );
}
return UiccCatReqTerminalResponse(
aCommandDetails,
tlvSpecificData.GetDataWithoutTopLevelTag(),
aTransId );
}
// -----------------------------------------------------------------------------
// CSatMessHandler::GetInkeyTerminalResp
// Constructs GetInkey specific part of terminal
// response and calls SendTerminalResponse to send the terminal response.
// -----------------------------------------------------------------------------
//
TInt CSatMessHandler::GetInkeyTerminalResp
(
const TUint8 aTransId, // Transaction id
const TDes8& aCommandDetails, // PCmd number
const RSat::TGetInkeyRspV2& aRsp // Response packet from Etel
)
{
OstTrace0( TRACE_NORMAL, CSATMESSHANDLER_GETINKEYTERMINALRESP_TD, "CSatMessHandler::GetInkeyTerminalResp" );
TFLOGSTRING("TSY:CSatMessHandler::GetInkeyTerminalRespL");
TTlv tlvSpecificData;
//General result
TUint8 result( aRsp.iGeneralResult );
tlvSpecificData.AddTag( KTlvResultTag );
tlvSpecificData.AddByte( result );
if ( CommandPerformedSuccessfully( result ) )
{
TUint8 dcs( K8BitDCS ); // Default
TBuf8<2> character; // Unicode has 2 bytes
// Text String Tlv
if ( NULL != aRsp.iAdditionalInfo.Length() )
{
// Response contain on one character
TPtrC16 unicodeChar( aRsp.iAdditionalInfo.Mid( 0, 1 ) );
switch ( aRsp.iRspFormat )
{
case RSat::ECharUcs2Alphabet:
{
dcs = KUCS2DCS;
TIsiUtility::CopyToBigEndian( unicodeChar, character );
break;
}
case RSat::EDigitOnly:
case RSat::ECharSmsDefaultAlphabet:
case RSat::EYesNo:
default:
{
// Dcs already set to K8BitDCS
TSatUtility::ConvertUnicode16ToSms7(
character, unicodeChar );
break;
}
}
}
else
{
// Just in case
dcs = K8BitDCS;
character.Copy( NULL );
}
tlvSpecificData.AddTag( KTlvTextStringTag );
tlvSpecificData.AddByte( dcs );
tlvSpecificData.AddData( character );
}
else if ( RSat::KNoAdditionalInfo != aRsp.iInfoType )
{
// Command not successfull
if ( NULL != aRsp.iAdditionalInfo.Length() )
{
tlvSpecificData.AddByte( TUint8 ( aRsp.iAdditionalInfo[0] ) );
}
}
else
{
// Command was not successful but additional info was not provided
}
// Append Duration TLV, if provided
TInt tlvTimeUnit( KErrNotFound );
switch ( aRsp.iDuration.iTimeUnit )
{
case RSat::EMinutes:
{
tlvTimeUnit = KMinutes;
break;
}
case RSat::ESeconds:
{
tlvTimeUnit = KSeconds;
break;
}
case RSat::ETenthsOfSeconds:
{
tlvTimeUnit = KTenthsOfSeconds;
break;
}
case RSat::ETimeUnitNotSet:
case RSat::ENoDurationAvailable:
default:
{
// Duration is not added to terminal response
break;
}
}
if ( KErrNotFound != tlvTimeUnit )
{
// Duration provided. Append it to terminal response.
tlvSpecificData.AddTag( KTlvDurationTag );
tlvSpecificData.AddByte( tlvTimeUnit );
tlvSpecificData.AddByte( aRsp.iDuration.iNumOfUnits );
}
return UiccCatReqTerminalResponse(
aCommandDetails,
tlvSpecificData.GetDataWithoutTopLevelTag(),
aTransId );
}
// -----------------------------------------------------------------------------
// CSatMessHandler::GetInputTerminalResp
// Constructs Get Input specific part of terminal
// response and calls SendTerminalResponse to send the terminal response.
// -----------------------------------------------------------------------------
//
TInt CSatMessHandler::GetInputTerminalResp
(
TUint8 aTransId, // Transaction id
TDes8& aCommandDetails, // Command details tlv
TUint8 aGeneralResult, // General result
TUint8 aAdditionalInfo, // Additional info
TDesC16& aTextString, // Response string
TUint8 aDataCodingScheme // Coding scheme
)
{
OstTrace0( TRACE_NORMAL, CSATMESSHANDLER_GETINPUTTERMINALRESP_TD, "CSatMessHandler::GetInputTerminalResp" );
TFLOGSTRING("TSY:CSatMessHandler::GetInputTerminalResp");
TTlv tlvSpecificData;
TBuf8<KGetInputStringMaxSize> string;
tlvSpecificData.AddTag( KTlvResultTag );
tlvSpecificData.AddByte( aGeneralResult );
if ( RSat::KMeUnableToProcessCmd == aGeneralResult )
{
tlvSpecificData.AddByte( aAdditionalInfo );
}
if ( CommandPerformedSuccessfully( aGeneralResult ) )
{
// create TextString TLV
tlvSpecificData.AddTag( KTlvTextStringTag );
if ( aTextString.Length() )
{
switch ( aDataCodingScheme )
{
case RSat::EUcs2Alphabet:
{
// data coding scheme UCS2 (16-bit)
tlvSpecificData.AddByte( KUCS2DCS );
if ( aTextString.Length() )
{
TIsiUtility::CopyToBigEndian( aTextString, string );
tlvSpecificData.AddData( string );
}
break;
}
case RSat::EDigitOnlyPacked:
case RSat::ESmsDefaultAlphabetPacked:
{
// data coding scheme 7-bit default sms
tlvSpecificData.AddByte( K7BitDefaultSmsDCS );
TSatUtility::UCSToPacket7( aTextString, string );
tlvSpecificData.AddData( string );
break;
}
case RSat::EDigitOnlyUnpacked:
case RSat::ESmsDefaultAlphabetUnpacked:
{
// data coding scheme 8-bit
tlvSpecificData.AddByte( K8BitDCS );
TSatUtility::ConvertUnicode16ToSms7( string, aTextString );
tlvSpecificData.AddData( string );
break;
}
default:
// do nothing
break;
}
}
}
return UiccCatReqTerminalResponse(
aCommandDetails,
tlvSpecificData.GetDataWithoutTopLevelTag(),
aTransId );
}
// -----------------------------------------------------------------------------
// CSatMessHandler::PlayToneTerminateResponse
// Constructs PlayTone specific part of terminal
// response and calls SendTerminalResponse to send the terminal response.
// -----------------------------------------------------------------------------
//
TInt CSatMessHandler::PlayToneTerminalResp
(
TUint8 aTransId, // Transaction Id
TDes8& aCommandDetails, // Command details
TUint8 aGeneralResult, // General result
TUint8 aAdditionalInfo // Additional info
)
{
OstTrace0( TRACE_NORMAL, CSATMESSHANDLER_PLAYTONETERMINALRESP_TD, "CSatMessHandler::PlayToneTerminalResp" );
TFLOGSTRING("TSY:CSatMessHandler::PlayToneTerminalResp");
TTlv tlvSpecificData;
tlvSpecificData.AddTag( KTlvResultTag );
//General result
tlvSpecificData.AddByte( aGeneralResult );
if ( AdditionalInfoNeeded( aGeneralResult ) )
{
tlvSpecificData.AddByte( aAdditionalInfo );
}
return UiccCatReqTerminalResponse(
aCommandDetails,
tlvSpecificData.GetDataWithoutTopLevelTag(),
aTransId );
}
// -----------------------------------------------------------------------------
// CSatMessHandler::SetUpMenuTerminalResp
// Constructs SetUpMenu specific part of terminal
// response and calls SendTerminalResponse to send the terminal response.
// -----------------------------------------------------------------------------
//
TInt CSatMessHandler::SetUpMenuTerminalResp
(
TUint8 aTransId, // Transaction id
TDes8& aCommandDetails, // aPCmdNumber
TUint8 aGeneralResult, // General result
TUint8 aAdditionalInfo // Additional info
)
{
OstTrace0( TRACE_NORMAL, CSATMESSHANDLER_SETUPMENUTERMINALRESP_TD, "CSatMessHandler::SetUpMenuTerminalResp" );
TFLOGSTRING("TSY:CSatMessHandler::SetUpMenuTerminalResp");
// Create and append response data
TTlv tlvSpecificData;
//create General Result TLV here
tlvSpecificData.AddTag( KTlvResultTag );
//General result
tlvSpecificData.AddByte( aGeneralResult );
if ( RSat::KMeUnableToProcessCmd == aGeneralResult )
{
tlvSpecificData.AddByte( aAdditionalInfo );
}
return UiccCatReqTerminalResponse(
aCommandDetails,
tlvSpecificData.GetDataWithoutTopLevelTag(),
aTransId );
}
// -----------------------------------------------------------------------------
// CSatMessHandler::SelectItemTerminalResp
// Constructs SelectItem specific part of terminal
// response and calls SendTerminalResponse to send the terminal response.
// -----------------------------------------------------------------------------
//
TInt CSatMessHandler::SelectItemTerminalResp
(
TUint8 aTransId, // Transaction id
TDes8& aCommandDetails, // Comamnd number
TUint8 aGeneralResult, // General result
TUint8 aAdditionalInfo // Additional info
)
{
OstTrace0( TRACE_NORMAL, CSATMESSHANDLER_SELECTITEMTERMINALRESP_TD, "CSatMessHandler::SelectItemTerminalResp" );
TFLOGSTRING("TSY:CSatMessHandler::SelectItemTerminalResp");
TTlv tlvSpecificData;
// Create general result TLV here
tlvSpecificData.AddTag( KTlvResultTag );
// General result
tlvSpecificData.AddByte( aGeneralResult );
if ( !( CommandPerformedSuccessfully( aGeneralResult ) ) )
{
switch ( aGeneralResult )
{
case RSat::KHelpRequestedByUser:
{
// add selected Item Id tag
tlvSpecificData.AddTag( KTlvItemIdentifierTag );
tlvSpecificData.AddByte( aAdditionalInfo ); // selected item
break;
}
case RSat::KPSessionTerminatedByUser:
case RSat::KBackwardModeRequestedByUser:
case RSat::KNoResponseFromUser:
{
break;
}
default:
{
tlvSpecificData.AddByte( aAdditionalInfo );
break;
}
}
}
else
{
// add selected Item Id tag
tlvSpecificData.AddTag( KTlvItemIdentifierTag );
tlvSpecificData.AddByte( aAdditionalInfo ); // selected item
}
return UiccCatReqTerminalResponse(
aCommandDetails,
tlvSpecificData.GetDataWithoutTopLevelTag(),
aTransId );
}
// -----------------------------------------------------------------------------
// CSatMessHandler::PollIntervalTerminateResp
// Constructs PollInterval specific part of terminal
// response and calls SendTerminalResponse to send the terminal response.
// -----------------------------------------------------------------------------
//
TInt CSatMessHandler::PollIntervalTerminalResp
(
TUint8 aTransId, // Transaction id
TDes8& aCommandDetails, // command number
TUint8 aGeneralResult, // General result
TUint8 aAdditionalInfo, // Additional info
TUint8 aNumOfUnits // Time interval
)
{
OstTrace0( TRACE_NORMAL, CSATMESSHANDLER_POLLINTERVALTERMINALRESP_TD, "CSatMessHandler::PollIntervalTerminalResp" );
TFLOGSTRING("TSY:CSatMessHandler::PollIntervalTerminalResp");
TTlv tlvSpecificData;
tlvSpecificData.AddTag( KTlvResultTag );
tlvSpecificData.AddByte( aGeneralResult );
if ( !( CommandPerformedSuccessfully( aGeneralResult ) ) )
{
switch ( aGeneralResult )
{
// Cases in which additional info is not required
case RSat::KPSessionTerminatedByUser:
case RSat::KBackwardModeRequestedByUser:
case RSat::KNoResponseFromUser:
case RSat::KErrorRequiredValuesMissing:
case RSat::KHelpRequestedByUser:
{
break;
}
default:
{
tlvSpecificData.AddByte( aAdditionalInfo );
break;
}
}
}
else
{
tlvSpecificData.AddTag( KTlvDurationTag );
tlvSpecificData.AddByte( KSeconds );
tlvSpecificData.AddByte( aNumOfUnits );
}
return UiccCatReqTerminalResponse(
aCommandDetails,
tlvSpecificData.GetDataWithoutTopLevelTag(),
aTransId );
}
// -----------------------------------------------------------------------------
// CSatMessHandler::SendSmTerminalResp
// Constructs SendSm specific part of terminal
// response and calls SendTerminalResponse to send the terminal response.
// -----------------------------------------------------------------------------
//
TInt CSatMessHandler::SendSmTerminalResp
(
TUint8 aTransId, // Transaction id
TDes8& aCommandDetails, // Command details
TUint8 aGeneralResult, // General result
TUint8 aAdditionalInfo // Additional info
)
{
OstTrace0( TRACE_NORMAL, CSATMESSHANDLER_SENDSMTERMINALRESP_TD, "CSatMessHandler::SendSmTerminalResp" );
TFLOGSTRING("TSY:CSatMessHandler::SendSmTerminalResp");
// Create and append response data
TTlv tlvSpecificData;
//create General Result TLV here
tlvSpecificData.AddTag( KTlvResultTag );
//General result
tlvSpecificData.AddByte( aGeneralResult );
if ( RSat::KMeUnableToProcessCmd == aGeneralResult ||
RSat::KNetworkUnableToProcessCmd == aGeneralResult ||
RSat::KSmsRpError == aGeneralResult ||
RSat::KInteractionWithCCPermanentError == aGeneralResult )
{
// if there is ME, Network or SMS error, append additional info
tlvSpecificData.AddByte( aAdditionalInfo );
}
// Send terminal response
return UiccCatReqTerminalResponse(
aCommandDetails,
tlvSpecificData.GetDataWithoutTopLevelTag(),
aTransId );
}
// -----------------------------------------------------------------------------
// CSatMessHandler::SendSsTerminalResp
// Constructs SendSS specific part of terminal
// response and calls SendTerminalResponse to send the terminal response.
// -----------------------------------------------------------------------------
//
TInt CSatMessHandler::SendSsTerminalResp
(
TUint8 aTransId, // Transaction id
TDes8& aCommandDetails, // Command details tlv
TUint8 aGeneralResult, // General result
TDesC8& aAdditionalInfo // Additional info
)
{
OstTrace0( TRACE_NORMAL, CSATMESSHANDLER_SENDSSTERMINALRESP_TD, "CSatMessHandler::SendSsTerminalResp" );
TFLOGSTRING("TSY:CSatMessHandler::SendSsTerminalResp");
// Create and append response data
TTlv tlvSpecificData;
tlvSpecificData.AddTag( KTlvResultTag );
// Append general result
tlvSpecificData.AddByte( aGeneralResult );
if ( RSat::KErrorRequiredValuesMissing != aGeneralResult &&
RSat::KCmdDataNotUnderstood != aGeneralResult )
{
tlvSpecificData.AddData( aAdditionalInfo );
}
return UiccCatReqTerminalResponse(
aCommandDetails,
tlvSpecificData.GetDataWithoutTopLevelTag(),
aTransId );
}
// -----------------------------------------------------------------------------
// CSatMessHandler::SendDtmfTerminalResp
// Constructs Send Dtmf specific part of terminal
// response and calls SendTerminalResponse to send the terminal response.
// -----------------------------------------------------------------------------
//
TInt CSatMessHandler::SendDtmfTerminalResp
(
TUint8 aTransId,
TDes8& aCommandDetails,
TUint8 aGeneralResult, // General result
TUint8 aAdditionalInfo // Additional info
)
{
OstTrace0( TRACE_NORMAL, CSATMESSHANDLER_SENDDTMFTERMINALRESP_TD, "CSatMessHandler::SendDtmfTerminalResp" );
TFLOGSTRING("CSatMessHandler::SendDtmfTerminalResp");
TTlv tlvSpecificData;
// Append general result tag
tlvSpecificData.AddTag( KTlvResultTag );
// Append general result
tlvSpecificData.AddByte( aGeneralResult );
if ( RSat::KMeUnableToProcessCmd == aGeneralResult )
{
// UnSuccessful result neccessitating additional info byte
tlvSpecificData.AddByte( aAdditionalInfo );
}
return UiccCatReqTerminalResponse(
aCommandDetails,
tlvSpecificData.GetDataWithoutTopLevelTag(),
aTransId );
}
// -----------------------------------------------------------------------------
// CSatMessHandler::SendUssdTerminalResponse
// Constructs and sends the Send USSD response to Phonet, in order
// to reach the CellMo side.
// -----------------------------------------------------------------------------
//
TInt CSatMessHandler::SendUssdTerminalResp
(
TUint8 aTransId,
TDes8& aCommandDetails,
TUint8 aGeneralResult,
TUint8 aAdditionalInfo,
TDes& aUssdData,
TUint8 aUssdCbsDataCodingScheme
)
{
OstTrace0( TRACE_NORMAL, CSATMESSHANDLER_SENDUSSDTERMINALRESP_TD, "CSatMessHandler::SendUssdTerminalResp" );
TFLOGSTRING("TSY:CSatMessHandler::SendUssdTerminalResp");
TTlv tlvSpecificData;
TBuf8<RSat::KStringMaxSize> string;
tlvSpecificData.AddTag( KTlvResultTag );
tlvSpecificData.AddByte( aGeneralResult );
// For the general results '20', '21', '37', '38', '39'
// it is mandatory for the ME to provide a specific
// cause value as additional
if ( ( RSat::KMeUnableToProcessCmd == aGeneralResult )
|| ( RSat::KNetworkUnableToProcessCmd == aGeneralResult )
|| ( RSat::KUssdReturnError == aGeneralResult)
|| ( RSat::KMultipleCardCmdsError == aGeneralResult)
|| ( RSat::KInteractionWithCCPermanentError == aGeneralResult ) )
{
tlvSpecificData.AddByte( aAdditionalInfo );
}
// For general result '32' additional info or text string is not used
else if ( RSat::KCmdDataNotUnderstood != aGeneralResult )
{
// Append received Ussd text string, with a Text string tag
tlvSpecificData.AddTag( KTlvTextStringTag );
// Decode DCS
// Remains to know if SatServer sets the general result to
// KUssdReturnError when the DCS has a reserved value.
TSmsDcs decodedDcs( ESmsUnknownOrReservedDcs );
decodedDcs = TSatUtility::DecodeCbsDcs( aUssdCbsDataCodingScheme );
//Data Coding Scheme for Text String
tlvSpecificData.AddByte( (TUint8)decodedDcs );
switch ( decodedDcs )
{
case ESms7BitDcs:
{
// Convert the Response string (which comes in the form of
// a TBuf (unicode)) to 7-bit gsm format.
TSatUtility::UCSToPacket7( aUssdData, string );
break;
}
case ESms8BitDcs:
{
// Convert the Response string (which comes in the form of
// a TBuf (unicode)) to 7-bit gsm format.
TSatUtility::ConvertUnicode16ToSms7( string, aUssdData );
break;
}
case ESms16BitDcs:
{
TIsiUtility::CopyToBigEndian( aUssdData, string );
break;
}
default:
{
// Reserved
// The general result should in fact prevent reaching this
// branch of the switch.
TFLOGSTRING("TSY:CSatMessHandler::SendUssdTerminalResp, \
The DCS sent by the network has a reserved value.");
OstTrace0( TRACE_NORMAL, DUP1_CSATMESSHANDLER_SENDUSSDTERMINALRESP_TD, "CSatMessHandler::SendUssdTerminalResp, The DCS sent by the network has a reserved value." );
break;
}
}
// Text
tlvSpecificData.AddData( string );
}
return UiccCatReqTerminalResponse(
aCommandDetails,
tlvSpecificData.GetDataWithoutTopLevelTag(),
aTransId );
}
// -----------------------------------------------------------------------------
// CSatMessHandler::SetUpCallTerminalResp
// Constructs SetUpCall specific part of terminal
// response and calls SendTerminalResponse to send the terminal response
// -----------------------------------------------------------------------------
//
TInt CSatMessHandler::SetUpCallTerminalResp
(
TUint8 aTransId, // Transaction id
TDes8& aCommandDetails, // Command Details tlv
TUint8 aGeneralResult, // General result
TUint8 aAdditionalInfo // Additional info
)
{
OstTrace0( TRACE_NORMAL, CSATMESSHANDLER_SETUPCALLTERMINALRESP_TD, "CSatMessHandler::SetUpCallTerminalResp" );
TFLOGSTRING("TSY:CSatMessHandler::SetUpCallTerminalResp");
// Create and append response data
TTlv tlvSpecificData;
tlvSpecificData.AddTag( KTlvResultTag );
// Result
tlvSpecificData.AddByte( aGeneralResult );
if ( RSat::KMeUnableToProcessCmd == aGeneralResult ||
RSat::KNetworkUnableToProcessCmd == aGeneralResult ||
RSat::KInteractionWithCCPermanentError == aGeneralResult )
{
// If there was ME or network error, add additional info
tlvSpecificData.AddByte( aAdditionalInfo );
}
return UiccCatReqTerminalResponse(
aCommandDetails,
tlvSpecificData.GetDataWithoutTopLevelTag(),
aTransId );
}
// -----------------------------------------------------------------------------
// CSatMessHandler::RefreshTerminalResp
// Constructs Refresh specific part of terminal
// response and calls SendTerminalResponse to send the terminal response
// -----------------------------------------------------------------------------
//
TInt CSatMessHandler::RefreshTerminalResp
(
TUint8 aTransId, // Transaction id
TDes8& aCommandDetails, // Command number
TUint8 aGeneralResult, // General result
TUint8 aAdditionalInfo // Additional info
)
{
OstTrace0( TRACE_NORMAL, CSATMESSHANDLER_REFRESHTERMINALRESP_TD, "CSatMessHandler::RefreshTerminalResp" );
TFLOGSTRING("TSY:CSatMessHandler::RefreshTerminalResp");
// Create and append response data
TTlv tlvSpecificData;
// append result tag
tlvSpecificData.AddTag( KTlvResultTag );
// General result
tlvSpecificData.AddByte( aGeneralResult );
if ( RSat::KMeUnableToProcessCmd == aGeneralResult )
{
tlvSpecificData.AddByte( aAdditionalInfo );
}
return UiccCatReqTerminalResponse(
aCommandDetails,
tlvSpecificData.GetDataWithoutTopLevelTag(),
aTransId );
}
// -----------------------------------------------------------------------------
// CSatMessHandler::MenuSelectionInd
// Constructs and sends the Menu Selection response to phonet
// -----------------------------------------------------------------------------
//
void CSatMessHandler::MenuSelectionInd
(
TUint8 aTransId, // Transaction id
TUint8 aItemIdentifier, // Item identifier
TUint8 aHelp // Help requested status
)
{
OstTrace0( TRACE_NORMAL, CSATMESSHANDLER_MENUSELECTIONIND_TD, "CSatMessHandler::MenuSelectionInd" );
TFLOGSTRING("TSY:CSatMessHandler::MenuSelectionInd");
TTlv tlvSpecificData;
tlvSpecificData.Begin( KBerTlvMenuSelectionTag );
tlvSpecificData.AddTag( KTlvDeviceIdentityTag );
tlvSpecificData.AddByte( KKeypad );
tlvSpecificData.AddByte( KSim );
tlvSpecificData.AddTag( KTlvItemIdentifierTag );
tlvSpecificData.AddByte( aItemIdentifier );
if ( aHelp )
{
tlvSpecificData.AddTag( KTlvHelpRequestTag );
}
// Save menu selection envelope's transaction id, because SIM session
// has to be completed if menu selection does not have successive commands.
iTerminalRespTraId = TInt( aTransId );
UiccCatReqEnvelope( aTransId, tlvSpecificData.End(), EFalse );
}
// -----------------------------------------------------------------------------
// CSatMessHandler::LaunchBrowserTerminalResp
// Constructs and sends the Launch Browser response to phonet
// -----------------------------------------------------------------------------
//
TInt CSatMessHandler::LaunchBrowserTerminalResp
(
TUint8 aTransId, // aTransId
TDes8& aCommandDetails, // command number
TUint8 aGeneralResult, // Result
TUint8 aAdditionalInfo // additional info
)
{
OstTrace0( TRACE_NORMAL, CSATMESSHANDLER_LAUNCHBROWSERTERMINALRESP_TD, "CSatMessHandler::LaunchBrowserTerminalResp" );
TFLOGSTRING("TSY:CSatMessHandler::LaunchBrowserTerminalResp");
TTlv tlvSpecificData;
tlvSpecificData.AddTag( KTlvResultTag );
//create General Result TLV here
tlvSpecificData.AddByte( aGeneralResult );
if ( !( CommandPerformedSuccessfully( aGeneralResult ) ) )
{
if ( RSat::KCmdTypeNotUnderstood != aGeneralResult
&& RSat::KCmdDataNotUnderstood != aGeneralResult
&& RSat::KErrorRequiredValuesMissing != aGeneralResult )
{
// additional info
tlvSpecificData.AddByte( aAdditionalInfo );
}
}
return UiccCatReqTerminalResponse(
aCommandDetails,
tlvSpecificData.GetDataWithoutTopLevelTag(),
aTransId );
}
// -----------------------------------------------------------------------------
// CSatMessHandler::CommandPerformedSuccessfully
// Test if a proactive command was performed successfully
// -----------------------------------------------------------------------------
//
TBool CSatMessHandler::CommandPerformedSuccessfully
(
TUint8 aGeneralResult
)
{
OstTrace0( TRACE_NORMAL, CSATMESSHANDLER_COMMANDPERFORMEDSUCCESSFULLY_TD, "CSatMessHandler::CommandPerformedSuccessfully" );
TFLOGSTRING("TSY:CSatMessHandler::CommandPerformedSuccessfully");
TBool ret( EFalse );
switch ( aGeneralResult )
{
case RSat::KSuccess:
case RSat::KPartialComprehension:
case RSat::KMissingInformation:
case RSat::KRefreshAdditionEFRead:
case RSat::KSuccessRequestedIconNotDisplayed:
case RSat::KModifiedByCallControl:
case RSat::KSuccessLimitedService:
case RSat::KPerformedWithModifications:
case RSat::KRefreshUSIMNotActive:
{
ret = ETrue;
break;
}
default:
{
ret = EFalse;
break;
}
}
return ret;
}
// -----------------------------------------------------------------------------
// CSatMessHandler::SetUpIdleModeTextTerminalResp
// Constructs SetUpIdleModeText specific part of terminal
// response and calls SendTerminalResponse to send the terminal response
// -----------------------------------------------------------------------------
//
TInt CSatMessHandler::SetUpIdleModeTextTerminalResp
(
TUint8 aTransId, // Transaction id
TDes8& aCommandDetails, // command number
TUint8 aGeneralResult, // Result
TUint8 aAdditionalInfo // Additional info
)
{
OstTrace0( TRACE_NORMAL, CSATMESSHANDLER_SETUPIDLEMODETEXTTERMINALRESP_TD, "CSatMessHandler::SetUpIdleModeTextTerminalResp" );
TFLOGSTRING("TSY:CSatMessHandler::SetUpIdleModeTextTerminalResp");
TTlv tlvSpecificData;
//create General Result TLV here
tlvSpecificData.AddTag( KTlvResultTag );
//General result
tlvSpecificData.AddByte( aGeneralResult );
if ( !( CommandPerformedSuccessfully( aGeneralResult ) ) )
{
switch ( aGeneralResult )
{
// Cases in which additional info is not required
case RSat::KPSessionTerminatedByUser:
case RSat::KBackwardModeRequestedByUser:
case RSat::KNoResponseFromUser:
case RSat::KErrorRequiredValuesMissing:
case RSat::KHelpRequestedByUser:
case RSat::KCmdDataNotUnderstood:
{
break;
}
default:
{
tlvSpecificData.AddByte( aAdditionalInfo );
break;
}
}
}
return UiccCatReqTerminalResponse(
aCommandDetails,
tlvSpecificData.GetDataWithoutTopLevelTag(),
aTransId );
}
// -----------------------------------------------------------------------------
// CSatMessHandler::UiccCatReqEnvelope
// Create and send UICC_CAT_REQ with UICC_SB_ENVELOPE
// -----------------------------------------------------------------------------
//
TInt CSatMessHandler::UiccCatReqEnvelope
(
TUint8 aTransId,
const TDesC8& aBerTlv, // BER-TLV specific data
TBool aStore // Is envelope stored for resending
)
{
OstTrace0( TRACE_NORMAL, CSATMESSHANDLER_UICCCATREQENVELOPE_TD, "CSatMessHandler::UiccCatReqEnvelope" );
TFLOGSTRING("TSY:CSatMessHandler::UiccCatReqEnvelope");
TIsiSend isiMsg( iPnSend->SendBufferDes() );
isiMsg.Set8bit( ISI_HEADER_OFFSET_RESOURCEID, PN_UICC );
isiMsg.Set8bit(
ISI_HEADER_SIZE + UICC_CAT_REQ_OFFSET_TRANSID,
aTransId );
isiMsg.Set8bit(
ISI_HEADER_SIZE + UICC_CAT_REQ_OFFSET_MESSAGEID,
UICC_CAT_REQ );
isiMsg.Set8bit(
ISI_HEADER_SIZE + UICC_CAT_REQ_OFFSET_SERVICETYPE,
UICC_CAT_ENVELOPE );
isiMsg.Set8bit(
ISI_HEADER_SIZE + UICC_CAT_REQ_OFFSET_NSB,
1 );
// Add UICC_SB_ENVELOPE
TBuf8<SIZE_UICC_SB_ENVELOPE + KMaxSizeOfEnvelope> uiccSbEnvelopeBuf( 0 );
TIsiSubBlock uiccSbEnvelope(
uiccSbEnvelopeBuf,
UICC_SB_ENVELOPE,
EIsiSubBlockTypeId16Len16 );
// 2x filler
uiccSbEnvelopeBuf.Append( KUiccPadding );
uiccSbEnvelopeBuf.Append( KUiccPadding );
uiccSbEnvelopeBuf.Append( aBerTlv.Length() >> 8 ); // Length of envelope
uiccSbEnvelopeBuf.Append( aBerTlv.Length() );
uiccSbEnvelopeBuf.Append( aBerTlv ); // Envelope
// Append subblock to ISI message
isiMsg.CopyData(
ISI_HEADER_SIZE + SIZE_UICC_CAT_REQ,
uiccSbEnvelope.CompleteSubBlock() );
// Store information if needed for possible resending
if ( aStore )
{
iTsySatMessaging->GetSatTimer()->StoreEnvelope( aTransId, aBerTlv );
}
return( iPnSend->Send( isiMsg.Complete() ) );
}
// -----------------------------------------------------------------------------
// CSatMessHandler::StoreNetServiceStatus
// Stores location information and network service status
// -----------------------------------------------------------------------------
//
TInt CSatMessHandler::StoreNetServiceStatus
(
const TIsiReceiveC& aIsiMessage
)
{
OstTrace0( TRACE_NORMAL, CSATMESSHANDLER_STORENETSERVICESTATUS_TD, "CSatMessHandler::StoreNetServiceStatus" );
TFLOGSTRING("TSY: CSatMessHandler::StoreNetServiceStatus");
// SubBlock offset
TUint sbOffset( 0 );
TInt messageId( aIsiMessage.Get8bit( ISI_HEADER_OFFSET_MESSAGEID ) );
TInt headerSize( KErrNotFound );
TInt retValue( KErrNone );
if ( NET_CELL_INFO_IND == messageId )
{
headerSize = SIZE_NET_CELL_INFO_IND;
}
else if ( NET_CELL_INFO_GET_RESP == messageId )
{
headerSize = SIZE_NET_CELL_INFO_GET_RESP;
}
else
{
// Header size contains already an error value as default.
}
if ( KErrNotFound != headerSize )
{
// Find NET_GSM_CELL_INFO or NET_WCDMA_CELL_INFO subblock
TInt retGsmSb( aIsiMessage.FindSubBlockOffsetById(
ISI_HEADER_SIZE + headerSize,
NET_GSM_CELL_INFO,
EIsiSubBlockTypeId8Len8,
sbOffset ) );
TInt retWcdmaSb( aIsiMessage.FindSubBlockOffsetById(
ISI_HEADER_SIZE + headerSize,
NET_WCDMA_CELL_INFO,
EIsiSubBlockTypeId8Len8,
sbOffset ) );
// Check if subblock exists.
if ( KErrNone == retGsmSb || KErrNone == retWcdmaSb )
{
// NET_GSM_CELL_INFO and NET_WCDMA_CELL_INFO subblocks have identical
// bytes and sizes ,use only NET_GSM_CELL_INFO subblock offset
// values when getting data.
// Get registration status value
iLocInfo.iRegStatus = aIsiMessage.Get8bit(
sbOffset + NET_GSM_CELL_INFO_OFFSET_SERVICESTATUS );
TFLOGSTRING2("TSY: CSatMessHandler::StoreNetServiceStatus: NET_REGISTRATION_STATUS = %d", iLocInfo.iRegStatus );
OstTrace1( TRACE_NORMAL, DUP1_CSATMESSHANDLER_STORENETSERVICESTATUS_TD, "CSatMessHandler::StoreNetServiceStatus NET_REGISTRATION_STATUS = %d", iLocInfo.iRegStatus );
if ( NET_SERVICE == iLocInfo.iRegStatus ||
NET_LIMITED_SERVICE == iLocInfo.iRegStatus )
{
// Get country code
iLocInfo.iOperatorCode.Copy(
aIsiMessage.GetData(
sbOffset + NET_GSM_CELL_INFO_OFFSET_OPERATORCODE,
3 ) );
// Set location area code, 2 bytes
iLocInfo.iLac.Copy(
aIsiMessage.GetData(
sbOffset + NET_GSM_CELL_INFO_OFFSET_CURRENTLAC,
2 ) );
// Cell id + Extented Cell id, 4 bytes
// Id's are included to Location Information TLV
// reverse order, see 31.111, 8.19
TPtrC8 tempCellId( aIsiMessage.GetData(
sbOffset + NET_GSM_CELL_INFO_OFFSET_CURRENTCELLID,
4 ) );
// Copy cell id to be first in buffer
iLocInfo.iCellId.Copy( tempCellId.Mid( 2 ) );
// Append extented cell id part
iLocInfo.iCellId.Append( tempCellId.Left( 2 ) );
// Network type
if ( NET_GSM_CELL_INFO == aIsiMessage.Get8bit(
sbOffset + NET_GSM_CELL_INFO_OFFSET_SUBBLOCKID ) )
{
iCurrentAccTech = KNetworkModeGsm;
}
else
{
iCurrentAccTech = KNetworkModeUtran;
}
}
}
else
{
TFLOGSTRING("TSY: CSatMessHandler::StoreNetServiceStatus - NET_GSM_CELL_INFO or NET_WCDMA_CELL_INFO not found!");
OstTrace0( TRACE_NORMAL, DUP2_CSATMESSHANDLER_STORENETSERVICESTATUS_TD, "CSatMessHandler::StoreNetServiceStatus NET_GSM_CELL_INFO or NET_WCDMA_CELL_INFO not found!" );
retValue = KErrNotFound;
}
}
else
{
TFLOGSTRING2("TSY: CSatMessHandler::StoreNetServiceStatus - Unexpected message id: %d", messageId );
OstTrace1( TRACE_NORMAL, DUP3_CSATMESSHANDLER_STORENETSERVICESTATUS_TD, "CSatMessHandler::StoreNetServiceStatus Unexpected message id: %d", messageId );
retValue = KErrNotFound;
}
return retValue;
}
// -----------------------------------------------------------------------------
// CSatMessHandler::SetUpEventListTerminalResp
// Constructs Setup EventList and calls
// SendTerminalResponse to send the terminal response
// -----------------------------------------------------------------------------
//
TInt CSatMessHandler::SetUpEventListTerminalResp
(
TUint8 aTransId, // Transaction id
TDes8& aCommandDetails, // Command details
TUint8 aGeneralResult, // General result
TUint8 aAdditionalInfo // Additional info
)
{
OstTrace0( TRACE_NORMAL, CSATMESSHANDLER_SETUPEVENTLISTTERMINALRESP_TD, "CSatMessHandler::SetUpEventListTerminalResp" );
TFLOGSTRING("TSY:CSatMessHandler::SetUpEventListTerminalResp");
// create responce data
TTlv tlvSpecificData;
//create General Result TLV here
tlvSpecificData.AddTag( KTlvResultTag );
//General result
tlvSpecificData.AddByte( aGeneralResult );
if ( RSat::KSuccess != aGeneralResult &&
RSat::KCmdBeyondMeCapabilities != aGeneralResult &&
RSat::KErrorRequiredValuesMissing != aGeneralResult)
{
tlvSpecificData.AddByte( aAdditionalInfo );
}
#ifdef INFO_PP_ENHANCED_NETWORK_SELECTION
iSetUpEventListTrSent = ETrue;
#endif // INFO_PP_ENHANCED_NETWORK_SELECTION
return UiccCatReqTerminalResponse(
aCommandDetails,
tlvSpecificData.GetDataWithoutTopLevelTag(),
aTransId );
}
// -----------------------------------------------------------------------------
// CSatMessHandler::PollingOffTerminalResp
// Constructs PollingOff specific part of terminal
// response and calls SendTerminalResponse
// -----------------------------------------------------------------------------
//
TInt CSatMessHandler::PollingOffTerminalResp
(
TUint8 aTransId,
TDes8& aCommandDetails, // Transaction id
TUint8 aGeneralResult, // General result
TUint8 aAdditionalInfo // Additional info
)
{
OstTrace0( TRACE_NORMAL, CSATMESSHANDLER_POLLINGOFFTERMINALRESP_TD, "CSatMessHandler::PollingOffTerminalResp" );
TFLOGSTRING("TSY:CSatMessHandler::PollingOffTerminalResp");
TTlv tlvSpecificData;
tlvSpecificData.AddTag( KTlvResultTag );
tlvSpecificData.AddByte( aGeneralResult );
if ( !( CommandPerformedSuccessfully( aGeneralResult ) ) )
{
switch ( aGeneralResult )
{
// Cases in which additional info is not required
case RSat::KPSessionTerminatedByUser:
case RSat::KBackwardModeRequestedByUser:
case RSat::KNoResponseFromUser:
case RSat::KErrorRequiredValuesMissing:
case RSat::KHelpRequestedByUser:
{
break;
}
default:
{
tlvSpecificData.AddByte( aAdditionalInfo );
break;
}
}
}
return UiccCatReqTerminalResponse(
aCommandDetails,
tlvSpecificData.GetDataWithoutTopLevelTag(),
aTransId );
}
// -----------------------------------------------------------------------------
// CSatMessHandler::LocalInfoTerminalResp
// Constructs and sends the Local information response to
// the SIM card.
// -----------------------------------------------------------------------------
//
TInt CSatMessHandler::LocalInfoTerminalResp
(
TUint8 aTransId, // Transaction id
TDes8& aCommandDetails, // Command details tlv
TUint8 aGeneralResult, // General result
TDes& aAdditionalInfo // Additional info
)
{
OstTrace0( TRACE_NORMAL, CSATMESSHANDLER_LOCALINFOTERMINALRESP_TD, "CSatMessHandler::LocalInfoTerminalResp" );
TFLOGSTRING("TSY: CSatMessHandler::LocalInfoTerminalResp");
// Create and append response data
TTlv tlvData;
// Create General Result TLV
tlvData.AddTag( KTlvResultTag );
// General result
tlvData.AddByte( aGeneralResult );
if ( RSat::KSuccess != aGeneralResult
&& RSat::KSuccessLimitedService != aGeneralResult )
{
if ( aAdditionalInfo.Length() )
{
tlvData.AddByte( TUint8( aAdditionalInfo[0] & 0xFF ) );
}
}
else
{
switch ( aCommandDetails[KCommandQualifier] )
{
case RSat::KProvideLocalInfo:
{
const TLocationInfo& locInfo = LocationInfo();
// Create Location Information TLV
tlvData.AddTag( KTlvLocationInformationTag );
// Append Mobile Country & Network Codes, 3 bytes
tlvData.AddData( locInfo.iOperatorCode );
// Append LAC code
tlvData.AddData( locInfo.iLac );
// Append CellId
tlvData.AddData( locInfo.iCellId );
break;
}
case RSat::KProvideLocalInfoImei:
{
// Add tlv tag
tlvData.AddTag( KTlvImeiTag );
TBuf8<8> bcdImei;
// Convert IMEI to BCD format
_LIT8( KTen, "*" );
_LIT8( KZero, "0" );
// Check if required changes is allready done for the IMEI
if ( '*' != iIMEI[0] )
{
// Processing BCD string is much harder than ASCII so
// required changes is done before BCD conversion.
// (lot's of shifting etc..)
// Insert '*'(0x2A) as a first character which is converted
// to 0xA in AsciiToBCD method.
// Type of identity for IMEI code is 0xA "1010b"
// See 3GPP TS 04.08
iIMEI.Insert( 0, KTen );
// Spare digit: this digit shall be zero, when transmitted
// by the Mobile Station.
// See GSM 03.03
iIMEI.Replace( iIMEI.Length() - 1, 1 , KZero );
}
TSatUtility::AsciiToBCD( iIMEI, bcdImei );
// Add IMEI code to the terminal response
tlvData.AddData( bcdImei );
break;
}
case RSat::KProvideLocalInfoIMEISV:
{
tlvData.AddTag( KTlvImeisvTag );
tlvData.AddData( iIMEIsv );
break;
}
case RSat::KProvideLocalInformationNmr:
{
// Check if NMR's were for UTRAN
if ( iUtranNMR.Length() )
{
tlvData.AddTag( KTlvNetworkMeasurementResultsTag );
tlvData.AddData( iUtranNMR );
}
else
{
// NMR's were for GSM
if ( iNMR.Length() )
{
// Network measurement result
tlvData.AddTag( KTlvNetworkMeasurementResultsTag );
tlvData.AddData( iNMR );
}
if ( iBCCHChannelList.Length() )
{
// append BCCH channel list tag
tlvData.AddTag( KTlvBccdChannelListTag );
TInt i( 0 );
TInt mask( 3 );
TInt shiftMove( 2 );
TUint8 nextChar( 0 );
// Convert BCCH channel list from 16-bit to 10-bit
// format
for ( i = 0; i < iBCCHChannelList.Length(); i++ )
{
TUint char2 = ( iBCCHChannelList[i] & 0x03FF );
TUint8 char1 = TUint8( char2 >> shiftMove);
// append byte
tlvData.AddByte( TUint8( char1 | nextChar ) );
nextChar = TUint8 ( ( char2 & mask )
<< ( 8 - shiftMove ) );
if ( 8 == shiftMove )
{
shiftMove = 2;
nextChar = 0;
tlvData.AddByte( TUint8( char2 & 0x00FF ) );
mask = 3;
}
else
{
shiftMove += 2;
mask = ( 1L << shiftMove) - 1;
}
}
// add last byte
tlvData.AddByte( nextChar );
}
}
// clear nmr
iNMR.Zero();
// clear BCCH channel list
iBCCHChannelList.Zero();
// clear UTRAN NMR's
iUtranNMR.Set( KNullDesC8 );
break;
}
case RSat::KProvideLocalInfoDateTimeTimeZone:
{
tlvData.AddTag( KTlvDateTimeAndTimeZoneTag );
// append current date/time/timezone to the terminal response
TInt i( 0 );
for ( i = 0; i < aAdditionalInfo.Length(); i++ )
{
tlvData.AddByte( TUint8( aAdditionalInfo[i] & 0x00FF ) );
}
break;
}
case RSat::KProvideLocalInfoTimingAdv:
{
TFLOGSTRING("TSY: CSatMessHandler::LocalInfoTerminalResp,\
TimingAdvance");
OstTrace0( TRACE_NORMAL, DUP1_CSATMESSHANDLER_LOCALINFOTERMINALRESP_TD, "CSatMessHandler::LocalInfoTerminalResp, TimingAdvance" );
// Timing advance result
tlvData.AddTag( KTlvTimingAdvanceTag );
tlvData.AddByte( iTaStatus );
tlvData.AddByte( iTimingAdvance );
break;
}
case RSat::KProvideLocalInfoLanguage:
{
TFLOGSTRING("TSY: CSatMessHandler::LocalInfoTerminalResp,\
LocalInfoLanguage");
OstTrace0( TRACE_NORMAL, DUP2_CSATMESSHANDLER_LOCALINFOTERMINALRESP_TD, "CSatMessHandler::LocalInfoTerminalResp, LocalInfoLanguage" );
if ( aAdditionalInfo.Length() )
{
// create Language TLV
tlvData.AddTag( KTlvLanguageTag );
TBuf8<2> character;
TIsiUtility::CopyToBigEndian( aAdditionalInfo, character);
tlvData.AddData( character );
}
break;
}
case RSat::KProvideLocalInfoAccTech:
{
TFLOGSTRING("TSY: CSatMessHandler::LocalInfoTerminalResp,\
Access Technology");
OstTrace0( TRACE_NORMAL, DUP3_CSATMESSHANDLER_LOCALINFOTERMINALRESP_TD, "CSatMessHandler::LocalInfoTerminalResp, Access Technology" );
// Access technology result
tlvData.AddTag( KTlvAccessTechnologyTag );
tlvData.AddByte( iCurrentAccTech );
break;
}
default:
{
break;
}
}
}
return UiccCatReqTerminalResponse(
aCommandDetails,
tlvData.GetDataWithoutTopLevelTag(),
aTransId );
}
// -----------------------------------------------------------------------------
// CSatMessHandler::InfoSerialNumberReadReq
// Constructs INFO_SERIAL_NUMBER_READ_REQ ISI message.
// Called from CTsySatMessaging::ConstructL method.
// -----------------------------------------------------------------------------
//
/*TInt CSatMessHandler::InfoSerialNumberReadReq
(
TUint8 aTransId, // Transactio id
TUint8 aTarget
)
{
OstTrace0( TRACE_NORMAL, CSATMESSHANDLER_INFOSERIALNUMBERREADREQ_TD, "CSatMessHandler::InfoSerialNumberReadReq" );
TFLOGSTRING("TSY:CSatMessHandler::InfoSerialNumberReadReq");
//set infoSerialNumberReadReq to point to the send buffer
TIsiSend infoSerialNumberReadReq( iPnSend->SendBufferDes() );
infoSerialNumberReadReq.Set8bit( ISI_HEADER_OFFSET_RESOURCEID, PN_INFO );
infoSerialNumberReadReq.Set8bit( ISI_HEADER_OFFSET_TRANSID, aTransId );
infoSerialNumberReadReq.Set8bit( ISI_HEADER_OFFSET_MESSAGEID,
INFO_SERIAL_NUMBER_READ_REQ );
infoSerialNumberReadReq.Set8bit( ISI_HEADER_SIZE
+ INFO_SERIAL_NUMBER_READ_REQ_OFFSET_TARGET, aTarget );
//send message via Phonet
return iPnSend->Send( infoSerialNumberReadReq.Complete() );
}*/
// -----------------------------------------------------------------------------
// CSatMessHandler::InfoSerialNumberReadResp
// Breaks a INFO_SERIAL_NUMBER_READ_RESP ISI-message.
// -----------------------------------------------------------------------------
//
/*void CSatMessHandler::InfoSerialNumberReadResp
(
const TIsiReceiveC& aIsiMessage // received ISI-message
)
{
OstTrace0( TRACE_NORMAL, CSATMESSHANDLER_INFOSERIALNUMBERREADRESP_TD, "CSatMessHandler::InfoSerialNumberReadResp" );
TFLOGSTRING("TSY:CSatMessHandler::InfoSerialNumberReadResp");
TUint sbStartOffset( 0 );
//check if INFO_SB_SN_IMEI_PLAIN sub block is present
if ( KErrNone == aIsiMessage.FindSubBlockOffsetById(
ISI_HEADER_SIZE + SIZE_INFO_SERIAL_NUMBER_READ_RESP,
INFO_SB_SN_IMEI_PLAIN, EIsiSubBlockTypeId8Len8,
sbStartOffset ) )
{
//store imei code
iIMEI.Copy( aIsiMessage.GetData(
sbStartOffset + INFO_SB_SN_IMEI_PLAIN_OFFSET_IMEIPLAINU8,
aIsiMessage.Get8bit( sbStartOffset +
INFO_SB_SN_IMEI_PLAIN_OFFSET_STRLEN ) - 1 ) );
//Set the flag to inform that needed data has been received
iImeiAvailable = ETrue;
TFLOGSTRING("TSY: SAT, Imei received.");
OstTrace0( TRACE_NORMAL, DUP1_CSATMESSHANDLER_INFOSERIALNUMBERREADRESP_TD, "SAT, Imei received." );
}
//check if INFO_SB_SN_IMEI_SV_TO_NET sub block is present
else if ( KErrNone == aIsiMessage.FindSubBlockOffsetById(
ISI_HEADER_SIZE + SIZE_INFO_SERIAL_NUMBER_READ_RESP,
INFO_SB_SN_IMEI_SV_TO_NET, EIsiSubBlockTypeId8Len8,
sbStartOffset ) )
{
// store imeisv code
iIMEIsv.Copy( aIsiMessage.GetData(
sbStartOffset + INFO_SB_SN_IMEI_SV_TO_NET_OFFSET_IMEISVU8,
aIsiMessage.Get8bit( sbStartOffset +
INFO_SB_SN_IMEI_SV_TO_NET_OFFSET_STRLEN ) ) );
iImeiSvAvailable = ETrue;
TFLOGSTRING("TSY: CSatMessHandler::InfoSerialNumberReadResp IMEISV received");
OstTrace0( TRACE_NORMAL, DUP2_CSATMESSHANDLER_INFOSERIALNUMBERREADRESP_TD, "CSatMessHandler::InfoSerialNumberReadResp IMEISV received" );
}
}*/
// -----------------------------------------------------------------------------
// CSatMessHandler::NetNeighbourCellsReq
// Constructs NET_NEIGHBOUR_CELLS_REQ ISI message.
// -----------------------------------------------------------------------------
//
TInt CSatMessHandler::NetNeighbourCellsReq
(
TUint8 aTransId, // Transaction Id
TUint8 aCellInfoType // Cell info type
)
{
OstTrace0( TRACE_NORMAL, CSATMESSHANDLER_NETNEIGHBOURCELLSREQ_TD, "CSatMessHandler::NetNeighbourCellsReq" );
TFLOGSTRING("TSY:CSatMessHandler::NetNeighbourCellsReq");
TBuf8<1> data;
data.Append( aCellInfoType );
return iPnSend->Send(
PN_MODEM_NETWORK,
aTransId,
NET_NEIGHBOUR_CELLS_REQ,
data );
}
// -----------------------------------------------------------------------------
// CSatMessHandler::NetNeighbourCellResp
// Parse NET_NEIGHBOUR_CELLS_RESP message and read from it BCCH
// channel list and Network measurement results.
// -----------------------------------------------------------------------------
//
void CSatMessHandler::NetNeighbourCellResp
(
const TIsiReceiveC& aIsiMessage
)
{
OstTrace0( TRACE_NORMAL, CSATMESSHANDLER_NETNEIGHBOURCELLRESP_TD, "CSatMessHandler::NetNeighbourCellResp" );
TFLOGSTRING("TSY:CSatMessHandler::NetNeighbourCellResp");
TUint8 result( RSat::KSuccess );
if ( iTsySatMessaging->GetNotifyLocalInfo()->LocalInfoStatus() )
{
// Provide local info proactive command is ongoing
// Subblock offset
TUint sbOffset( 0 );
TInt successCode ( aIsiMessage.Get8bit(
ISI_HEADER_SIZE + NET_NEIGHBOUR_CELLS_RESP_OFFSET_SUCCESSCODE ) );
// Additional info
TBuf<1> additionalInfo;
additionalInfo.Zero();
// Get transaction id
TUint8 transId(
iTsySatMessaging->GetNotifyLocalInfo()->GetTransactionId() );
// Get command details tlv
TBuf8<5> commandDetails;
commandDetails =
iTsySatMessaging->GetNotifyLocalInfo()->GetCmdDetails();
TInt sbIndex( 1 );
TInt retValue( aIsiMessage.FindSubBlockOffsetByIndex(
ISI_HEADER_SIZE + SIZE_NET_NEIGHBOUR_CELLS_RESP,
sbIndex,
EIsiSubBlockTypeId8Len8,
sbOffset ) );
if ( NET_CAUSE_OK == successCode && KErrNone == retValue )
{
if ( NET_LIMITED_SERVICE == iLocInfo.iRegStatus )
{
result = RSat::KSuccessLimitedService;
}
switch( aIsiMessage.Get8bit( sbOffset ) )
{
case NET_GSM_SIM_NMR_INFO:
{
// Store network measurements results, 16 bytes
iNMR = aIsiMessage.GetData( sbOffset
+ NET_GSM_SIM_NMR_INFO_OFFSET_MEASUREMENTRESULTS,
16 );
// Get BCCH channel list
TUint numChannels( aIsiMessage.Get8bit( sbOffset
+ NET_GSM_SIM_NMR_INFO_OFFSET_NUMBEROFCHANNELS ) );
// Each channel takes 2 bytes
TPtrC8 bcchList( aIsiMessage.GetData(
sbOffset + NET_GSM_SIM_NMR_INFO_OFFSET_ARFCN,
2 * numChannels ) );
for ( TInt i = 0; i < bcchList.Length(); i+=2 )
{
iBCCHChannelList.Append(
bcchList[i] << 8 | bcchList[i+1] );
}
// Call local info terminal response method to send
// terminal response to the sim card.
LocalInfoTerminalResp( transId,
commandDetails,
result,
additionalInfo );
break;
}
case NET_UTRAN_SIM_NMR_INFO:
{
TUint8 reportLength( aIsiMessage.Get8bit( sbOffset
+ NET_UTRAN_SIM_NMR_INFO_OFFSET_MEASREPORTLENGTH ) );
iUtranNMR.Set( aIsiMessage.GetData(
sbOffset + NET_UTRAN_SIM_NMR_INFO_OFFSET_MEASREPORT,
reportLength ) );
LocalInfoTerminalResp( transId,
commandDetails,
result,
additionalInfo );
break;
}
default:
{
//Response included unexpected subblock
iNMR.Zero();
iBCCHChannelList.Zero();
iUtranNMR.Set( KNullDesC8 );
additionalInfo.Append( RSat::KNoService );
// Send terminal response to the sim card
LocalInfoTerminalResp( transId,
commandDetails,
RSat::KMeUnableToProcessCmd,
additionalInfo );
break;
}
}
}
else
{
// No service
iNMR.Zero();
iBCCHChannelList.Zero();
iUtranNMR.Set( KNullDesC8 );
additionalInfo.Append( RSat::KNoService );
// Send terminal response to the sim card
LocalInfoTerminalResp( transId,
commandDetails,
RSat::KMeUnableToProcessCmd,
additionalInfo );
}
// Clear local info flag
iTsySatMessaging->GetNotifyLocalInfo()->LocalInfoStatus( ETrue );
}
}
// -----------------------------------------------------------------------------
// CSatMessHandler::CallModemResourceReq
// Sends a CALL_MODEM_RESOURCE_REQ ISI message.
// -----------------------------------------------------------------------------
//
TInt CSatMessHandler::CallModemResourceReq(
TUint8 aTransId,
const TDesC8& aMsg
)
{
TFLOGSTRING("TSY:CSatMessHandler::CallModemResourceReq");
OstTrace0( TRACE_NORMAL, CSATMESSHANDLER_CALLMODEMRESOURCEREQ_TD, "TSY:CSatMessHandler::CallModemResourceReq" );
return iPnSend->Send( PN_MODEM_CALL, aTransId, CALL_MODEM_RESOURCE_REQ, aMsg );
}
// -----------------------------------------------------------------------------
// CSatMessHandler::CallModemResourceConfReq
// Sends a CALL_MODEM_RESOURCE_CONF_REQ ISI message.
// -----------------------------------------------------------------------------
//
TInt CSatMessHandler::CallModemResourceConfReq(
TUint16 aResourceId,
TUint16 aResourceIdMask )
{
TFLOGSTRING("TSY:CSatMessHandler::CallModemResourceConfReq");
OstTrace0( TRACE_NORMAL, CSATMESSHANDLER_CALLMODEMRESOURCECONFREQ_TD, "TSY:CSatMessHandler::CallModemResourceConfReq" );
TBuf8< SIZE_CALL_MODEM_RESOURCE_CONF_REQ +
SIZE_CALL_MODEM_SB_RESOURCE_CONF> msg;
// CALL_MODEM_RES_CONF_OPERATION
msg.Append( CALL_MODEM_RES_CONF_SET );
// Nbr of sb's
msg.Append( 1 );
TIsiSubBlock sbResourceConf(
msg,
CALL_MODEM_SB_RESOURCE_CONF,
EIsiSubBlockTypeId8Len8 );
TSatUtility::AppendWord( aResourceId, msg );
TSatUtility::AppendWord( aResourceIdMask, msg);
sbResourceConf.CompleteSubBlock();
return iPnSend->Send(
PN_MODEM_CALL,
iTsySatMessaging->GetTransactionId(),
CALL_MODEM_RESOURCE_CONF_REQ,
msg );
}
// -----------------------------------------------------------------------------
// CSatMessHandler::SsResourceConfReq
// Sends a SS_RESOURCE_CONF_REQ ISI message.
// -----------------------------------------------------------------------------
//
TInt CSatMessHandler::SsResourceConfReq()
{
TFLOGSTRING("TSY:CSatMessHandler::SsResourceConfReq");
OstTrace0( TRACE_NORMAL, CSATMESSHANDLER_SSRESOURCECONFREQ_TD, "TSY:CSatMessHandler::SsResourceConfReq" );
TBuf8< SIZE_SS_RESOURCE_CONF_REQ +
SIZE_SS_SB_RESOURCE_CONF > msg;
// SS_RESOURCE_CONF_OPERATION
msg.Append( SS_RESOURCE_CONF_SET );
// Nbr of sb's
msg.Append( 1 );
TIsiSubBlock sbResourceConf(
msg,
SS_SB_RESOURCE_CONF,
EIsiSubBlockTypeId8Len8 );
TSatUtility::AppendWord( SS_RES_ID_MO_SS_OPERATION, msg );
TSatUtility::AppendWord( SS_RES_ID_MO_SS_OPERATION_MASK, msg);
sbResourceConf.CompleteSubBlock();
return iPnSend->Send(
PN_SS,
iTsySatMessaging->GetTransactionId(),
SS_RESOURCE_CONF_REQ,
msg );
}
// -----------------------------------------------------------------------------
// CSatMessHandler::SsResourceControlReq
// Sends a SS_RESOURCE_CONNTROL_REQ ISI message.
// -----------------------------------------------------------------------------
//
TInt CSatMessHandler::SsResourceControlReq(
TUint8 aTransId,
const TDesC8& aMsg
)
{
TFLOGSTRING("TSY:CSatMessHandler::SsResourceControlReq");
OstTrace0( TRACE_NORMAL, CSATMESSHANDLER_SSRESOURCECONTROLREQ_TD, "TSY:CSatMessHandler::SsResourceControlReq" );
return iPnSend->Send(
PN_SS,
aTransId,
SS_RESOURCE_CONTROL_REQ,
aMsg );
}
// -----------------------------------------------------------------------------
// CSatMessHandler::GpdsResourceConfReq
// Sends a GPDS_RESOURCE_CONF_REQISI message.
// -----------------------------------------------------------------------------
//
TInt CSatMessHandler::GpdsResourceConfReq()
{
TFLOGSTRING("TSY:CSatMessHandler::GpdsResourceConfReq");
OstTrace0( TRACE_NORMAL, CSATMESSHANDLER_GPDSRESOURCECONFREQ_TD, "TSY:CSatMessHandler::GpdsResourceConfReq" );
TBuf8< SIZE_GPDS_RESOURCE_CONF_REQ +
SIZE_GPDS_RESOURCE_CONF > msg;
// SS_RESOURCE_CONF_OPERATION
msg.Append( GPDS_RESOURCE_CONF_SET );
// Nbr of sb's
msg.Append( 1 );
TIsiSubBlock sbResourceConf(
msg,
GPDS_RESOURCE_CONF,
EIsiSubBlockTypeId8Len8 );
TSatUtility::AppendWord( GPDS_RES_ID_CC_FOR_GPRS, msg );
TSatUtility::AppendWord( GPDS_RES_ID_MASK_CC_FOR_GPRS, msg);
sbResourceConf.CompleteSubBlock();
return iPnSend->Send(
PN_GPDS,
iTsySatMessaging->GetTransactionId(),
GPDS_RESOURCE_CONF_REQ,
msg );
}
// -----------------------------------------------------------------------------
// CSatMessHandler::GpdsResourceControlReq
// Sends a GPDS_RESOURCE_CONNTROL_REQ ISI message.
// -----------------------------------------------------------------------------
//
TInt CSatMessHandler::GpdsResourceControlReq(
TUint8 aTransId,
const TDesC8& aMsg
)
{
TFLOGSTRING("TSY:CSatMessHandler::GpdsResourceControlReq");
OstTrace0( TRACE_NORMAL, CSATMESSHANDLER_GPDSRESOURCECONTROLREQ_TD, "CSatMessHandler::GpdsResourceControlReq" );
return iPnSend->Send(
PN_GPDS,
aTransId,
GPDS_RESOURCE_CONTROL_REQ,
aMsg );
}
// -----------------------------------------------------------------------------
// CSatMessHandler::SetPollingInterval
// Set Polling Interval, sending a request to sim server
// -----------------------------------------------------------------------------
//
void CSatMessHandler::SetPollingInterval( TUint8 aTraId, TUint8 aValue )
{
OstTrace0( TRACE_NORMAL, CSATMESSHANDLER_SETPOLLINGINTERVAL_TD, "CSatMessHandler::SetPollingInterval" );
TFLOGSTRING("TSY:CSatMessHandler::SetPollingInterval");
iPollingInterval = aValue;
TIsiSend isiMsg( iPnSend->SendBufferDes() );
isiMsg.Set8bit( ISI_HEADER_OFFSET_RESOURCEID, PN_UICC );
isiMsg.Set8bit(
ISI_HEADER_SIZE + UICC_CAT_REQ_OFFSET_TRANSID,
aTraId );
isiMsg.Set8bit(
ISI_HEADER_SIZE + UICC_CAT_REQ_OFFSET_MESSAGEID,
UICC_CAT_REQ );
isiMsg.Set8bit(
ISI_HEADER_SIZE + UICC_CAT_REQ_OFFSET_SERVICETYPE,
UICC_CAT_POLLING_SET );
isiMsg.Set8bit(
ISI_HEADER_SIZE + UICC_CAT_REQ_OFFSET_NSB,
1 );
// Add UICC_SB_POLLING_SET
TBuf8<SIZE_UICC_SB_POLLING_SET> uiccSbPollingBuf( 0 );
TIsiSubBlock uiccSbPolling(
uiccSbPollingBuf,
UICC_SB_POLLING_SET,
EIsiSubBlockTypeId16Len16 );
// Polling interval
uiccSbPollingBuf.Append( aValue >> 8 );
uiccSbPollingBuf.Append( aValue );
// 2x filler
uiccSbPollingBuf.Append( KPadding );
uiccSbPollingBuf.Append( KPadding );
// Append subblock to ISI message
isiMsg.CopyData(
ISI_HEADER_SIZE + SIZE_UICC_CAT_REQ,
uiccSbPolling.CompleteSubBlock() );
iPnSend->Send( isiMsg.Complete() );
}
// -----------------------------------------------------------------------------
// CSatMessHandler::TimerMgmtTerminalResp
// Constructs and sends the Local information response to phonet
// -----------------------------------------------------------------------------
//
TInt CSatMessHandler::TimerMgmtTerminalResp
(
TUint8 aTransId, // Transaction id
TDes8& aCommandDetails, // command details
TUint8 aGeneralResult, // General result
TUint8 aTimerValue[3], // Timer Value
TUint8 aTimerId, // Timer Identifier
TUint8 aAdditionalInfo // Additional info
)
{
OstTrace0( TRACE_NORMAL, CSATMESSHANDLER_TIMERMGMTTERMINALRESP_TD, "CSatMessHandler::TimerMgmtTerminalResp" );
TFLOGSTRING("TSY:CSatMessHandler::TimerMgmtTerminalResp");
// Create and append response data
TTlv tlvSpecificData;
//create General Result TLV here
tlvSpecificData.AddTag( KTlvResultTag );
//General result
tlvSpecificData.AddByte( aGeneralResult );
//include timer value and id only when command is performed successfully
if( RSat::KSuccess == aGeneralResult )
{
//Timer Id
//Value KTlvTimerIdentifierTagCRBitOn ( 0xA4 ) is added,
//because used KTlvTimerIdentifierTag ( 0x24 ) doesn't
//include comprehension bit in tag the value and it is expected
//to be present in indications and terminal responses.
tlvSpecificData.AddTag( KTlvTimerIdentifierTagCRBitOn );
tlvSpecificData.AddByte( aTimerId );
//Timer value is included when the Command Qualifier is indicating
//"deactivate" or "get the current value of the timer"
if ( aCommandDetails[4] )
{
tlvSpecificData.AddTag( KTlvTimerValueTag );
//Timer value in semi-octets
tlvSpecificData.AddByte( aTimerValue[0] ); //hours
tlvSpecificData.AddByte( aTimerValue[1] ); //minutes
tlvSpecificData.AddByte( aTimerValue[2] ); //seconds
}
}
else if( RSat::KContradictionWithTimerState != aGeneralResult &&
RSat::KErrorRequiredValuesMissing != aGeneralResult &&
RSat::KCmdDataNotUnderstood != aGeneralResult &&
RSat::KCmdTypeNotUnderstood != aGeneralResult )
{
tlvSpecificData.AddByte( aAdditionalInfo );
}
else
{
TFLOGSTRING("TSY: CSatMessHandler::TimerMgmtTerminalResp, Unknown result.");
OstTrace0( TRACE_NORMAL, DUP1_CSATMESSHANDLER_TIMERMGMTTERMINALRESP_TD, "CSatMessHandler::TimerMgmtTerminalResp, Unknown result." );
}
return UiccCatReqTerminalResponse(
aCommandDetails,
tlvSpecificData.GetDataWithoutTopLevelTag(),
aTransId );
}
// -----------------------------------------------------------------------------
// CSatMessHandler::TimerExpirationInd
// Constructs TimerExpiration and calls SendAtkEnvelopeNtf to send the indication
// -----------------------------------------------------------------------------
//
TInt CSatMessHandler::TimerExpirationInd
(
TUint8 aTransId, // Transaction id
TUint8 aTimerId, // Timer Identifier
TUint8 aTimerValue[3] // Timer Value
)
{
OstTrace0( TRACE_NORMAL, CSATMESSHANDLER_TIMEREXPIRATIONIND_TD, "CSatMessHandler::TimerExpirationInd" );
TFLOGSTRING("TSY:CSatMessHandler::TimerExpirationInd");
TTlv data;
data.Begin( KBerTlvTimerExpirationTag );
//Create Device Identity TLV
//Device identity tag
data.AddTag( KTlvDeviceIdentityTag );
//Source device identity = ME
data.AddByte( KMe );
//Destination device identity = SIM
data.AddByte( KSim );
//Value KTlvTimerIdentifierTagCRBitOn ( 0xA4 ) is added,
//because used KTlvTimerIdentifierTag ( 0x24 ) doesn't
//include comprehension bit in tag the value and it is expected
//to be present in indications and terminal responses.
data.AddTag( KTlvTimerIdentifierTagCRBitOn );
data.AddByte( aTimerId);
//Timer value in semi-octets
data.AddTag( KTlvTimerValueTag );
data.AddByte( aTimerValue[0] ); //hours
data.AddByte( aTimerValue[1] ); //minutes
data.AddByte( aTimerValue[2] ); //seconds
return UiccCatReqEnvelope( aTransId, data.End() );
}
// -----------------------------------------------------------------------------
// CSatMessHandler::RefreshResultL
// Method to analyze refresh result from SIM Server.
// Called by CSatMessHandler::SimAtkResp.
// -----------------------------------------------------------------------------
//
void CSatMessHandler::RefreshResultL( TUint8 aStatus ) // UICC server status
{
OstTrace0( TRACE_NORMAL, CSATMESSHANDLER_REFRESHRESULTL_TD, "CSatMessHandler::RefreshResultL" );
TFLOGSTRING("TSY:CSatMessHandler::RefreshResultL");
TUint8 result( RSat::KSuccess );
TUint8 additionalInfo( 0 );
TInt ret( KErrNone );
if ( iRefreshRequestIsOn )
{
switch ( aStatus )
{
case UICC_STATUS_OK:
{
// Refresh is done!
TFLOGSTRING("TSY: CSatMessHandler::RefreshResultL, ISA has performed refresh successfully ");
TFLOGSTRING("TSY: CSatMessHandler::RefreshResultL, Inform S60 to re-read SIM data");
OstTrace0( TRACE_NORMAL, DUP1_CSATMESSHANDLER_REFRESHRESULTL_TD, "CSatMessHandler::RefreshResultL, ISA has performed refresh successfully " );
OstTrace0( TRACE_NORMAL, DUP2_CSATMESSHANDLER_REFRESHRESULTL_TD, "CSatMessHandler::RefreshResultL, Inform S60 to re-read SIM data" );
// Read service table
if ( CSatNotifyRefresh::KCacheEFSST &
iTsySatMessaging->GetNotifyRefresh()->CachedFiles() )
{
TInt ret( KErrNone );
// Re-read EF-UST
if ( UICC_CARD_TYPE_ICC == iCardType )
{
// Call control in USSD is supported only in SIM, from byte 10
ret = UiccReadServiceTableReq( KUiccTrIdServiceTableByte11, 10 );
User::LeaveIfError( ret );
// SMS-PP DD and Call Control from byte 7
ret = UiccReadServiceTableReq( KUiccTrIdServiceTableByte7, 6 );
User::LeaveIfError( ret );
}
else if( UICC_CARD_TYPE_UICC == iCardType )
{
// Call control, MO-SMS Control and SMS PP Datadownload, from byte 4
ret = UiccReadServiceTableReq( KUiccTrIdServiceTableByte4, 3 );
User::LeaveIfError( ret );
}
#ifdef INFO_PP_ATK_MO_SM_CONTROL
// Check MO SMS control is supported by product profile
// USIM: byte 4, SIM: byte 10
TUint8 serviceTableTrIdMoSms( KUiccTrIdServiceTableByte4 );
TUint8 serviceTableOffsetMoSms( 3 );
if ( UICC_CARD_TYPE_ICC == iCardType )
{
// Transaction ID and byte offset for SIM
serviceTableTrIdMoSms = KUiccTrIdServiceTableByte10;
serviceTableOffsetMoSms = 9;
}
if ( iMoSmsSupportedInPp )
{
// ...and by SIM service table
ret = UiccReadServiceTableReq(
serviceTableTrIdMoSms,
serviceTableOffsetMoSms );
User::LeaveIfError( ret );
}
#else
// If flag not defined, check feature availability only
// from USIM
ret = UiccReadServiceTableReq(
serviceTableTrIdMoSms,
serviceTableOffsetMoSms );
User::LeaveIfError( ret );
#endif // INFO_PP_ATK_MO_SM_CONTROL
}
break;
}
default:
{
TFLOGSTRING2("TSY: CSatMessHandler::RefreshResultL, refresh failed, UICC STATUS: 0x%x", aStatus );
OstTraceExt1( TRACE_NORMAL, DUP4_CSATMESSHANDLER_REFRESHRESULTL_TD, "CSatMessHandler::RefreshResultL, refresh failed, UICC STATUS: 0x%hhx", aStatus );
result = RSat::KMeUnableToProcessCmd;
additionalInfo = RSat::KNoSpecificMeProblem;
ret = KErrGeneral;
break;
}
}
if ( RSat::KSuccess != result )
{
// If result was not successfull then send terminal response
// Otherwise terminal response is sent by the Client.
RefreshTerminalResp(
iTsySatMessaging->GetNotifyRefresh()->GetTransactionId(),
iTsySatMessaging->GetNotifyRefresh()->GetCmdDetails(),
result,
additionalInfo );
}
// Complete refresh to the client even if it was not successfully,
// for buffer cleaning purposes. Also this way the Client will know
// that refresh was terminated.
iTsySatMessaging->GetNotifyRefresh()->CompleteRequest( ret );
// Refresh is now handled, clear refresh flag
iRefreshRequestIsOn = EFalse;
}
}
// -----------------------------------------------------------------------------
// CSatMessHandler::SendSmsReportReq
// Send a Sms-Pp report to SMS server using a request
// -----------------------------------------------------------------------------
//
void CSatMessHandler::SendSmsReportReq
(
TUint8 aTransId,
TDesC8& aData
)
{
OstTrace0( TRACE_NORMAL, CSATMESSHANDLER_SENDSMSREPORTREQ_TD, "CSatMessHandler::SendSmsReportReq" );
TFLOGSTRING("CSatMessHandler::SendSmsReportReq");
iPnSend->Send( PN_SMS, aTransId, SMS_RECEIVED_MSG_REPORT_REQ, aData );
}
// -----------------------------------------------------------------------------
// CSatMessHandler::SmsResourceConfReq
// Send a request to SMS server
// -----------------------------------------------------------------------------
//
void CSatMessHandler::SmsResoureConfReq
(
TUint8 aTransId,
TUint8 aMsgId,
TDesC8& aData
)
{
OstTrace0( TRACE_NORMAL, CSATMESSHANDLER_SMSRESOURCECONFREQ_TD, "CSatMessHandler::SmsResourceConfReq" );
TFLOGSTRING("CSatMessHandler::SmsResourceConfReq");
iPnSend->Send( PN_SMS, aTransId, aMsgId, aData );
}
// -----------------------------------------------------------------------------
// CSatMessHandler::SetPollingResult
// Sends terminal response according to the response coming from Sim server
// to a request having a service type KSimStSetPolling.
// This method handles both PollingInterval and PollingOff proactive commands.
// Called by SimAtkResp.
// -----------------------------------------------------------------------------
//
void CSatMessHandler::SetPollingResult(
TUint8 aStatus,
TUint8 aTransId,
TUint8 aInterval
)
{
OstTrace0( TRACE_NORMAL, CSATMESSHANDLER_SETPOLLINGRESULT_TD, "CSatMessHandler::SetPollingResult" );
TFLOGSTRING("TSY:CSatMessHandler::SetPollingResult ");
if ( UICC_STATUS_OK == aStatus )
{
// The response can be from a PollInterval or a PollingOff command
if ( iPollingOff )
{
TFLOGSTRING("TSY:CSatMessHandler::SetPollingResult, iPollingOff = ETrue");
OstTrace0( TRACE_NORMAL, DUP1_CSATMESSHANDLER_SETPOLLINGRESULT_TD, "CSatMessHandler::SetPollingResult, iPollingOff = ETrue" );
PollingOffTerminalResp(
aTransId,
iTsySatMessaging->GetNotifyPollingOff()->GetCmdDetails(),
RSat::KSuccess,
RSat::KNoAdditionalInfo );
}
else
{
TFLOGSTRING("TSY:CSatMessHandler::SetPollingResult, iPollingOff = EFalse");
OstTrace0( TRACE_NORMAL, DUP2_CSATMESSHANDLER_SETPOLLINGRESULT_TD, "CSatMessHandler::SetPollingResult, iPollingOff = EFalse" );
PollIntervalTerminalResp(
aTransId,
iTsySatMessaging->GetNotifyPollInterval()->GetCmdDetails(),
RSat::KSuccess,
RSat::KNoAdditionalInfo,
aInterval );
}
}
else
{
if ( iPollingOff )
{
// PollingOff was actually not executed, then set iPollingOff to false
iPollingOff = EFalse;
PollingOffTerminalResp(
aTransId,
iTsySatMessaging->GetNotifyPollingOff()->GetCmdDetails(),
RSat::KMeUnableToProcessCmd,
RSat::KNoSpecificMeProblem );
}
else
{
// If last request rejected and request was over 25 seconds,
// renew the request with legacy maximum. Otherwise there was
// an actual error
if ( iLongPollIntervalReq )
{
SetPollingInterval(aTransId, KMaxLegacyPollInterval );
iLongPollIntervalReq = EFalse;
}
else
{
PollIntervalTerminalResp(
aTransId,
iTsySatMessaging->GetNotifyPollInterval()->GetCmdDetails(),
RSat::KMeUnableToProcessCmd,
RSat::KNoSpecificMeProblem,
aInterval );
}
}
}
// Terminal Response is sent, reset flag
iLongPollIntervalReq = EFalse;
}
// -----------------------------------------------------------------------------
// CSatMessHandler::CheckProactiveCommand
// Method to check validity of received proactive command.
// Checked fields are: Proactive command tag, length, device id and
// command details tag.
// -----------------------------------------------------------------------------
//
TInt CSatMessHandler::CheckProactiveCommand
(
const TIsiReceiveC& aIsiMessage // received isi message
)
{
OstTrace0( TRACE_NORMAL, CSATMESSHANDLER_CHECKPROACTIVECOMMAND_TD, "CSatMessHandler::CheckProactiveCommand" );
TFLOGSTRING("TSY:CSatMessHandler::CheckProactiveCommand");
TTlv data;
// Get ber tlv
CBerTlv berTlv;
TBuf8<5> commandDetailsTlv; // 5 = command details data length
// BerTlv method checks Proactive command tag 'D0'.
if ( KErrNone == berTlv.BerTlv( aIsiMessage ) )
{
TInt ret( KErrNone );
TUint8 generalResult( 0 );
CTlv commandDetails;
CTlv deviceId;
// Get length part of TLV
TUint16 length( berTlv.GetLength() );
// compare TLVs length value and real length
if ( length > KOneByteLengthLimit )
{
// 5 = Proactive command tag + two byte length tag + length + SW1
// + SW2
// GetSize returns total size.
if ( ( length + 5 ) != berTlv.GetSize() )
{
// result
generalResult = RSat::KCmdDataNotUnderstood;
ret = KErrCorrupt;
}
}
// 4 = Proactive command tag + length + SW1 + SW2
else if ( ( length + 4 ) != berTlv.GetSize() )
{
// result
generalResult = RSat::KCmdDataNotUnderstood;
ret = KErrCorrupt;
}
else if ( KErrNone != CheckTlvObjects( berTlv ) )
{
// result
generalResult = RSat::KCmdDataNotUnderstood;
ret = KErrCorrupt;
}
// Check command details tlv and device id tlv
else if ( ( KErrNotFound == berTlv.TlvByTagValue( &commandDetails,
KTlvCommandDetailsTag ) )
|| ( KErrNotFound == berTlv.TlvByTagValue( &deviceId,
KTlvDeviceIdentityTag ) ) )
{
// result
generalResult = RSat::KErrorRequiredValuesMissing;
ret = KErrCorrupt;
}
// Check that len of command details is correct
else if( 5 != commandDetails.GetSize() )
{
generalResult = RSat::KCmdDataNotUnderstood;
ret = KErrCorrupt;
}
else
{
TFLOGSTRING("TSY: CSatMessHandler::CheckProactiveCommand. Proactive command Ok.");
OstTrace0( TRACE_NORMAL, DUP1_CSATMESSHANDLER_CHECKPROACTIVECOMMAND_TD, "CSatMessHandler::CheckProactiveCommand Proactive command Ok." );
}
if ( KErrCorrupt == ret )
{
if ( !berTlv.TlvByTagValue( &commandDetails,
KTlvCommandDetailsTag ) &&
5 == commandDetails.GetSize() )
{
commandDetailsTlv.Copy( commandDetails.Data() );
}
else
{
// The SIM shall interpret a Terminal Response with a command
// number '00' as belonging to the last proactive command
// having been sent to the ME.
// See 3GPP TS 11.14
commandDetailsTlv.FillZ( 5 ); // 5 = command details data length
}
data.AddTag( KTlvResultTag );
data.AddByte( generalResult );
UiccCatReqTerminalResponse(
commandDetailsTlv,
data.GetDataWithoutTopLevelTag(),
aIsiMessage.Get8bit( ISI_HEADER_OFFSET_TRANSID ) );
return KErrCorrupt;
}
return KErrNone;
}
// 'D0' is missing in the begin of the proactive command.
data.AddTag( KTlvResultTag );
// result
data.AddByte( RSat::KErrorRequiredValuesMissing );
// Set command details tlv to Zero, because method to read command details
// does not work if 'D0' is missing...
commandDetailsTlv.FillZ( 5 ); // 5 = command details data length
UiccCatReqTerminalResponse(
commandDetailsTlv,
data.GetDataWithoutTopLevelTag(),
aIsiMessage.Get8bit( ISI_HEADER_OFFSET_TRANSID ) );
return KErrCorrupt;
}
// -----------------------------------------------------------------------------
// CSatMessHandler::MoreTimeTerminalResp
// Constructs and sends the More Time response to phonet
// -----------------------------------------------------------------------------
//
TInt CSatMessHandler::MoreTimeTerminalResp
(
TUint8 aTransId, // Transaction id
TDes8& aCommandDetails, // Command details
TUint8 aGeneralResult // General result
)
{
OstTrace0( TRACE_NORMAL, CSATMESSHANDLER_MORETIMETERMINALRESP_TD, "CSatMessHandler::MoreTimeTerminalResp" );
TFLOGSTRING("TSY:CSatMessHandler::MoreTimeTerminalResp");
// Create and append response data
TTlv tlvSpecificData;
//create General Result TLV here
tlvSpecificData.AddTag( KTlvResultTag );
//General result
tlvSpecificData.AddByte( aGeneralResult );
return UiccCatReqTerminalResponse(
aCommandDetails,
tlvSpecificData.GetDataWithoutTopLevelTag(),
aTransId );
}
// -----------------------------------------------------------------------------
// CSatMessHandler::SmsCbRoutingReq
// Sends a request to Sms server to allow routing of Cell Broadcast messages.
// -----------------------------------------------------------------------------
//
TInt CSatMessHandler::SmsCbRoutingReq
(
TUint8 aTransId, // Transaction Id
TUint8 aRoutingCommand // Routing command
)
{
OstTrace0( TRACE_NORMAL, CSATMESSHANDLER_SMSCBROUTINGREQ_TD, "CSatMessHandler::SmsCbRoutingReq" );
TFLOGSTRING("TSY:CSatMessHandler::SmsRoutingReq");
TInt ret( KErrNone );
iCbRoutingReqTraId = TInt( aTransId );
// Routing is ongoing
iSmsCbRoutingComplete = EFalse;
// TBuf8<SIZE_SMS_CB_ROUTING_REQ> because we are sending [U]SIM EF CBMID Message
// Subscription;
TBuf8<SIZE_SMS_CB_ROUTING_REQ> data;
// Append Routing command
data.Append( aRoutingCommand );
// Append Subscription number
data.Append( SMS_NEW_SUBSCRIPTION );
// append Subscription type
data.Append( SMS_TYPE_SIM );
// Append Filler bytes
data.AppendFill( KPadding, 2 );
// Append no of Subblocks
data.Append( 0 );
// Send Subscription request
ret = iPnSend->Send( PN_SMS, aTransId, SMS_CB_ROUTING_REQ,
data );
return ret;
}
// -----------------------------------------------------------------------------
// CSatMessHandler::SmsCbRoutingResp
// Handles response from Sms server for a request of type SmsGsmTempCbRoutingReq.
// -----------------------------------------------------------------------------
//
void CSatMessHandler::SmsCbRoutingResp
(
const TIsiReceiveC& aIsiMessage
)
{
OstTrace0( TRACE_NORMAL, CSATMESSHANDLER_SMSCBROUTINGRESP_TD, "CSatMessHandler::SmsCbRoutingResp" );
TFLOGSTRING("TSY:CSatMessHandler::SmsCbRoutingResp");
if ( iCbRoutingReqTraId == aIsiMessage.Get8bit(
ISI_HEADER_OFFSET_TRANSID ) )
{
TUint8 cause( aIsiMessage.Get8bit(
ISI_HEADER_SIZE + SMS_CB_ROUTING_RESP_OFFSET_SMSCAUSE ) );
iCbRoutingReqTraId = KNoTransactionOngoing;
switch ( cause )
{
case SMS_ERR_CS_INACTIVE:
case SMS_ERR_SUBJECT_COUNT_OVERFLOW:
case SMS_ERR_DCS_COUNT_OVERFLOW:
{
TFLOGSTRING2("TSY:CSatMessHandler::SmsCbRoutingResp \
Routing req failed on temporary problem: %d", cause );
OstTraceExt1( TRACE_NORMAL, DUP1_CSATMESSHANDLER_SMSCBROUTINGRESP_TD, "CSatMessHandler::SmsCbRoutingResp Routing req failed on temporary problem: %hhu", cause );
iSmsCbRoutingComplete = EFalse;
break;
}
case SMS_OK:
case SMS_ERR_INVALID_SUBSCRIPTION_NR:
case SMS_ERR_INVALID_PARAMETER:
case SMS_ERR_ALL_SUBSCRIPTIONS_ALLOCATED:
default:
{
// Routing req was either completed successfully, or permanent
// problem occured. In both cases, no need to retry.
iSmsCbRoutingComplete = ETrue;
break;
}
}
}
}
// -----------------------------------------------------------------------------
// CSatMessHandler::SmsResourceConfInd
// Handles Indication from SMS Server for resource configuration Startup
// and reconfigure condition .
// -----------------------------------------------------------------------------
//
void CSatMessHandler::SmsResourceConfInd
(
const TIsiReceiveC& aIsiMessage
)
{
TFLOGSTRING("TSY:CSatMoSmsCtrl::SmsResourceConfIndReceived: Response for Resource confoguration Indication, Receive Indication from SMS server");
OstTrace0( TRACE_NORMAL, DUP1_CSATMOSMSCTRL_SMSRESOURCECONFINDRECEIVED_TD, "CSatMoSmsCtrl::SmsResourceRespReceived: Response for Resource Configuration Ind, Receive indication from SMS server" );
// To check The receive indication is for startup or reconfiguration
if ( SMS_RES_CONF_STARTUP == aIsiMessage.Get8bit( ISI_HEADER_SIZE
+ SMS_RESOURCE_CONF_IND_OFFSET_CONFSTATUS ) )
{
TUint sbStartOffset( 0 );
// Check if resource control is requested for MO SM.
if ( KErrNone == aIsiMessage.FindSubBlockOffsetById(
ISI_HEADER_SIZE + SIZE_SMS_RESOURCE_CONF_IND,
SMS_SB_RESOURCE_CONF_REQUIRED,
EIsiSubBlockTypeId16Len16,
sbStartOffset ) )
{
TUint16 resource( aIsiMessage.Get16bit( sbStartOffset +
SMS_SB_RESOURCE_CONF_REQUIRED_OFFSET_RESPP ) );
// Check MO SMS control is supported by SIM service table
if ( SMS_RES_ID_CONF_MO_SM_INIT == resource )
{
if ( UICC_CARD_TYPE_UICC == iCardType )
{
// USIM: Read MO-SMS control from byte 4
UiccReadServiceTableReq( KUiccTrIdServiceTableByte4, 3 );
}
else if ( UICC_CARD_TYPE_ICC == iCardType )
{
// SIM: Read MO-SMS control from byte 10
UiccReadServiceTableReq( KUiccTrIdServiceTableByte10, 9 );
}
}
}
}
}
// -----------------------------------------------------------------------------
// CSatMessHandler::NetCellInfoGetReq
// Creates NET_CELL_INFO_GET_REQ ISI message and sends it to Phonet
// -----------------------------------------------------------------------------
//
TInt CSatMessHandler::NetCellInfoGetReq
(
TUint8 aTransId
)
{
OstTrace0( TRACE_NORMAL, CSATMESSHANDLER_NETCELLINFOGETREQ_TD, "CSatMessHandler::NetCellInfoGetReq" );
TFLOGSTRING("TSY:CSatMessHandler::NetCellInfoGetReq");
TBuf8<1> noData;
return iPnSend->Send(
PN_MODEM_NETWORK,
aTransId,
NET_CELL_INFO_GET_REQ,
noData );
}
// -----------------------------------------------------------------------------
// CSatMessHandler::NetCellInfoGetResp
// Breaks a NET_CELL_INFO_GET_RESP ISI-message and if this response is for
// local info proactive command then send a terminal response to the sim card.
// -----------------------------------------------------------------------------
//
void CSatMessHandler::NetCellInfoGetResp
(
const TIsiReceiveC& aIsiMessage
)
{
OstTrace0( TRACE_NORMAL, CSATMESSHANDLER_NETCELLINFOGETRESP_TD, "CSatMessHandler::NetCellInfoGetResp" );
TFLOGSTRING("TSY: CSatMessHandler::NetCellInfoGetResp");
TUint8 successCode( aIsiMessage.Get8bit(
ISI_HEADER_SIZE + NET_CELL_INFO_GET_RESP_OFFSET_SUCCESSCODE ) );
TBuf<1> additionalInfo;
additionalInfo.Zero();
// Default result
TUint8 result( RSat::KMeUnableToProcessCmd );
// Store recieved network parameters
TInt retValue( StoreNetServiceStatus( aIsiMessage ) );
if ( iTsySatMessaging->GetNotifyLocalInfo()->LocalInfoAccTechStatus() )
{
if ( NET_CAUSE_OK == successCode )
{
if ( KErrNone == retValue )
{
if ( NET_SERVICE == iLocInfo.iRegStatus
|| NET_LIMITED_SERVICE == iLocInfo.iRegStatus )
{
result = RSat::KSuccess;
}
else
{
// No service.
additionalInfo.Append( RSat::KNoService );
}
}
// No else, result already set.
}
// No else, result already set.
// Clear local info access technology flag
iTsySatMessaging->GetNotifyLocalInfo()->LocalInfoAccTechStatus( ETrue );
}
else
{
switch ( iLocInfo.iRegStatus )
{
case NET_SERVICE:
{
result = RSat::KSuccess;
break;
}
case NET_LIMITED_SERVICE:
{
result = RSat::KSuccessLimitedService;
break;
}
case NET_NO_COVERAGE:
{
// Default result value already set
additionalInfo.Append( RSat::KNoService );
break;
}
default:
{
// Default result value already set
TFLOGSTRING2("TSY: CSatMessHandler::NetCellInfoGetResp - Unexpected iRegStatus: %d", iLocInfo.iRegStatus );
OstTrace1( TRACE_NORMAL, DUP1_CSATMESSHANDLER_NETCELLINFOGETRESP_TD, "CSatMessHandler::NetCellInfoGetResp Unexpected iRegStatus: %d", iLocInfo.iRegStatus );
additionalInfo.Append( RSat::KNoSpecificMeProblem );
break;
}
}
}
TInt trId( aIsiMessage.Get8bit( ISI_HEADER_OFFSET_TRANSID ) );
// Check if this response is for provide local info proactive command.
if ( iTsySatMessaging->GetNotifyLocalInfo()->LocalInfoStatus()
&& iTsySatMessaging->GetNotifyLocalInfo()->GetTransactionId()
== trId )
{
// Send terminal response
LocalInfoTerminalResp(
iTsySatMessaging->GetNotifyLocalInfo()->GetTransactionId(),
iTsySatMessaging->GetNotifyLocalInfo()->GetCmdDetails(),
result,
additionalInfo );
// Clear local info flag
iTsySatMessaging->GetNotifyLocalInfo()->LocalInfoStatus( ETrue );
}
}
// -----------------------------------------------------------------------------
// CSatMessHandler::GssCsServiceReq
// Constructs GSS_CS_SERVICE_REQ ISI message.
// -----------------------------------------------------------------------------
//
TInt CSatMessHandler::GssCsServiceReq
(
TUint8 aTransId, // Transaction Id
TUint8 aOperation // Gss operation
)
{
OstTrace0( TRACE_NORMAL, CSATMESSHANDLER_GSSCSSERVICEREQ_TD, "CSatMessHandler::GssCsServiceReq" );
TFLOGSTRING("TSY: CSatMessHandler::GssCsServiceReq ");
TBuf8<2> data;
data.Append( aOperation );
data.Append( 0x00 ); // number of subblocks
return iPnSend->Send( PN_GSS, aTransId, GSS_CS_SERVICE_REQ, data );
}
// -----------------------------------------------------------------------------
// CSatMessHandler::GssCsServiceResp
// Breaks GSS_CS_SERVICE_RESP ISI message.
// -----------------------------------------------------------------------------
//
void CSatMessHandler::GssCsServiceResp
(
const TIsiReceiveC& aIsiMessage // Received isi messge
)
{
OstTrace0( TRACE_NORMAL, CSATMESSHANDLER_GSSCSSERVICERESP_TD, "CSatMessHandler::GssCsServiceResp" );
TFLOGSTRING("CSatMessHandler::GssCsServiceResp ");
if ( iTsySatMessaging->GetNotifyLocalInfo()->LocalInfoStatus() )
{
TUint8 generalResult ( RSat::KSuccess );
// Provide local info proactive command is ongoing
TBuf<1> additionalInfo;
additionalInfo.Zero();
// Get transaction id
TUint8 transId(
iTsySatMessaging->GetNotifyLocalInfo()->GetTransactionId() );
// Get command details tlv
TBuf8<5> commandDetails;
commandDetails =
iTsySatMessaging->GetNotifyLocalInfo()->GetCmdDetails();
// If this is a Timing advance response and message includes subblocks
if ( GSS_ATK_TIMING_ADVANCE_GET == aIsiMessage.Get8bit(
ISI_HEADER_SIZE + GSS_CS_SERVICE_RESP_OFFSET_OPERATION )
&&
0 < aIsiMessage.Get8bit(
ISI_HEADER_SIZE + GSS_CS_SERVICE_RESP_OFFSET_NBROFSUBBLOCKS ) )
{
// GSS_ATK_TIMING_ADVANCE sub block
// SubBlock offset
TUint sbOffset( 0 );
if ( KErrNone == aIsiMessage.FindSubBlockOffsetById(
ISI_HEADER_SIZE + SIZE_GSS_CS_SERVICE_RESP,
GSS_ATK_TIMING_ADVANCE,
EIsiSubBlockTypeId8Len8,
sbOffset) )
{
// Store Timing Advance Status
iTaStatus = aIsiMessage.Get8bit(
sbOffset + GSS_ATK_TIMING_ADVANCE_OFFSET_TASTATUS );
TFLOGSTRING2("TSY: CSatMessHandler::GssCsServiceResp iTaStatus=%d", iTaStatus);
OstTraceExt1( TRACE_NORMAL, DUP1_CSATMESSHANDLER_GSSCSSERVICERESP_TD, "CSatMessHandler::GssCsServiceResp iTaStatus: %hhu", iTaStatus );
// Store timing advance
iTimingAdvance = aIsiMessage.Get8bit(
sbOffset + GSS_ATK_TIMING_ADVANCE_OFFSET_TIMINGADVANCE );
TFLOGSTRING2("TSY: CSatMessHandler::GssCsServiceResp \
iTimingAdvance=%d", iTimingAdvance);
OstTraceExt1( TRACE_NORMAL, DUP2_CSATMESSHANDLER_GSSCSSERVICERESP_TD, "CSatMessHandler::GssCsServiceResp iTimingAdvance: %hhu", iTimingAdvance );
if ( GSS_TIMING_ADVANCE_NOT_AVAILABLE == iTimingAdvance )
{
generalResult = RSat::KMeUnableToProcessCmd;
}
}
else
{
generalResult = RSat::KErrorRequiredValuesMissing;
}
// Call local info terminal response method to send
// terminal response to the sim card.
LocalInfoTerminalResp( transId,
commandDetails,
generalResult,
additionalInfo );
// Clear local info flag
iTsySatMessaging->GetNotifyLocalInfo()->LocalInfoStatus( ETrue );
}
else
{
// No service
additionalInfo.Append( RSat::KNoService );
// Clear local info flag
iTsySatMessaging->GetNotifyLocalInfo()->LocalInfoStatus( ETrue );
// Call local info terminal response method to send
// terminal response to the sim card.
LocalInfoTerminalResp( transId,
commandDetails,
RSat::KMeUnableToProcessCmd,
additionalInfo );
}
}
}
// -----------------------------------------------------------------------------
// CSatMessHandler::GssCsServiceFailResp
// Breaks a GSS_CS_SERVICE_FAIL_RESP ISI message.
// -----------------------------------------------------------------------------
//
void CSatMessHandler::GssCsServiceFailResp
(
const TIsiReceiveC& aIsiMessage // Received isi messge
)
{
OstTrace0( TRACE_NORMAL, CSATMESSHANDLER_GSSCSSERVICEFAILRESP_TD, "CSatMessHandler::GssCsServiceFailResp" );
TFLOGSTRING("CSatMessHandler::GssCsServiceFailResp ");
if ( iTsySatMessaging->GetNotifyLocalInfo()->LocalInfoStatus() )
{
if ( GSS_ATK_TIMING_ADVANCE_GET == aIsiMessage.Get8bit(
ISI_HEADER_SIZE + GSS_CS_SERVICE_RESP_OFFSET_OPERATION ) )
{
TBuf<1> additionalInfo;
additionalInfo.Zero();
additionalInfo.Append( RSat::KNoService );
// Get transaction id
TUint8 transId(
iTsySatMessaging->GetNotifyLocalInfo()->GetTransactionId() );
// Get command details tlv
TBuf8<5> commandDetails;
commandDetails =
iTsySatMessaging->GetNotifyLocalInfo()->GetCmdDetails();
// Call local info terminal response method to send
// terminal response to the sim card.
LocalInfoTerminalResp( transId,
commandDetails,
RSat::KMeUnableToProcessCmd,
additionalInfo );
// Clear local info flag
iTsySatMessaging->GetNotifyLocalInfo()->LocalInfoStatus( ETrue );
}
}
}
// -----------------------------------------------------------------------------
// CSatMessHandler::LanguageNotificationTerminalResp
// Constructs LanguageNotification specific part of terminal
// response and calls SendTerminalResponse to send the terminal response
// -----------------------------------------------------------------------------
//
TInt CSatMessHandler::LanguageNotificationTerminalResp
(
TUint8 aTransId, // Transaction id
TDes8& aCommandDetails, // Comamnd number
TUint8 aGeneralResult, // General result
TUint8 aAdditionalInfo // additional info
)
{
OstTrace0( TRACE_NORMAL, CSATMESSHANDLER_LANGUAGENOTIFICATIONTERMINALRESP_TD, "CSatMessHandler::LanguageNotificationTerminalResp" );
TFLOGSTRING("TSY:CSatMessHandler::LanguageNotificationTerminalResp");
TTlv tlvSpecificData;
// Create general result TLV here
tlvSpecificData.AddTag( KTlvResultTag );
// General result
tlvSpecificData.AddByte( aGeneralResult );
if ( RSat::KSuccess != aGeneralResult )
{
tlvSpecificData.AddByte( aAdditionalInfo );
}
return UiccCatReqTerminalResponse(
aCommandDetails,
tlvSpecificData.GetDataWithoutTopLevelTag(),
aTransId );
}
// -----------------------------------------------------------------------------
// CSatMessHandler::NetTimeInd
// Break's a NET_TIME_IND isi-message and stores time zone information.
// Time zone is needed in provide local information proactive command.
// -----------------------------------------------------------------------------
//
void CSatMessHandler::NetTimeInd
(
const TIsiReceiveC& aIsiMessage
)
{
OstTrace0( TRACE_NORMAL, CSATMESSHANDLER_NETTIMEIND_TD, "CSatMessHandler::NetTimeInd" );
TFLOGSTRING("TSY: CSatMessHandler::NetTimeInd");
// NET_TIME_INFO is mandatory sub block
// SubBlock offset
TUint sbOffset( 0 );
// Find NET_TIME_INFO subblock
TInt ret ( aIsiMessage.FindSubBlockOffsetById(
ISI_HEADER_SIZE + SIZE_NET_TIME_IND,
NET_TIME_INFO,
EIsiSubBlockTypeId8Len8,
sbOffset ) );
if ( KErrNone == ret )
{
// Get timezone
// If the time zone is invalid or time zone is unknown, all bits are
// set to 1 (including B6).
iTimeZone = aIsiMessage.Get8bit( sbOffset + NET_TIME_INFO_OFFSET_TIMEZONE );
TFLOGSTRING2("TSY: CSatMessHandler::NetTimeInd, Time zone: 0x%x", iTimeZone );
OstTraceExt1( TRACE_NORMAL, DUP1_CSATMESSHANDLER_NETTIMEIND_TD, "CSatMessHandler::NetTimeInd Time zone: %hhu", iTimeZone );
}
}
// -----------------------------------------------------------------------------
// CSatMessHandler::OpenChannelTerminalResp
// Constructs Open Channel specific part of terminal
// response and calls SendTerminalResponse to send the terminal response.
// -----------------------------------------------------------------------------
//
TInt CSatMessHandler::OpenChannelTerminalResp
(
TUint8 aTransId, // Transaction Id
TDes8& aCommandDetails, // Command details
TUint8 aGeneralResult, // General Result
TDes8& aAdditionalInfo, // Additional Info
TUint8 aBearerType, // Bearer type
TDesC8& aBearer, // Bearer
TUint16 aBufferSize // Buffer size
)
{
OstTrace0( TRACE_NORMAL, CSATMESSHANDLER_OPENCHANNELTERMINALRESP_TD, "CSatMessHandler::OpenChannelTerminalResp" );
TFLOGSTRING("CSatMessHandler::OpenChannelTerminalResp");
// Create and append response data
TTlv tlvSpecificData;
//create General Result TLV here
tlvSpecificData.AddTag( KTlvResultTag );
//General result
tlvSpecificData.AddByte( aGeneralResult );
if ( ( RSat::KMeUnableToProcessCmd == aGeneralResult )
|| ( RSat::KNetworkUnableToProcessCmd == aGeneralResult )
|| ( RSat::KInteractionWithCCPermanentError == aGeneralResult )
|| ( RSat::KErrorRequiredValuesMissing == aGeneralResult )
|| ( RSat::KBearerIndepProtocolError == aGeneralResult ) )
{
if( aAdditionalInfo.Length())
// UNSuccessful result neccessitating additional info byte
tlvSpecificData.AddByte( aAdditionalInfo[1] );
}
else if ( RSat::KSuccess == aGeneralResult
|| ( RSat::KPartialComprehension == aGeneralResult )
|| ( RSat::KMissingInformation == aGeneralResult )
|| ( RSat::KPerformedWithModifications == aGeneralResult )
|| ( RSat::KSuccessRequestedIconNotDisplayed == aGeneralResult ) )
{
// Successful result: append Channel Status using
// additional info.
for ( TInt i=0; i<aAdditionalInfo.Length();i+=4 )
{
tlvSpecificData.AddTag( KTlvChannelStatusTag );
tlvSpecificData.AddByte( aAdditionalInfo[i+1] );
tlvSpecificData.AddByte( aAdditionalInfo[i+3] );
}
}
else
{
TFLOGSTRING("TSY: CSatMessHandler::OpenChannelTerminalResp, General result did not match.");
OstTrace0( TRACE_NORMAL, DUP1_CSATMESSHANDLER_OPENCHANNELTERMINALRESP_TD, "CSatMessHandler::OpenChannelTerminalResp, General result did not match." );
}
// For any result:
// Append Bearer Description data
if ( aBearer.Length() )
{
tlvSpecificData.AddTag( KTlvBearerDescriptionTag );
tlvSpecificData.AddByte( aBearerType );
tlvSpecificData.AddData( aBearer );
}
else
{
// Well, if Sat Server doesn't provide it,
// then what values should we use in here??
}
// Append Buffer Size
tlvSpecificData.AddTag( KTlvBufferSizeTag );
tlvSpecificData.AddByte( TUint8( (aBufferSize&0xFF00)>>8 ));
tlvSpecificData.AddByte( TUint8( aBufferSize&0x00FF ) );
return UiccCatReqTerminalResponse(
aCommandDetails,
tlvSpecificData.GetDataWithoutTopLevelTag(),
aTransId );
}
// -----------------------------------------------------------------------------
// CSatMessHandler::GetChannelStatusTerminalResp
// Constructs Get Channel Status specific part of terminal
// response and calls SendTerminalResponse method to send it.
// -----------------------------------------------------------------------------
//
TInt CSatMessHandler::GetChannelStatusTerminalResp
(
TUint8 aTransId,
TDes8 &aCommandDetails,
TUint8 aGeneralResult,
const TDes8& aAdditionalInfo
)
{
OstTrace0( TRACE_NORMAL, CSATMESSHANDLER_GETCHANNELSTATUSTERMINALRESP_TD, "CSatMessHandler::GetChannelStatusTerminalResp" );
TFLOGSTRING("CSatMessHandler::GetChannelStatusTerminalResp");
TTlv tlvSpecificData;
// Append general result tag
tlvSpecificData.AddTag( KTlvResultTag );
// Append general result
tlvSpecificData.AddByte( aGeneralResult );
if ( ( RSat::KMeUnableToProcessCmd == aGeneralResult )
|| ( RSat::KNetworkUnableToProcessCmd == aGeneralResult )
|| ( RSat::KInteractionWithCCPermanentError == aGeneralResult )
|| ( RSat::KErrorRequiredValuesMissing == aGeneralResult )
|| ( RSat::KBearerIndepProtocolError == aGeneralResult ) )
{
// UNSuccessful result neccessitating additional info byte
tlvSpecificData.AddData( aAdditionalInfo );
}
else if ( RSat::KSuccess == aGeneralResult )
{
// Length check is carried out in
// CSatNotifyGetChannelStatus::TerminalResponseL
for ( TInt i=0; i<aAdditionalInfo.Length();i+=4 )
{
tlvSpecificData.AddTag( KTlvChannelStatusTag );
tlvSpecificData.AddByte( aAdditionalInfo[i+1] );
tlvSpecificData.AddByte( aAdditionalInfo[i+3] );
}
}
else
{
TFLOGSTRING("CSatMessHandler::GetChannelStatusTerminalResp - mandatory channel status missing");
OstTrace0( TRACE_NORMAL, DUP1_CSATMESSHANDLER_GETCHANNELSTATUSTERMINALRESP_TD, "CSatMessHandler::GetChannelStatusTerminalResp - mandatory channel status missing" );
}
return UiccCatReqTerminalResponse(
aCommandDetails,
tlvSpecificData.GetDataWithoutTopLevelTag(),
aTransId );
}
// -----------------------------------------------------------------------------
// CSatMessHandler::CloseChannelTerminalResp
// Constructs Close Channel specific part of terminal
// response and calls SendTerminalResponse method to send it.
// -----------------------------------------------------------------------------
//
TInt CSatMessHandler::CloseChannelTerminalResp
(
TUint8 aTransId,
TDes8 &aCommandDetails,
TUint8 aGeneralResult,
const TDes8& aAdditionalInfo
)
{
OstTrace0( TRACE_NORMAL, CSATMESSHANDLER_CLOSECHANNELTERMINALRESP_TD, "CSatMessHandler::CloseChannelTerminalResp" );
TFLOGSTRING("CSatMessHandler::CloseChannelTerminalResp");
TTlv tlvSpecificData;
// Append general result tag
tlvSpecificData.AddTag( KTlvResultTag );
// Append general result
tlvSpecificData.AddByte( aGeneralResult );
if ( ( RSat::KMeUnableToProcessCmd == aGeneralResult )
|| ( RSat::KNetworkUnableToProcessCmd == aGeneralResult )
|| ( RSat::KInteractionWithCCPermanentError == aGeneralResult )
|| ( RSat::KErrorRequiredValuesMissing == aGeneralResult )
|| ( RSat::KBearerIndepProtocolError == aGeneralResult ) )
{
// UNSuccessful result neccessitating additional info byte
tlvSpecificData.AddData( aAdditionalInfo );
}
// Successful result: no additional info,
// no parameters
return UiccCatReqTerminalResponse(
aCommandDetails,
tlvSpecificData.GetDataWithoutTopLevelTag(),
aTransId );
}
// -----------------------------------------------------------------------------
// CSatMessHandler::SendDataTerminalResp
// Constructs Send Data specific part of terminal
// response and calls SendTerminalResponse method to send it.
// -----------------------------------------------------------------------------
//
TInt CSatMessHandler::SendDataTerminalResp
(
TUint8 aTransId,
TDes8 &aCommandDetails,
TUint8 aGeneralResult,
const TDes8& aAdditionalInfo,
TUint8 aChannelDataLength
)
{
OstTrace0( TRACE_NORMAL, CSATMESSHANDLER_SENDDATATERMINALRESP_TD, "CSatMessHandler::SendDataTerminalResp" );
TFLOGSTRING("CSatMessHandler::SendDataTerminalResp");
TTlv tlvSpecificData;
// Append general result tag
tlvSpecificData.AddTag( KTlvResultTag );
// Append general result
tlvSpecificData.AddByte( aGeneralResult );
if ( ( RSat::KMeUnableToProcessCmd == aGeneralResult )
|| ( RSat::KNetworkUnableToProcessCmd == aGeneralResult )
|| ( RSat::KInteractionWithCCPermanentError == aGeneralResult )
|| ( RSat::KErrorRequiredValuesMissing == aGeneralResult )
|| ( RSat::KBearerIndepProtocolError == aGeneralResult ) )
{
// UNSuccessful result neccessitating additional info byte
tlvSpecificData.AddData( aAdditionalInfo );
}
else if (( RSat::KSuccess == aGeneralResult )
|| ( RSat::KSuccessRequestedIconNotDisplayed == aGeneralResult ))
{
// Successful result:
// append Channel Status
tlvSpecificData.AddTag( KTlvChannelDataLengthTag );
tlvSpecificData.AddByte( aChannelDataLength );
}
else
{
TFLOGSTRING("TSY: CSatMessHandler::SendDataTerminalResp, General result did not match.");
OstTrace0( TRACE_NORMAL, DUP1_CSATMESSHANDLER_SENDDATATERMINALRESP_TD, "CSatMessHandler::SendDataTerminalResp, General result did not match." );
}
return UiccCatReqTerminalResponse(
aCommandDetails,
tlvSpecificData.GetDataWithoutTopLevelTag(),
aTransId );
}
// -----------------------------------------------------------------------------
// CSatMessHandler::ReceiveDataTerminalResp
// Constructs Receive Data specific part of terminal
// response and calls SendTerminalResponse method to send it.
// -----------------------------------------------------------------------------
//
TInt CSatMessHandler::ReceiveDataTerminalResp
(
TUint8 aTransId,
TDes8& aCommandDetails,
TUint8 aGeneralResult,
const TDes8& aAdditionalInfo,
TUint8 aChannelDataLength
)
{
OstTrace0( TRACE_NORMAL, CSATMESSHANDLER_RECEIVEDATATERMINALRESP_TD, "CSatMessHandler::ReceiveDataTerminalResp" );
TFLOGSTRING("CSatMessHandler::ReceiveDataTerminalResp");
TTlv tlvSpecificData;
// Append general result tag
tlvSpecificData.AddTag( KTlvResultTag );
// Append general result
tlvSpecificData.AddByte( aGeneralResult );
if ( ( RSat::KMeUnableToProcessCmd == aGeneralResult )
|| ( RSat::KNetworkUnableToProcessCmd == aGeneralResult )
|| ( RSat::KInteractionWithCCPermanentError == aGeneralResult )
|| ( RSat::KErrorRequiredValuesMissing == aGeneralResult )
|| ( RSat::KBearerIndepProtocolError == aGeneralResult ) )
{
// UNSuccessful result neccessitating additional info byte
tlvSpecificData.AddData( aAdditionalInfo );
}
else if (( RSat::KSuccess == aGeneralResult )
|| ( RSat::KSuccessRequestedIconNotDisplayed == aGeneralResult )
|| ( RSat::KMissingInformation == aGeneralResult ))
{
// Successful result:
//append Channel Data using additional info
tlvSpecificData.AddTag( KTlvChannelDataTag );
tlvSpecificData.AddData( aAdditionalInfo );
// Channel data length
tlvSpecificData.AddTag( KTlvChannelDataLengthTag );
tlvSpecificData.AddByte( aChannelDataLength );
}
else
{
TFLOGSTRING("TSY: CSatMessHandler::ReceiveDataTerminalResp, General result did not match.");
OstTrace0( TRACE_NORMAL, DUP1_CSATMESSHANDLER_RECEIVEDATATERMINALRESP_TD, "CSatMessHandler::ReceiveDataTerminalResp, General result did not match." );
}
return UiccCatReqTerminalResponse(
aCommandDetails,
tlvSpecificData.GetDataWithoutTopLevelTag(),
aTransId );
}
// -----------------------------------------------------------------------------
// CSatMessHandler::SendSmsResourceReq
// Send a response to SMS server after reception of SmsResourceInd.
// This response tells whether the SMS can be sent or not.
// -----------------------------------------------------------------------------
//
TInt CSatMessHandler::SendSmsResourceReq
(
TUint8 aTransId,
TDesC8& aData,
TUint8 aReceiverObject
)
{
OstTrace0( TRACE_NORMAL, CSATMESSHANDLER_SENDSMSRESOURCERESP_TD, "CSatMessHandler::SendSmsResourceResp" );
TFLOGSTRING("TSY:CSatMessHandler::SendSmsResourceResp");
TIsiSend isimsg( iPnSend->SendBufferDes() );
isimsg.Set8bit( ISI_HEADER_OFFSET_RECEIVEROBJECT, aReceiverObject );
isimsg.Set8bit( ISI_HEADER_OFFSET_RESOURCEID, PN_SMS );
isimsg.Set8bit( ISI_HEADER_OFFSET_TRANSID , aTransId );
isimsg.Set8bit( ISI_HEADER_OFFSET_MESSAGEID, SMS_RESOURCE_REQ );
isimsg.CopyData( ISI_HEADER_SIZE + SMS_RESOURCE_REQ_OFFSET_FILLERBYTE1,
aData );
// add padding
while ( iPnSend->SendBufferDes().Length() % 4 )
{
iPnSend->SendBufferDes().Append( 0x00 );
}
//send message
return iPnSend->Send( isimsg.Complete() );
}
// -----------------------------------------------------------------------------
// CSatMessHandler::SsStatusInd
// Break's a SS_STATUS_IND isi-message and stores status information
// -----------------------------------------------------------------------------
//
void CSatMessHandler::SsStatusInd
(
const TIsiReceiveC& aIsiMessage
)
{
OstTrace0( TRACE_NORMAL, CSATMESSHANDLER_SSSTATUSIND_TD, "CSatMessHandler::SsStatusInd" );
TFLOGSTRING("TSY: CSatMessHandler::SsStatusInd");
TUint8 ssStatus = aIsiMessage.Get8bit( ISI_HEADER_SIZE
+ SS_STATUS_IND_OFFSET_SSSTATUSINDICATION );
if( ( SS_STATUS_REQUEST_SERVICE_BUSY == ssStatus )
|| ( SS_STATUS_REQUEST_SERVICE_START == ssStatus ) )
{
iSsStatus = ESsBusy;
}
else if( ( SS_GSM_STATUS_REQUEST_USSD_BUSY == ssStatus )
|| ( SS_GSM_STATUS_REQUEST_USSD_START == ssStatus ) )
{
iSsStatus = EUssdBusy;
}
else
{
iSsStatus = ENotBusy;
}
}
// -----------------------------------------------------------------------------
// CSatMessHandler::AdditionalInfoNeeded
// Checks if given result requires an additional info byte(s)
// -----------------------------------------------------------------------------
//
TBool CSatMessHandler::AdditionalInfoNeeded
(
const TUint8 aGeneralResult
)
{
OstTrace0( TRACE_NORMAL, CSATMESSHANDLER_ADDITIONALINFONEEDED_TD, "CSatMessHandler::AdditionalInfoNeeded" );
// NOTE: This method shall not be used with SendSS proactive command as its
// additional info handling differs from other commands.
TBool ret( EFalse );
switch ( aGeneralResult )
{
// This list is based on 3GPP TS 11.14 chapter 12.12
case RSat::KMeUnableToProcessCmd:
case RSat::KNetworkUnableToProcessCmd:
case RSat::KLaunchBrowserError:
case RSat::KSsReturnError:
case RSat::KSmsRpError:
case RSat::KUssdReturnError:
case RSat::KMultipleCardCmdsError:
case RSat::KInteractionWithCCPermanentError:
case RSat::KBearerIndepProtocolError:
{
ret = ETrue;
break;
}
default:
{
// do nothing. ret is already set to EFalse
break;
}
}
return ret;
}
// -----------------------------------------------------------------------------
// CSatMessHandler:: ReceiveMessageL
// Called by phonet receiver when an ISI message
// has been received
// -----------------------------------------------------------------------------
//
void CSatMessHandler::ReceiveMessageL
(
const TIsiReceiveC& aIsiMessage
)
{
OstTrace0( TRACE_NORMAL, CSATMESSHANDLER_RECEIVEMESSAGEL_TD, "CSatMessHandler::ReceiveMessageL" );
TFLOGSTRING("TSY: CSatMessHandler::ReceiveMessageL");
// Get ISI message resource and id
TInt resource ( aIsiMessage.Get8bit( ISI_HEADER_OFFSET_RESOURCEID ) );
// Received AtkSwDataNtf-message can be response for an envelope
// or terminal response. Responses for TR and failed envelopes (SIM busy)
// are handled in AtkServerMessageReceivedL. All other cases are passed
// ProactiveProcedureMessageReceivedL-method
TBool handled( EFalse );
switch ( resource )
{
case PN_SS:
{
SsServerMessageReceived( aIsiMessage );
break;
}
/*case PN_PHONE_INFO:
{
PhoneInfoMessageReceivedL( aIsiMessage );
break;
}*/
case PN_MODEM_NETWORK:
{
NetServerMessageReceived( aIsiMessage );
break;
}
case PN_GSS:
{
GsmStackServerMessageReceived( aIsiMessage );
break;
}
case PN_SMS:
{
SmsServerMessageReceived( aIsiMessage );
break;
}
case PN_UICC:
{
handled = UiccServerMessageReceivedL( aIsiMessage );
break;
}
default:
{
// Do nothing
break;
}
}
if ( !handled )
{
ProactiveProcedureMessageReceivedL( aIsiMessage );
}
}
// -----------------------------------------------------------------------------
// CSatMessHandler::HandleError
// Handles CSatMessHandler's errors that comes via PhoNetReceiver
// RunError method.
// -----------------------------------------------------------------------------
//
void CSatMessHandler::HandleError
(
const TIsiReceiveC& /*aIsiMessage*/,
TInt /*aErrorCode*/
)
{
OstTrace0( TRACE_NORMAL, CSATMESSHANDLER_HANDLEERROR_TD, "CSatMessHandler::HandleError" );
// No implementation
}
// -----------------------------------------------------------------------------
// CSatMessHandler::NetRatInd
// Breaks a NET_RAT_IND isi-message
// -----------------------------------------------------------------------------
//
void CSatMessHandler::NetRatInd
(
const TIsiReceiveC& aIsiMessage // ISI message
)
{
OstTrace0( TRACE_NORMAL, CSATMESSHANDLER_NETRATIND_TD, "CSatMessHandler::NetRatInd" );
TFLOGSTRING("TSY:CSatMessHandler::NetRatInd");
// Check the presence of subblocks
if ( 0 != aIsiMessage.Get8bit(
ISI_HEADER_SIZE + NET_RAT_IND_OFFSET_SUBBLOCKCOUNT ) )
{
// Subblock offset
TUint sbOffset( 0 );
// NET_RAT_INFO sub block
TInt ret = aIsiMessage.FindSubBlockOffsetById(
ISI_HEADER_SIZE + SIZE_NET_RAT_IND,
NET_RAT_INFO,
EIsiSubBlockTypeId8Len8,
sbOffset );
// Check if NET_RAT_INFO sub block is present
if( KErrNone == ret )
{
// Get ratName
TUint8 ratName( aIsiMessage.Get8bit(
sbOffset + NET_RAT_INFO_OFFSET_RATNAME ) );
switch ( ratName )
{
case NET_GSM_RAT:
{
iCurrentAccTech = KNetworkModeGsm;
iTsySatMessaging->GetEventDownload()
->SendAccessTechnologyChangeEnvelope( KNetworkModeGsm );
break;
}
case NET_UMTS_RAT:
{
iCurrentAccTech = KNetworkModeUtran;
iTsySatMessaging->GetEventDownload()
->SendAccessTechnologyChangeEnvelope( KNetworkModeUtran );
break;
}
default:
{
// Do nothing
break;
}
}
}
TFLOGSTRING2("TSY:CSatMessHandler::NetRatInd - Current Acc Tech: %d",iCurrentAccTech);
OstTraceExt1( TRACE_NORMAL, DUP1_CSATMESSHANDLER_NETRATIND_TD, "CSatMessHandler::NetRatInd - Current Acc Tech: %hhu", iCurrentAccTech );
}
}
// -----------------------------------------------------------------------------
// CSatMessHandler::LocationInfo
// Getter for location information structure
// -----------------------------------------------------------------------------
//
const CSatMessHandler::TLocationInfo& CSatMessHandler::LocationInfo()
{
OstTrace0( TRACE_NORMAL, CSATMESSHANDLER_LOCATIONINFO_TD, "CSatMessHandler::LocationInfo" );
// Extended Cell Id is provided only if both USIM and
// 3G network are present.
if ( KNetworkModeUtran != iCurrentAccTech
|| UICC_CARD_TYPE_UICC != iCardType )
{
// Exclude the extended Cell Id
iLocInfo.iCellId.SetLength( 2 );
}
else
{
iLocInfo.iCellId.SetLength( 4 );
}
return iLocInfo;
}
// -----------------------------------------------------------------------------
// CSatMessHandler::UiccApplCmdResp
// (other items were commented in a header).
// -----------------------------------------------------------------------------
//
void CSatMessHandler::UiccApplCmdResp( const TIsiReceiveC& aIsiMessage )
{
TFLOGSTRING("TSY: CSatMessHandler::UiccApplCmdResp");
OstTrace0( TRACE_NORMAL, CSATMESSHANDLER_UICCAPPLCMDRESP_TD, "CSatMessHandler::UiccApplCmdResp" );
TInt error( KErrNone );
// Get transaction ID, status and service type
TUint8 trId( aIsiMessage.Get8bit(
ISI_HEADER_SIZE + UICC_APPL_CMD_RESP_OFFSET_TRANSID ) );
TUint8 status( aIsiMessage.Get8bit(
ISI_HEADER_SIZE + UICC_APPL_CMD_RESP_OFFSET_STATUS ) );
TUint8 serviceType( aIsiMessage.Get8bit(
ISI_HEADER_SIZE +
UICC_APPL_CMD_RESP_OFFSET_SERVICETYPE ) );
// Card type
iCardType = aIsiMessage.Get8bit(
ISI_HEADER_SIZE + UICC_APPL_CMD_RESP_OFFSET_CARDTYPE );
// Read file data from UICC_SB_FILE_DATA
TInt fileDataLength( 0 );
TPtrC8 fileData;
TUint uiccSbFileDataOffset( 0 );
if ( KErrNone == aIsiMessage.FindSubBlockOffsetById(
ISI_HEADER_SIZE + SIZE_UICC_APPL_CMD_RESP,
UICC_SB_FILE_DATA,
EIsiSubBlockTypeId16Len16,
uiccSbFileDataOffset ) )
{
fileDataLength = aIsiMessage.Get32bit(
uiccSbFileDataOffset + UICC_SB_FILE_DATA_OFFSET_DATALENGTH );
fileData.Set( aIsiMessage.GetData(
uiccSbFileDataOffset + UICC_SB_FILE_DATA_OFFSET_DATA,
fileDataLength ) );
}
else // Subblock is mandatory
{
TFLOGSTRING("TSY: CSatMessHandler::UiccApplCmdResp - Mandatory subblock UICC_SB_FILE_DATA not found");
OstTrace0( TRACE_NORMAL, DUP1_CSATMESSHANDLER_UICCAPPLCMDRESP_TD, "CSatMessHandler::UiccApplCmdResp - Mandatory subblock UICC_SB_FILE_DATA not found" );
error = KErrNotFound;
}
switch( trId )
{
// Call control, SMS PP DD, USIM MO-SMS control
case KUiccTrIdServiceTableByte4:
{
if ( KErrNone == error )
{
// MO SMS control status, only in case of USIM
SimMoSmsControlAvail(
fileData[0] & KMoSmsControlBitMaskUsim );
iTsySatMessaging->GetDataDownload()->SmsPpDlSupported(
fileData[0] & KSmsPpDdBitMaskUsim );
}
break;
}
// MO SMS control ( this transaction ID is used for SIM only )
case KUiccTrIdServiceTableByte10:
{
if ( KErrNone == error )
{
// MO SMS control status, only in case of USIM
SimMoSmsControlAvail(
KMoSmsControlBitMaskSim == ( fileData[0] & KMoSmsControlBitMaskSim ) );
}
break;
}
// USSD in Call Control ( this transaction ID is used for SIM only )
case KUiccTrIdServiceTableByte11:
{
iTsySatMessaging->SetStatusOfUssdSupport(
KMoUssdCallControlBitMaskSim == ( fileData[0] & KMoUssdCallControlBitMaskSim ) );
break;
}
// SMS PP Datadownload ( this transaction ID is used for SIM only )
case KUiccTrIdServiceTableByte7:
{
if ( UICC_CARD_TYPE_UICC == iCardType )
{
TBool ppDdSupported( EFalse );
if( KSmsPpDdBitMaskSim == ( fileData[0] & KSmsPpDdBitMaskSim ) )
{
ppDdSupported = ETrue;
}
iTsySatMessaging->GetDataDownload()->SmsPpDlSupported( ppDdSupported );
}
break;
}
// SAT icon
case KUiccTrIdReadSatIcon:
{
TBuf8<1> infoNotSet( 0 );
iTsySatMessaging->GetSatIcon()->
CompleteIconRequest( error, fileData, infoNotSet );
break;
}
// SAT icon instance
case KUiccTrIdReadIconInstancePhase1:
case KUiccTrIdReadIconInstancePhase2:
case KUiccTrIdReadIconClut:
{
if ( KUiccTrIdReadIconInstancePhase1 == trId )
{
// See image instance data context coding from
// 3GPP 31.102 v8.3.0. ANNEX B
// Save image coding scaheme
iImageCodingScheme = fileData[2];
// File ID of instance is in bytes 4 and 5
// Read instance file in phase 2
TUint16 fileId( ( fileData[3] << 8 ) | fileData[4] );
UiccReadSatIconInstanceReq( fileId );
}
else // Instance data and clut are set here
{
TPtrC8 data;
TBuf8<6> info;
TUint8 width( fileData[0] );
TUint8 heigth( fileData[1] );
TUint8 colorDepth( 1 );
TUint16 clutOffset( 0 );
TUint offset( 2 ); // instance data offset in basic coding
// Set in case of coulor image coding
iNumberOfClut = 0;
info.Append( width );
info.Append( heigth );
// Colour image coding scheme
if ( KBlackAndWhite != iImageCodingScheme )
{
colorDepth = fileData[2];
iNumberOfClut = fileData[3];
clutOffset = ( fileData[4] << 8 | fileData[5] );
offset = 6;
// Save clut data for clut request.
// So it is not needed to read instance file from UICC
// again.
TInt clutLength( KClutEntrySize * iNumberOfClut );
if ( 0 == clutLength )
{
clutLength = KClutEntrySize * 256;
}
iClutData.Set( fileData.Mid( clutOffset, clutLength ));
}
info.Append( colorDepth );
info.Append( iNumberOfClut );
info.Append( 0x00 ); // offset (default value added)
info.Append( 0x00 ); // offset (default value added)
TUint lengthInBits( width * heigth * colorDepth );
TUint lengthInBytes( lengthInBits / 8 );
// There might be rounding error in statement above, if
// length in bits is not evenly divisible by 8 ( one byte ).
if ( lengthInBits % 8 )
{
lengthInBytes++;
}
data.Set( fileData.Mid( offset, lengthInBytes ) );
iTsySatMessaging->GetSatIcon()->
CompleteIconRequest( error, data, info);
}
break;
}
default:
{
break;
}
} // End of switch( trId )
}
// -----------------------------------------------------------------------------
// CSatMessHandler::UiccCatIndL
// Breaks UICC_CAT_IND ISI-message.
// -----------------------------------------------------------------------------
//
void CSatMessHandler::UiccCatIndL
(
const TIsiReceiveC& aIsiMessage // Received ISI message
)
{
OstTrace0( TRACE_NORMAL, CSATMESSHANDLER_UICCCATINDL_TD, "CSatMessHandler::UiccCatIndL" );
TFLOGSTRING("TSY: CSatMessHandler::UiccCatIndL");
// UICC status
TUint8 serviceType( aIsiMessage.Get8bit(
ISI_HEADER_SIZE + UICC_CAT_IND_OFFSET_SERVICETYPE ) );
if ( UICC_READY == serviceType )
{
// Card type
iCardType = aIsiMessage.Get8bit(
ISI_HEADER_SIZE + UICC_CAT_IND_OFFSET_CARDTYPE );
// Application file ID is concluded from card type
if ( UICC_CARD_TYPE_UICC == iCardType )
{
// ADF USIM is used, ID = '7FFF'
TBuf8<2> umtsFileId;
umtsFileId.Append( 0x7F );
umtsFileId.Append( 0xFF );
iApplFileId.Copy( umtsFileId );
}
else if ( UICC_CARD_TYPE_ICC == iCardType )
{
// DF GSM is used, ID = '7F20'
TBuf8<2> gsmFileId;
gsmFileId.Append( 0x7F );
gsmFileId.Append( 0x20 );
iApplFileId.Copy( gsmFileId );
}
// No else, initialized to 'FFFF' in constructor.
// Send terminal profile
UiccTerminalProfileReq();
}
// Proactive command was fetched from SIM
else if ( UICC_CAT_FETCHED_CMD == serviceType )
{
if ( KErrNone == CheckProactiveCommand( aIsiMessage ) )
{
iTsySatMessaging->PCmdReceivedL( aIsiMessage );
}
else
{
TFLOGSTRING("TSY: CSatMessHandler::UiccCatIndL: Received SAT message was not valid!");
OstTrace0( TRACE_NORMAL, DUP1_CSATMESSHANDLER_UICCCATINDL_TD, "CSatMessHandler::UiccCatIndL. Received SAT message was not valid!" );
}
}
}
// -----------------------------------------------------------------------------
// CSatMessHandler::InfoPpReadReq
// Construct a INFO_PP_READ_REQ ISI message
// -----------------------------------------------------------------------------
//
/*TInt CSatMessHandler::InfoPpReadReq
(
const TUint8 aReqType // request type
)
{
OstTrace0( TRACE_NORMAL, CSATMESSHANDLER_INFOPPREADREQ_TD, "CSatMessHandler::InfoPpReadReq" );
TFLOGSTRING("TSY: CSatMessHandler::InfoPpReadReq" );
// Construct INFO_PP_READ_REQ message (INFO_BATCH_TYPE +
// sub block count + INFO_SB_PP sub block)
TBuf8<2 + SIZE_INFO_SB_PP> infoPpReadReq;
//set pp batch reading to read specific product profile, thus 0.
infoPpReadReq.Append( INFO_PP_PROD_PROFILE_FEATURE );
// add sub block
infoPpReadReq.Append( 1 ); // number of sub blocks
// create INFO_SB_PP sub block
TIsiSubBlock sbPPSubBlock( infoPpReadReq, INFO_SB_PP,
EIsiSubBlockTypeId8Len8 );
// Add 0x00 as the Dynamic Value ID, used to read a static value
infoPpReadReq.Append( 0x00 );
// Add 0x01 as the length of the product profile, reading only one profile
infoPpReadReq.Append( 0x01 );
// Add the product profile feature number being requested
infoPpReadReq.Append( aReqType );
// Value of the product profile is 0x00, since reading
infoPpReadReq.Append( 0x00 );
// complete sub block and append to INFO_PP_READ_REQ
sbPPSubBlock.CompleteSubBlock();
TUint8 tempTraId( iTsySatMessaging->GetTransactionId() );
#ifdef INFO_PP_ATK_MO_SM_CONTROL
if ( INFO_PP_ATK_MO_SM_CONTROL == aReqType )
{
// Save transaction id to separate actions in InfoPpReadResp.
// INFO_PP_ATK_MO_SM_CONTROL is the only PP flag which causes actions
// if response is unsuccessful and there can be several simultaneous
// PP queries ongoing
iInfoPpMoSmsTraId = tempTraId;
}
#endif
//create the isi message
return iPnSend->Send(
PN_INFO,
tempTraId,
INFO_PP_READ_REQ,
infoPpReadReq );
}*/
// -----------------------------------------------------------------------------
// CSatMessHandler::InfoPpReadRespL
// Breaks a INFO_PP_READ_RESP ISI-message.
// -----------------------------------------------------------------------------
//
/*void CSatMessHandler::InfoPpReadRespL
(
const TIsiReceiveC& aIsiMessage
)
{
OstTrace0( TRACE_NORMAL, CSATMESSHANDLER_INFOPPREADRESPL_TD, "CSatMessHandler::InfoPpReadRespL" );
TFLOGSTRING("TSY: CSatMessHandler::InfoPpReadRespL" );
TUint8 traId( aIsiMessage.Get8bit( ISI_HEADER_SIZE +
INFO_PP_READ_RESP_OFFSET_TRANSID ) );
TUint8 status( aIsiMessage.Get8bit( ISI_HEADER_SIZE +
INFO_PP_READ_RESP_OFFSET_STATUS ) );
TFLOGSTRING2("TSY: CSatMessHandler::InfoPpReadRespL - Status: %d",
status );
OstTraceExt1( TRACE_NORMAL, DUP1_CSATMESSHANDLER_INFOPPREADRESPL_TD, "CSatMessHandler::InfoPpReadRespL - Status: %hhu", status );
switch ( status )
{
case INFO_OK:
{
TUint sbInfoPpReadStartOffset( 0 );
if ( KErrNone == aIsiMessage.FindSubBlockOffsetById(
ISI_HEADER_SIZE + SIZE_INFO_PP_READ_RESP, INFO_SB_PP,
EIsiSubBlockTypeId8Len8, sbInfoPpReadStartOffset ) )
{
TInt length( aIsiMessage.Get8bit( sbInfoPpReadStartOffset +
INFO_SB_PP_OFFSET_STRLEN ) );
if ( length )
{
// Buffer to hold product profile feature and its
// corresponding value, thus buffer size is 2
TBuf8<2> pPFeatures;
// copy 2 bytes from product profile
// 1st byte = PP Feature
// 2nd byte = PP Value
pPFeatures.Copy( aIsiMessage.GetData(
sbInfoPpReadStartOffset +
INFO_SB_PP_OFFSET_PRODUCTPROFILE, 2 ) );
#ifdef INFO_PP_ATK_MO_SM_CONTROL
// Check that product profile is requested one
if ( INFO_PP_ATK_MO_SM_CONTROL == pPFeatures [0] )
{
//Get the value of the MO SMS control feature
if ( INFO_PP_FALSE != pPFeatures [1] )
{
TFLOGSTRING("TSY: CSatMessHandler::InfoPpReadRespL, MO SMS control supported by ME product profile" );
OstTrace0( TRACE_NORMAL, DUP2_CSATMESSHANDLER_INFOPPREADRESPL_TD, "CSatMessHandler::InfoPpReadRespL, MO SMS control supported by ME product profile" );
iMoSmsSupportedInPp = ETrue;
TInt ret( KErrNone );
// Continue MO SMS control check by checking
// feature availability from USIM
if ( UICC_CARD_TYPE_UICC == iCardType )
{
// USIM: Read MO-SMS control from byte 4
ret = UiccReadServiceTableReq( KUiccTrIdServiceTableByte4, 3 );
User::LeaveIfError( ret );
}
else if ( UICC_CARD_TYPE_ICC == iCardType )
{
// SIM: Read MO-SMS control from byte 10
ret = UiccReadServiceTableReq( KUiccTrIdServiceTableByte10, 9 );
User::LeaveIfError( ret );
}
}
else
{
TFLOGSTRING("TSY: CSatMessHandler::InfoPpReadRespL, MO SMS control not supported by ME product profile" );
OstTrace0( TRACE_NORMAL, DUP3_CSATMESSHANDLER_INFOPPREADRESPL_TD, "CSatMessHandler::InfoPpReadRespL, MO SMS control not supported by ME product profile" );
iMoSmsSupportedInPp = EFalse;
// Feature was not activated in product profile
// Set MoSmsCtrl object´s member
// iIsMoSmsCtrlActivated to EFalse
iTsySatMessaging->GetMoSmsCtrl()->Deactivate();
}
}
#endif // INFO_PP_ATK_MO_SM_CONTROL
#ifdef INFO_PP_ENHANCED_NETWORK_SELECTION
if ( INFO_PP_ENHANCED_NETWORK_SELECTION == pPFeatures [0] )
{
//Get the value of the ENS feature
if ( INFO_PP_FALSE != pPFeatures [1] )
{
TFLOGSTRING("TSY: CSatMessHandler::InfoPpReadRespL, INFO_PP_ENHANCED_NETWORK_SELECTION supported by ME product profile" );
OstTrace0( TRACE_NORMAL, DUP8_CSATMESSHANDLER_INFOPPREADRESPL_TD, "CSatMessHandler::InfoPpReadRespL, INFO_PP_ENHANCED_NETWORK_SELECTION supported by ME product profile" );
iEnsSupportedInPp = ETrue;
}
else
{
TFLOGSTRING("TSY: CSatMessHandler::InfoPpReadRespL, INFO_PP_ENHANCED_NETWORK_SELECTION not supported by ME product profile" );
OstTrace0( TRACE_NORMAL, DUP9_CSATMESSHANDLER_INFOPPREADRESPL_TD, "CSatMessHandler::InfoPpReadRespL, INFO_PP_ENHANCED_NETWORK_SELECTION not supported by ME product profile" );
iEnsSupportedInPp = EFalse;
}
}
#endif // INFO_PP_ENHANCED_NETWORK_SELECTION
#ifdef INFO_PP_SIM_OLD_POLL_INTERVAL
if ( INFO_PP_SIM_OLD_POLL_INTERVAL == pPFeatures [0] )
{
//Get the value of the SIM_POLL_INTERVAL control feature
if ( INFO_PP_FALSE != pPFeatures [1] )
{
TFLOGSTRING("TSY: CSatMessHandler::InfoPpReadRespL, INFO_PP_SIM_OLD_POLL_INTERVAL supported by ME product profile" );
OstTrace0( TRACE_NORMAL, DUP4_CSATMESSHANDLER_INFOPPREADRESPL_TD, "CSatMessHandler::InfoPpReadRespL, INFO_PP_SIM_OLD_POLL_INTERVAL supported by ME product profile" );
iOldPollIntervalSupportedInPp = ETrue;
}
else
{
TFLOGSTRING("TSY: CSatMessHandler::InfoPpReadRespL, INFO_PP_SIM_OLD_POLL_INTERVAL not supported by ME product profile" );
OstTrace0( TRACE_NORMAL, DUP5_CSATMESSHANDLER_INFOPPREADRESPL_TD, "CSatMessHandler::InfoPpReadRespL, INFO_PP_SIM_OLD_POLL_INTERVAL not supported by ME product profile" );
iOldPollIntervalSupportedInPp = EFalse;
}
}
#endif // INFO_PP_SIM_OLD_POLL_INTERVAL
//no else
}
}
break;
}
case INFO_NO_NUMBER:
{
TFLOGSTRING("TSY: CSatMessHandler::InfoPpReadRespL, Requested feature not defined in product profile" );
OstTrace0( TRACE_NORMAL, DUP6_CSATMESSHANDLER_INFOPPREADRESPL_TD, "CSatMessHandler::InfoPpReadRespL, Requested feature not defined in product profile" );
#ifdef INFO_PP_ATK_MO_SM_CONTROL
// Request was for INFO_PP_ATK_MO_SM_CONTROL
if ( traId == iInfoPpMoSmsTraId )
{
// If the MO SMS feature is not defined in product profile,
// internal Boolean used as feature supported ( for refresh )
iMoSmsSupportedInPp = ETrue;
TInt ret( KErrNone );
// Continue as usual by checking feature avalability from USIM
if ( UICC_CARD_TYPE_UICC == iCardType )
{
// USIM: Read MO-SMS control from byte 4
ret = UiccReadServiceTableReq( KUiccTrIdServiceTableByte4, 3 );
User::LeaveIfError( ret );
}
else if ( UICC_CARD_TYPE_ICC == iCardType )
{
// SIM: Read MO-SMS control from byte 10
ret = UiccReadServiceTableReq( KUiccTrIdServiceTableByte10, 9 );
User::LeaveIfError( ret );
}
}
#endif // INFO_PP_ATK_MO_SM_CONTROL
break;
}
case INFO_FAIL:
default:
{
TFLOGSTRING("TSY: CSatMessHandler::InfoPpReadRespL, - default Requested feature not supported by ME product profile" );
OstTrace0( TRACE_NORMAL, DUP7_CSATMESSHANDLER_INFOPPREADRESPL_TD, "CSatMessHandler::InfoPpReadRespL, - default Requested feature not supported by ME product profile" );
#ifdef INFO_PP_ATK_MO_SM_CONTROL
// Request was for INFO_PP_ATK_MO_SM_CONTROL
if ( traId == iInfoPpMoSmsTraId )
{
iMoSmsSupportedInPp = EFalse;
iTsySatMessaging->GetMoSmsCtrl()->Deactivate();
}
#endif // INFO_PP_ATK_MO_SM_CONTROL
break;
}
}
// Zero iInfoPpMoSmsTraId if used. Not used by default.
if ( traId == iInfoPpMoSmsTraId )
{
iInfoPpMoSmsTraId = 0;
}
}*/
// -----------------------------------------------------------------------------
// CSatMessHandler::CheckTlvObjects
// Validates every simple tlv object from proactive command
// -----------------------------------------------------------------------------
//
TInt CSatMessHandler::CheckTlvObjects( CBerTlv& berTlv )
{
TFLOGSTRING("TSY: CSatMessHandler::CheckTlvObjects" );
OstTrace0( TRACE_NORMAL, CSATMESSHANDLER_CHECKTLVOBJECTS_TD, "CSatMessHandler::CheckTlvObjects" );
TInt ret( KErrNone );
TPtrC8 dataPtr = berTlv.Data();
TUint16 berTlvLength( berTlv.GetLength() );
TInt totalLength = 0;
// index is set to beginning of data inside BER-TLV object. If length
// of BER-TLV object is coded as one byte, data starts from index 2
// and if length of BER-TLV object is coded as two bytes, data starts
// from index 3.
TInt index = 2;
if( KTwoByteLengthCoding == dataPtr[KTlvLengthStartPosition] )
{
// data len is coded as two bytes, let's increment these variables
// so that two byte len is handled correctly
index++;
}
while( berTlvLength > ( index - 2 ) )
{
// now index points to tag of simple TLV object, let's increment
// index by one so that it points to length of the simple TLV object
index++;
// totalLength is incremented by 2 so that tag & len fields of the current
// simple tlv object are calcucated to total length of BER TLV object
totalLength += 2;
if( KTwoByteLengthCoding == dataPtr[index] )
{
// data len is coded as two bytes, let's increment these variables
// so that two byte len is handled correctly
index++;
totalLength++;
// if length of the simple TLV value is coded with two bytes,
// length of the simple TLV value must be 128-255, otherwise
// it is treaded as error
if( 0x80 > dataPtr[index] || 0xFF < dataPtr[index] )
{
TFLOGSTRING2("TSY: CSatMessHandler::CheckTlvObjects: corrupted simple tlv obj, len: %d even it should be 128-255", dataPtr[index] );
OstTrace1( TRACE_NORMAL, DUP1_CSATMESSHANDLER_CHECKTLVOBJECTS_TD, "CSatMessHandler::CheckTlvObjects; corrupted simple tlv obj, len: %d even it should be 128-255", dataPtr[index] );
ret = KErrCorrupt;
break;
}
}
else
{
// if length of the simple TLV value is coded with one byte,
// length of the simple TLV value must be 0-127, otherwise
// it is treaded as error
if( 0x80 <= dataPtr[index] )
{
TFLOGSTRING2("TSY: CSatMessHandler::CheckTlvObjects: corrupted simple tlv obj, len: %d even it should be 0-127", dataPtr[index] );
OstTrace1( TRACE_NORMAL, DUP2_CSATMESSHANDLER_CHECKTLVOBJECTS_TD, "CSatMessHandler::CheckTlvObjects; corrupted simple tlv obj, len: %d even it should be 0-127", dataPtr[index] );
ret = KErrCorrupt;
break;
}
}
// total length is incremented by data len of the current simple
// tlv object
totalLength += dataPtr[index];
// let's move index to beginning of next simple TLV object. So
// after incrementing the index, it points to next simple TLV
// object's tag value
index += dataPtr[index] + 1;
} // end of while
// let's check does length from proactive command match to
// calculated length
if( berTlvLength != totalLength )
{
TFLOGSTRING3("TSY: CSatMessHandler::CheckTlvObjects: proactive command len (%d) and calculated len (%d) doesn't match", berTlvLength, totalLength );
OstTraceExt2( TRACE_NORMAL, DUP3_CSATMESSHANDLER_CHECKTLVOBJECTS_TD, "CSatMessHandler::CheckTlvObjects; proactive command len (%d) and calculated len (%d) doesn't match", berTlvLength, totalLength );
ret = KErrCorrupt;
}
return ret;
}
// -----------------------------------------------------------------------------
// CSatMessHandler::SimMoSmsControlAvail
// Activate or deactivate MO SMS Control on SMS Server
// -----------------------------------------------------------------------------
//
void CSatMessHandler::SimMoSmsControlAvail( TUint8 aStatus )
{
TFLOGSTRING("TSY: CSatMessHandler::SimMoSmsControlAvail" );
OstTrace0( TRACE_NORMAL, CSATMESSHANDLER_SIMMOSMSCONTROLAVAIL_TD, "CSatMessHandler::SimMoSmsControlAvail" );
// Activate the MO-SMS Control in SMS server. This is done by
// sending a request SMS_RESOURCE_CONF_REQ to SMS server
TBuf8<SIZE_SMS_RESOURCE_CONF_REQ + SIZE_SMS_SB_RESOURCE_CONF> data;
// Append Configuration operation
data.Append( SMS_RES_CONF_SET );
// Number of Subblocks
data.Append( 1 );
// Add Subblock
TIsiSubBlock ResourceConfReqSb(
data,
SMS_SB_RESOURCE_CONF,
EIsiSubBlockTypeId16Len16 );
if( aStatus )
{
// Set MoSmsCtrl object´s member iIsMoSmsCtrlActivated to ETrue
iTsySatMessaging->GetMoSmsCtrl()->Activate();
TSatUtility::AppendWord( SMS_RES_ID_MO_SM_INIT, data );
}
else
{
// Set MoSmsCtrl object´s member IsMoSmsCtrlDeActivated to EFalse
iTsySatMessaging->GetMoSmsCtrl()->Deactivate();
TSatUtility::AppendWord( 0x0000, data);
}
// SMS_RES_ID_MASK_MO_SM_INIT is the only "official" value for mask
TSatUtility::AppendWord( SMS_RES_ID_MASK_MO_SM_INIT, data);
ResourceConfReqSb.CompleteSubBlock();
SmsResoureConfReq(
iTsySatMessaging->GetTransactionId(),
SMS_RESOURCE_CONF_REQ,
data );
}
// -----------------------------------------------------------------------------
// CSatMessHandler::UiccTerminalProfileReq
// Send terminal profile
// -----------------------------------------------------------------------------
//
void CSatMessHandler::UiccTerminalProfileReq()
{
OstTrace0( TRACE_NORMAL, CSATMESSHANDLER_UICCTERMINALPROFILEREQ_TD, "CSatMessHandler::UiccTerminalProfileReq" );
TFLOGSTRING("TSY: CSatMessHandler::UiccTerminalProfileReq");
// Pointer to terminal profile buffer
const TUint8* terminalProfilePtr( NULL );
// Size of terminal profile
TInt sizeofTerminalProfile( 0 );
if ( UICC_CARD_TYPE_UICC == iCardType )
{
terminalProfilePtr = &KTerminalProfileUicc[0];
sizeofTerminalProfile = sizeof( KTerminalProfileUicc );
}
else // ICC type
{
terminalProfilePtr = &KTerminalProfileIcc[0];
sizeofTerminalProfile = sizeof( KTerminalProfileIcc );
}
// Create UICC_CAT_REQ message
TIsiSend isiMsg( iPnSend->SendBufferDes() );
isiMsg.Set8bit( ISI_HEADER_OFFSET_RESOURCEID, PN_UICC );
isiMsg.Set8bit(
ISI_HEADER_SIZE + UICC_CAT_REQ_OFFSET_TRANSID,
KUiccTrIdCommon );
isiMsg.Set8bit(
ISI_HEADER_SIZE + UICC_CAT_REQ_OFFSET_MESSAGEID,
UICC_CAT_REQ );
isiMsg.Set8bit(
ISI_HEADER_SIZE + UICC_CAT_REQ_OFFSET_SERVICETYPE,
UICC_CAT_TERMINAL_PROFILE );
isiMsg.Set8bit( ISI_HEADER_SIZE + UICC_CAT_REQ_OFFSET_NSB, 1 );
// Create UICC_SB_TERMINAL_PROFILE subblock
TBuf8<KSizeOfTerminalProfileSb> terminalProfileBuf( 0 );
TIsiSubBlock uiccSbTerminalProfile(
terminalProfileBuf,
UICC_SB_TERMINAL_PROFILE,
EIsiSubBlockTypeId16Len16 );
// 2x filler
terminalProfileBuf.Append( KUiccPadding );
terminalProfileBuf.Append( KUiccPadding );
// Terminal profile length (16-bit)
terminalProfileBuf.Append( 0 );
terminalProfileBuf.Append( sizeofTerminalProfile );
// Terminal profile
terminalProfileBuf.Append( terminalProfilePtr, sizeofTerminalProfile );
// Append subblock to ISI message
isiMsg.CopyData(
ISI_HEADER_SIZE + SIZE_UICC_CAT_REQ,
uiccSbTerminalProfile.CompleteSubBlock() );
iPnSend->Send( isiMsg.Complete() );
}
// -----------------------------------------------------------------------------
// CSatMessHandler::UiccReadServiceTable
// (other items were commented in a header).
// -----------------------------------------------------------------------------
//
TInt CSatMessHandler::UiccReadServiceTableReq(
TUint8 aTrId,
TUint16 aFileOffset )
{
TFLOGSTRING2("TSY: CSatMessHandler::UiccReadServiceTableReq, transaction ID: %d", aTrId );
OstTraceExt1( TRACE_NORMAL, CSATMESSHANDLER_UICCREADSERVICETABLE_TD, "CSatMessHandler::UiccReadServiceTableReq;aTrId=%hhu", aTrId );
TIsiSend isiMsg( iPnSend->SendBufferDes() );
isiMsg.Set8bit( ISI_HEADER_OFFSET_RESOURCEID, PN_UICC );
isiMsg.Set8bit(
ISI_HEADER_SIZE + UICC_APPL_CMD_REQ_OFFSET_TRANSID,
aTrId );
isiMsg.Set8bit(
ISI_HEADER_SIZE + UICC_APPL_CMD_REQ_OFFSET_MESSAGEID,
UICC_APPL_CMD_REQ );
isiMsg.Set8bit(
ISI_HEADER_SIZE + UICC_APPL_CMD_REQ_OFFSET_SERVICETYPE,
UICC_APPL_READ_TRANSPARENT );
isiMsg.Set8bit(
ISI_HEADER_SIZE + UICC_APPL_CMD_REQ_OFFSET_APPLID,
iApplicationId );
isiMsg.Set8bit(
ISI_HEADER_SIZE + UICC_APPL_CMD_REQ_OFFSET_SESSIONID,
UICC_SESSION_ID_NOT_USED );
isiMsg.Set16bit(
ISI_HEADER_SIZE + UICC_APPL_CMD_REQ_OFFSET_FILLERBYTE1,
KUiccPadding );
isiMsg.Set8bit(
ISI_HEADER_SIZE + UICC_APPL_CMD_REQ_OFFSET_NSB,
KNumOfSbsInUiccApplCmdReq );
// UICC_SB_CLIENT
TBuf8<SIZE_UICC_SB_CLIENT> uiccSbClientBuf( 0 );
TIsiSubBlock uiccSbClient(
uiccSbClientBuf,
UICC_SB_CLIENT,
EIsiSubBlockTypeId16Len16 );
// 3x padding
uiccSbClientBuf.Append( KUiccPadding );
uiccSbClientBuf.Append( KUiccPadding );
uiccSbClientBuf.Append( KUiccPadding );
uiccSbClientBuf.Append( iUiccClientId );
// Append subblock to ISI message
isiMsg.CopyData( KUiccApplCmdReqOffset, uiccSbClient.CompleteSubBlock() );
// UICC_SB_TRANSPARENT
TBuf8<SIZE_UICC_SB_TRANSPARENT> uiccSbTransparentBuf( 0 );
TIsiSubBlock uiccSbTransparent(
uiccSbTransparentBuf,
UICC_SB_TRANSPARENT,
EIsiSubBlockTypeId16Len16 );
// File offset defines which service is read, 16-bit.
// Service table is max. 10 bytes so MSB bytes are set to 0
uiccSbTransparentBuf.Append( 0 );
uiccSbTransparentBuf.Append( aFileOffset );
// Data amount, 16-bit
// Read only one byte -> MSB bits are set to 0
uiccSbTransparentBuf.Append( 0 );
uiccSbTransparentBuf.Append( 1 );
// Append subblock to ISI message
isiMsg.CopyData(
KUiccApplCmdReqOffset + SIZE_UICC_SB_CLIENT,
uiccSbTransparent.CompleteSubBlock() );
// UICC_SB_APPL_PATH
TBuf8<KUiccSbApplPathSize> uiccSbApplPathBuf( 0 );
TIsiSubBlock uiccSbApplPath(
uiccSbApplPathBuf,
UICC_SB_APPL_PATH,
EIsiSubBlockTypeId16Len16 );
// File ID is '6F38', EF UST
uiccSbApplPathBuf.Append( KUiccElemFileServiceTable >> 8 );
uiccSbApplPathBuf.Append( KUiccElemFileServiceTable );
// File ID SFI, 8-bit
uiccSbApplPathBuf.Append( KUiccSfiServiceTable );
// Filler, 8-bit
uiccSbApplPathBuf.Append( KUiccPadding );
// Length of the DF path, 8-bit
uiccSbApplPathBuf.Append( KUiccFilePathLengthServiceTable );
// Filler, 8-bit
uiccSbApplPathBuf.Append( KUiccPadding );
// Application file path:
// master file ID + application file ID
uiccSbApplPathBuf.Append( KUiccMasterFileId >> 8 );
uiccSbApplPathBuf.Append( KUiccMasterFileId );
uiccSbApplPathBuf.Append( iApplFileId );
// Append subblock to ISI message
isiMsg.CopyData(
KUiccApplCmdReqOffset + SIZE_UICC_SB_CLIENT + SIZE_UICC_SB_TRANSPARENT,
uiccSbApplPath.CompleteSubBlock() );
return( iPnSend->Send( isiMsg.Complete() ) );
}
// -----------------------------------------------------------------------------
// CSatMessHandler::UiccReadSatIconReq
// (other items were commented in a header).
// -----------------------------------------------------------------------------
//
TInt CSatMessHandler::UiccReadSatIconReq(
TUint8 aRecordNumber,
TUint8 aFileOffset,
TUint8 aDataAmount,
TUint8 aTrId )
{
TIsiSend isiMsg( iPnSend->SendBufferDes() );
isiMsg.Set8bit( ISI_HEADER_OFFSET_RESOURCEID, PN_UICC );
isiMsg.Set8bit(
ISI_HEADER_SIZE + UICC_APPL_CMD_REQ_OFFSET_TRANSID,
aTrId );
isiMsg.Set8bit(
ISI_HEADER_SIZE + UICC_APPL_CMD_REQ_OFFSET_MESSAGEID,
UICC_APPL_CMD_REQ );
isiMsg.Set8bit(
ISI_HEADER_SIZE + UICC_APPL_CMD_REQ_OFFSET_SERVICETYPE,
UICC_APPL_READ_TRANSPARENT );
isiMsg.Set8bit(
ISI_HEADER_SIZE + UICC_APPL_CMD_REQ_OFFSET_APPLID,
iApplicationId );
isiMsg.Set8bit(
ISI_HEADER_SIZE + UICC_APPL_CMD_REQ_OFFSET_SESSIONID,
UICC_SESSION_ID_NOT_USED );
isiMsg.Set16bit(
ISI_HEADER_SIZE + UICC_APPL_CMD_REQ_OFFSET_FILLERBYTE1,
KUiccPadding );
isiMsg.Set8bit(
ISI_HEADER_SIZE + UICC_APPL_CMD_REQ_OFFSET_NSB,
KNumOfSbsInUiccApplCmdReq );
// UICC_SB_CLIENT
TBuf8<SIZE_UICC_SB_CLIENT> uiccSbClientBuf( 0 );
TIsiSubBlock uiccSbClient(
uiccSbClientBuf,
UICC_SB_CLIENT,
EIsiSubBlockTypeId16Len16 );
// 3x padding
uiccSbClientBuf.Append( KUiccPadding );
uiccSbClientBuf.Append( KUiccPadding );
uiccSbClientBuf.Append( KUiccPadding );
uiccSbClientBuf.Append( iUiccClientId );
// Append subblock to ISI message
isiMsg.CopyData( KUiccApplCmdReqOffset, uiccSbClient.CompleteSubBlock() );
// UICC_SB_LINEAR_FIXED
TBuf8<SIZE_UICC_SB_LINEAR_FIXED> uiccSbLinearFixedBuf( 0 );
TIsiSubBlock uiccSbLinearFixed(
uiccSbLinearFixedBuf,
UICC_SB_LINEAR_FIXED,
EIsiSubBlockTypeId16Len16 );
// Record number, 8-bit
uiccSbLinearFixedBuf.Append( aRecordNumber );
// File offset, 8-bit
uiccSbLinearFixedBuf.Append( aFileOffset );
// Data amount, 8-bit
uiccSbLinearFixedBuf.Append( aDataAmount );
// Append subblock to ISI message
isiMsg.CopyData(
KUiccApplCmdReqOffset + SIZE_UICC_SB_CLIENT,
uiccSbLinearFixed.CompleteSubBlock() );
// UICC_SB_APPL_PATH
TBuf8<KUiccSbApplPathSize> uiccSbApplPathBuf( 0 );
TIsiSubBlock uiccSbApplPath(
uiccSbApplPathBuf,
UICC_SB_APPL_PATH,
EIsiSubBlockTypeId16Len16 );
// File ID is '4F20', EF IMG
uiccSbApplPathBuf.Append( KUiccElemFileImg >> 8 );
uiccSbApplPathBuf.Append( KUiccElemFileImg );
// File ID SFI, 8-bit
uiccSbApplPathBuf.Append( UICC_SFI_NOT_PRESENT );
// Filler, 8-bit
uiccSbApplPathBuf.Append( KUiccPadding );
// Length of the DF path, 8-bit
uiccSbApplPathBuf.Append( KUiccFilePathLength );
// Filler, 8-bit
uiccSbApplPathBuf.Append( KUiccPadding );
// Application file path:
// master file + application file + dedicated file +
// elementary file
uiccSbApplPathBuf.Append( KUiccMasterFileId >> 8 );
uiccSbApplPathBuf.Append( KUiccMasterFileId );
uiccSbApplPathBuf.Append( KUiccDedicatedFileTelecom >> 8 );
uiccSbApplPathBuf.Append( KUiccDedicatedFileTelecom );
uiccSbApplPathBuf.Append( KUiccDedicatedFileGraphics >> 8 );
uiccSbApplPathBuf.Append( KUiccDedicatedFileGraphics );
// Append subblock to ISI message
isiMsg.CopyData(
KUiccApplCmdReqOffset + SIZE_UICC_SB_CLIENT +
SIZE_UICC_SB_LINEAR_FIXED,
uiccSbApplPath.CompleteSubBlock() );
return( iPnSend->Send( isiMsg.Complete() ) );
}
// -----------------------------------------------------------------------------
// CSatMessHandler::UiccReadSatIconInstanceReq
// (other items were commented in a header).
// -----------------------------------------------------------------------------
//
TInt CSatMessHandler::UiccReadSatIconInstanceReq( TUint16 aFileId )
{
TIsiSend isiMsg( iPnSend->SendBufferDes() );
isiMsg.Set8bit( ISI_HEADER_OFFSET_RESOURCEID, PN_UICC );
isiMsg.Set8bit(
ISI_HEADER_SIZE + UICC_APPL_CMD_REQ_OFFSET_TRANSID,
KUiccTrIdReadIconInstancePhase2 );
isiMsg.Set8bit(
ISI_HEADER_SIZE + UICC_APPL_CMD_REQ_OFFSET_MESSAGEID,
UICC_APPL_CMD_REQ );
isiMsg.Set8bit(
ISI_HEADER_SIZE + UICC_APPL_CMD_REQ_OFFSET_SERVICETYPE,
UICC_APPL_READ_TRANSPARENT );
isiMsg.Set8bit(
ISI_HEADER_SIZE + UICC_APPL_CMD_REQ_OFFSET_APPLID,
iApplicationId );
isiMsg.Set8bit(
ISI_HEADER_SIZE + UICC_APPL_CMD_REQ_OFFSET_SESSIONID,
UICC_SESSION_ID_NOT_USED );
isiMsg.Set16bit(
ISI_HEADER_SIZE + UICC_APPL_CMD_REQ_OFFSET_FILLERBYTE1,
KUiccPadding );
isiMsg.Set8bit(
ISI_HEADER_SIZE + UICC_APPL_CMD_REQ_OFFSET_NSB,
KNumOfSbsInUiccApplCmdReq );
// UICC_SB_CLIENT
TBuf8<SIZE_UICC_SB_CLIENT> uiccSbClientBuf( 0 );
TIsiSubBlock uiccSbClient(
uiccSbClientBuf,
UICC_SB_CLIENT,
EIsiSubBlockTypeId16Len16 );
// 3x padding
uiccSbClientBuf.Append( KUiccPadding );
uiccSbClientBuf.Append( KUiccPadding );
uiccSbClientBuf.Append( KUiccPadding );
uiccSbClientBuf.Append( iUiccClientId );
// Append subblock to ISI message
isiMsg.CopyData( KUiccApplCmdReqOffset, uiccSbClient.CompleteSubBlock() );
// UICC_SB_LINEAR_FIXED
TBuf8<SIZE_UICC_SB_TRANSPARENT> uiccSbTransparentBuf( 0 );
TIsiSubBlock uiccSbTransparent(
uiccSbTransparentBuf,
UICC_SB_TRANSPARENT,
EIsiSubBlockTypeId16Len16 );
// File offset, 8-bit
uiccSbTransparentBuf.Append( 0 );
// Data amount, 8-bit
uiccSbTransparentBuf.Append( 0 );
// Append subblock to ISI message
isiMsg.CopyData(
KUiccApplCmdReqOffset + SIZE_UICC_SB_CLIENT,
uiccSbTransparent.CompleteSubBlock() );
// UICC_SB_APPL_PATH
TBuf8<KUiccSbApplPathSize> uiccSbApplPathBuf( 0 );
TIsiSubBlock uiccSbApplPath(
uiccSbApplPathBuf,
UICC_SB_APPL_PATH,
EIsiSubBlockTypeId16Len16 );
// File ID is '4F20', EF IMG
uiccSbApplPathBuf.Append( aFileId >> 8 );
uiccSbApplPathBuf.Append( aFileId );
// File ID SFI, 8-bit
uiccSbApplPathBuf.Append( UICC_EF_ID_NOT_PRESENT );
// Filler, 8-bit
uiccSbApplPathBuf.Append( KUiccPadding );
// Length of the DF path, 8-bit
uiccSbApplPathBuf.Append( KUiccFilePathLength );
// Filler, 8-bit
uiccSbApplPathBuf.Append( KUiccPadding );
// Application file path:
// master file + application file + dedicated file +
// elementary file
uiccSbApplPathBuf.Append( KUiccMasterFileId >> 8 );
uiccSbApplPathBuf.Append( KUiccMasterFileId );
uiccSbApplPathBuf.Append( KUiccDedicatedFileTelecom >> 8 );
uiccSbApplPathBuf.Append( KUiccDedicatedFileTelecom );
uiccSbApplPathBuf.Append( KUiccDedicatedFileGraphics >> 8 );
uiccSbApplPathBuf.Append( KUiccDedicatedFileGraphics );
// Append subblock to ISI message
isiMsg.CopyData(
KUiccApplCmdReqOffset + SIZE_UICC_SB_CLIENT +
SIZE_UICC_SB_TRANSPARENT,
uiccSbApplPath.CompleteSubBlock() );
return( iPnSend->Send( isiMsg.Complete() ) );
}
// -----------------------------------------------------------------------------
// CSatMessHandler::UiccCatReq
// Create and send UICC_CAT_REQ ISI message
// -----------------------------------------------------------------------------
//
TInt CSatMessHandler::UiccCatReq( TUint8 aCommand )
{
TFLOGSTRING("TSY: CSatMessHandler::UiccCatReq");
OstTrace0( TRACE_NORMAL, CSATMESSHANDLER_UICCCATREQ_TD, "CSatMessHandler::UiccCatReq" );
TIsiSend isiMsg( iPnSend->SendBufferDes() );
isiMsg.Set8bit( ISI_HEADER_OFFSET_RESOURCEID, PN_UICC );
isiMsg.Set8bit(
ISI_HEADER_SIZE + UICC_CAT_REQ_OFFSET_TRANSID,
KUiccTrIdCommon );
isiMsg.Set8bit(
ISI_HEADER_SIZE + UICC_CAT_REQ_OFFSET_MESSAGEID,
UICC_CAT_REQ );
isiMsg.Set8bit(
ISI_HEADER_SIZE + UICC_CAT_REQ_OFFSET_SERVICETYPE,
aCommand );
// No subblocks
isiMsg.Set8bit(
ISI_HEADER_SIZE + UICC_CAT_REQ_OFFSET_NSB,
0 );
return( iPnSend->Send( isiMsg.Complete() ) );
}
// -----------------------------------------------------------------------------
// CSatMessHandler::UiccCatReqRefresh
// Create and send UICC_CAT_REQ ISI message for refresh command
// -----------------------------------------------------------------------------
//
TInt CSatMessHandler::UiccCatReqRefresh(
const TUint8 aTransId, // Transaction ID
const TUint8 aServiceType, // Type of refresh
TDes8& aFileList, // List of files
const TDesC8& aAid ) // Application ID (USIM)
{
TFLOGSTRING("TSY: CSatMessHandler::UiccCatReqRefresh");
OstTrace0( TRACE_NORMAL, CSATMESSHANDLER_UICCCATREQREFRESH_TD, "CSatMessHandler::UiccCatReqRefresh" );
TUint8 numOfSubblocks( 1 ); // One mandatory subblock UICC_SB_REFRESH
TUint8 uiccSbOffset(
ISI_HEADER_SIZE + SIZE_UICC_CAT_REQ + SIZE_UICC_SB_REFRESH );
TIsiSend isiMsg( iPnSend->SendBufferDes() );
isiMsg.Set8bit( ISI_HEADER_OFFSET_RESOURCEID, PN_UICC );
isiMsg.Set8bit(
ISI_HEADER_SIZE + UICC_CAT_REQ_OFFSET_TRANSID,
aTransId );
isiMsg.Set8bit(
ISI_HEADER_SIZE + UICC_CAT_REQ_OFFSET_MESSAGEID,
UICC_CAT_REQ );
isiMsg.Set8bit(
ISI_HEADER_SIZE + UICC_CAT_REQ_OFFSET_SERVICETYPE,
UICC_CAT_REFRESH );
// Add UICC_SB_REFRESH
TBuf8<SIZE_UICC_SB_REFRESH> uiccSbRefreshBuf( 0 );
TIsiSubBlock uiccSbRefresh(
uiccSbRefreshBuf,
UICC_SB_REFRESH,
EIsiSubBlockTypeId16Len16 );
// Type of refresh
uiccSbRefreshBuf.Append( aServiceType );
// 3x filler
uiccSbRefreshBuf.Append( KUiccPadding );
uiccSbRefreshBuf.Append( KUiccPadding );
uiccSbRefreshBuf.Append( KUiccPadding );
// Append subblock to ISI message
isiMsg.CopyData(
ISI_HEADER_SIZE + SIZE_UICC_CAT_REQ,
uiccSbRefresh.CompleteSubBlock() );
// Add UICC_SB_AID if needed
if ( aAid.Length() )
{
numOfSubblocks++;
TBuf8<KMaxLengthUiccSbAid> uiccSbAidBuf( 0 );
TIsiSubBlock uiccSbAid(
uiccSbAidBuf,
UICC_SB_AID,
EIsiSubBlockTypeId16Len16 );
// AID length
uiccSbAidBuf.Append( aAid.Length() );
// Add AID
uiccSbAidBuf.Append( aAid );
// Append subblock to ISI message
isiMsg.CopyData( uiccSbOffset, uiccSbAid.CompleteSubBlock() );
// Calculate offset for next subblock
TUint16 lengthOfUiccSbAid( uiccSbAidBuf.Length() ); // Length of UICC_SB_AID
uiccSbOffset += lengthOfUiccSbAid;
}
// Add UICC_SB_APPL_PATH subblock(s) if needed
while ( aFileList.Length() )
{
numOfSubblocks++;
// Search last file's start position
TInt position( aFileList.LocateReverse( KRefreshMasterFileHeader ) );
if ( KErrNotFound == position )
{
// File path is corrupted
TFLOGSTRING("TSY: CSatMessHandler::SimAtkReq, File path is corrupted");
OstTrace0( TRACE_NORMAL, DUP1_CSATMESSHANDLER_UICCCATREQREFRESH_TD, "CSatMessHandler::UiccCatReqRefresh,File path is corrupted" );
break;
}
// Length of whole file path (file path + file id)
TUint8 length( (TUint8) ( aFileList.Length() - position ) );
// length of file path (without file id)
TUint8 pathLength( (TUint8) ( length - KUiccFileIdLength ) );
// File path
TBuf8<KUiccFilePathLength> filePath(
aFileList.Mid( position, length ) );
// File ID is two last bytes
TBuf8<KUiccFileIdLength> fileId(
filePath.Mid( filePath.Length() - 2 ) );
TBuf8<SIZE_UICC_SB_APPL_PATH + KUiccFilePathLength>
uiccSbApplPathBuf( 0 );
TIsiSubBlock uiccSbApplPath(
uiccSbApplPathBuf,
UICC_SB_APPL_PATH,
EIsiSubBlockTypeId16Len16 );
// Append file ID
uiccSbApplPathBuf.Append( fileId );
// File ID SFI is not known
uiccSbApplPathBuf.Append( UICC_SFI_NOT_PRESENT );
// Filler
uiccSbApplPathBuf.Append( KUiccPadding );
// File path length in bytes
uiccSbApplPathBuf.Append( pathLength );
// Filler
uiccSbApplPathBuf.Append( KUiccPadding );
// File path
uiccSbApplPathBuf.Append( filePath.Mid( 0, pathLength ) );
// Append subblock to ISI message
isiMsg.CopyData( uiccSbOffset, uiccSbApplPath.CompleteSubBlock() );
// Update subblock offset
uiccSbOffset += uiccSbApplPathBuf.Length();
// Remove already added file from buffer
aFileList.SetLength( aFileList.Length() - length );
// Clear buffer for a new sub block
uiccSbApplPathBuf.Zero();
}
isiMsg.Set8bit(
ISI_HEADER_SIZE + UICC_CAT_REQ_OFFSET_NSB,
numOfSubblocks );
// set flag on that we are waiting a response for a refresh request
iRefreshRequestIsOn = ETrue;
return( iPnSend->Send( isiMsg.Complete() ) );
}
// -----------------------------------------------------------------------------
// CSatMessHandler::UiccCatReqTerminalResponse
// Send UICC_CAT_REQ ISI message for sending terminal response to UICC
// -----------------------------------------------------------------------------
//
TInt CSatMessHandler::UiccCatReqTerminalResponse(
const TDes8& aCommandDetails, // Command details tlv
const TDesC8& aBerTlvSpecificData, // BER-TLV specific data
const TUint8 aTransId )
{
TFLOGSTRING("TSY: CSatMessHandler::UiccCatReqTerminalResponse");
OstTrace0( TRACE_NORMAL, CSATMESSHANDLER_UICCCATREQTERMINALRESPONSE_TD, "CSatMessHandler::UiccCatReqTerminalResponse" );
TIsiSend isiMsg( iPnSend->SendBufferDes() );
isiMsg.Set8bit( ISI_HEADER_OFFSET_RESOURCEID, PN_UICC );
isiMsg.Set8bit(
ISI_HEADER_SIZE + UICC_CAT_REQ_OFFSET_TRANSID,
aTransId );
isiMsg.Set8bit(
ISI_HEADER_SIZE + UICC_CAT_REQ_OFFSET_MESSAGEID,
UICC_CAT_REQ );
isiMsg.Set8bit(
ISI_HEADER_SIZE + UICC_CAT_REQ_OFFSET_SERVICETYPE,
UICC_CAT_TERMINAL_RESPONSE );
// One subblock, UICC_SB_TERMINAL_RESPONSE
isiMsg.Set8bit(
ISI_HEADER_SIZE + UICC_CAT_REQ_OFFSET_NSB,
1 );
// UICC_SB_TERMINAL_RESPONSE
TBuf8<KMaxSizeOfUiccSbTerminalResponse> uiccSbTerminalResponseBuf( 0 );
TIsiSubBlock uiccSbTerminalResponse(
uiccSbTerminalResponseBuf,
UICC_SB_TERMINAL_RESPONSE,
EIsiSubBlockTypeId16Len16 );
// 2x filler
uiccSbTerminalResponseBuf.Append( KUiccPadding );
uiccSbTerminalResponseBuf.Append( KUiccPadding );
if ( aCommandDetails.Length() )
{
// Calculate terminal response data length
// 9 = command details lenght + device identity length
TUint16 lengthOfData( ( TUint16 ) ( 9 + aBerTlvSpecificData.Length() ) );
// Terminal response data length (2 bytes)
uiccSbTerminalResponseBuf.Append( lengthOfData >> 8 );
uiccSbTerminalResponseBuf.Append( lengthOfData );
// Add command details
uiccSbTerminalResponseBuf.Append( aCommandDetails );
// Add device identity TLV
// Device identity tag
uiccSbTerminalResponseBuf.Append( KTlvDeviceIdentityTag );
// Device identity TLV length
uiccSbTerminalResponseBuf.Append( KTlvDeviceIdentityLength );
// Source device identity = ME
uiccSbTerminalResponseBuf.Append( KMe );
// Destination device identity = SIM
uiccSbTerminalResponseBuf.Append( KSim );
// Add TLV specific data
uiccSbTerminalResponseBuf.Append( aBerTlvSpecificData );
}
else // Empty terminal response => length is zero
{
uiccSbTerminalResponseBuf.Append( 0 );
uiccSbTerminalResponseBuf.Append( 0 );
}
// Save terminal resp transaction id
iTerminalRespTraId = aTransId;
TFLOGSTRING2("TSY: CSatMessHandler::UiccCatReqTerminalResponse iTerminalRespTraId=%d", iTerminalRespTraId);
OstTrace1( TRACE_NORMAL, DUP1_CSATMESSHANDLER_UICCCATREQTERMINALRESPONSE_TD, "CSatMessHandler::UiccCatReqTerminalResponse;iTerminalRespTraId=%d", iTerminalRespTraId );
// Append subblock to ISI message
isiMsg.CopyData(
ISI_HEADER_SIZE + SIZE_UICC_CAT_REQ,
uiccSbTerminalResponse.CompleteSubBlock() );
return( iPnSend->Send( isiMsg.Complete() ) );
}
// -----------------------------------------------------------------------------
// CSatMessHandler::UiccCatRespEnvelope
// Handles UICC response for envelope
// -----------------------------------------------------------------------------
//
TBool CSatMessHandler::UiccCatRespEnvelope( const TIsiReceiveC& aIsiMessage )
{
OstTrace0( TRACE_NORMAL, CSATMESSHANDLER_UICCCATENVELOPERESP_TD, "CSatMessHandler::UiccCatRespEnvelope" );
TFLOGSTRING("TSY:CSatMessHandler::UiccCatRespEnvelope");
TBool handled( EFalse );
TUint8 trId( aIsiMessage.Get8bit( ISI_HEADER_OFFSET_TRANSID ) );
TUint uiccSbApduOffset( 0 );
if ( KErrNone == aIsiMessage.FindSubBlockOffsetById(
ISI_HEADER_SIZE + SIZE_UICC_CAT_RESP,
UICC_SB_APDU,
EIsiSubBlockTypeId16Len16,
uiccSbApduOffset ) )
{
TPtrC8 apduData;
TUint16 apduLength( aIsiMessage.Get16bit(
uiccSbApduOffset + UICC_SB_APDU_OFFSET_APDULENGTH ) );
apduData.Set( aIsiMessage.GetData(
uiccSbApduOffset + UICC_SB_APDU_OFFSET_APDU,
apduLength ) );
// Status bytes are two last bytes in APDU
TUint8 sw1( apduData[apduLength - 2] );
TUint8 sw2( apduData[apduLength - 1] );
if ( KAtkSwDataNtfSw1NormalEnding == sw1
&& KAtkSwDataNtfSw2NormalEnding == sw2 )
{
// SIM responded OK. Remove stored envelope.
iTsySatMessaging->GetSatTimer()->RemoveEnvelope( trId );
if ( iTerminalRespTraId == trId )
{
iTsySatMessaging->SessionEnd( aIsiMessage );
iTerminalRespTraId = KNoTransactionOngoing;
}
}
else
{
// Problems in envelope sending, resend envelope if appropriate.
if ( KErrNone == iTsySatMessaging->GetSatTimer()->
ActivateEnvelopeResend( trId, sw1 ) )
{
TFLOGSTRING( "TSY:CSatMessHandler::UiccCatRespEnvelope, resending of envelope" );
OstTrace0( TRACE_NORMAL, DUP2_CSATMESSHANDLER_UICCCATENVELOPERESP_TD, "CSatMessHandler::UiccCatRespEnvelope,resending of envelope" );
// Envelope will be resent, mark as handled
handled = ETrue;
}
}
}
else // Subblock is mandatory
{
TFLOGSTRING("TSY: CSatMessHandler::UiccCatRespEnvelope - Mandatory subblock UICC_SB_APDU not found");
OstTrace0( TRACE_NORMAL, DUP1_CSATMESSHANDLER_UICCCATENVELOPERESP_TD, "CSatMessHandler::UiccCatRespEnvelope- Mandatory subblock UICC_SB_APDU not found" );
}
return handled;
}
// -----------------------------------------------------------------------------
// CSatMessHandler::UiccCatRespTerminalResponse
// Handles UICC response for envelope
// -----------------------------------------------------------------------------
//
TBool CSatMessHandler::UiccCatRespTerminalResponse(
const TIsiReceiveC& aIsiMessage )
{
OstTrace0( TRACE_NORMAL, DUP2_CSATMESSHANDLER_UICCCATRESPTERMINALRESPONSE_TD, "CSatMessHandler::UiccCatRespTerminalResponse" );
TFLOGSTRING("TSY:CSatMessHandler::UiccCatRespTerminalResponse");
TBool handled( EFalse );
TUint8 trId( aIsiMessage.Get8bit( ISI_HEADER_OFFSET_TRANSID ) );
TUint uiccSbApduOffset( 0 );
if ( KErrNone == aIsiMessage.FindSubBlockOffsetById(
ISI_HEADER_SIZE + SIZE_UICC_CAT_RESP,
UICC_SB_APDU,
EIsiSubBlockTypeId16Len16,
uiccSbApduOffset ) )
{
TPtrC8 apduData;
TUint16 apduLength( aIsiMessage.Get16bit(
uiccSbApduOffset + UICC_SB_APDU_OFFSET_APDULENGTH ) );
apduData.Set( aIsiMessage.GetData(
uiccSbApduOffset + UICC_SB_APDU_OFFSET_APDU,
apduLength ) );
// Status bytes are two last bytes in APDU
TUint8 sw1( apduData[apduLength - 2] );
TUint8 sw2( apduData[apduLength - 1] );
if ( KAtkSwDataNtfSw1NormalEnding == sw1
&& KAtkSwDataNtfSw2NormalEnding == sw2 )
{
TFLOGSTRING("CSatMessHandler::UiccCatRespTerminalResponse, - SIM SESSION END, 90 00 -");
OstTrace0( TRACE_NORMAL, DUP1_CSATMESSHANDLER_UICCCATRESPTERMINALRESPONSE_TD, "CSatMessHandler::UiccCatRespTerminalResponse" );
iTsySatMessaging->SessionEnd( aIsiMessage );
// Set flag to indicate that terminal response has been
// processed by the SIM with status '90 00'.
iTsySatMessaging->GetSatTimer()->
SetProactiveCommandOnGoingStatus( EFalse );
iTerminalRespTraId = KNoTransactionOngoing;
}
handled = ETrue;
#ifdef INFO_PP_ENHANCED_NETWORK_SELECTION
// Only if SET UP EVENT LIST TR is sent
if ( iSetUpEventListTrSent )
{
iSetUpEventListTrSent = EFalse;
iTsySatMessaging->GetEventDownload()->ForceLocationStatusEnvelope();
}
#endif // INFO_PP_ENHANCED_NETWORK_SELECTION
}
else // Subblock is not found
{
TFLOGSTRING("TSY: CSatMessHandler::UiccCatRespTerminalResponse - Subblock UICC_SB_APDU not found");
OstTrace0( TRACE_NORMAL, CSATMESSHANDLER_UICCCATRESPTERMINALRESPONSE_TD, "CSatMessHandler::UiccCatRespTerminalResponse" );
}
return handled;
}
// -----------------------------------------------------------------------------
// CSatMessHandler::GetApplicationId
// (other items were commented in a header).
// -----------------------------------------------------------------------------
//
const TDesC8& CSatMessHandler::GetApplicationFileId()
{
TFLOGSTRING("TSY: CSatMessHandler::GetApplicationId");
OstTrace0( TRACE_NORMAL, CSATMESSHANDLER_GETAPPLICATIONID_TD, "CSatMessHandler::GetApplicationId" );
return iApplFileId;
}
// -----------------------------------------------------------------------------
// CSatMessHandler::SetSatReadyStatus
// Set status of iSatReady flag
// -----------------------------------------------------------------------------
//
void CSatMessHandler::SetSatReadyStatus( TBool aSatReadyStatus )
{
OstTrace0( TRACE_NORMAL, CSATMESSHANDLER_SETSATREADYSTATUS_TD, "CSatMessHandler::SetSatReadyStatus" );
TFLOGSTRING("TSY: CSatMessHandler::SetSatReadyStatus");
iSatReady = aSatReadyStatus;
}
// -----------------------------------------------------------------------------
// CSatMessHandler::GetSatReadyStatus
// Set status of iSatReady flag
// -----------------------------------------------------------------------------
//
TBool CSatMessHandler::GetSatReadyStatus()
{
TFLOGSTRING("TSY: CSatMessHandler::GetSatReadyStatus");
OstTrace0( TRACE_NORMAL, CSATMESSHANDLER_GETSATREADYSTATUS_TD, "CSatMessHandler::GetSatReadyStatus" );
return iSatReady;
}
// -----------------------------------------------------------------------------
// CSatMessHandler::GetTerminalProfileStatus
// Get status of iTerminalProfileSent flag
// -----------------------------------------------------------------------------
//
TBool CSatMessHandler::GetTerminalProfileStatus()
{
TFLOGSTRING("TSY: CSatMessHandler::GetTerminalProfileStatus");
OstTrace0( TRACE_NORMAL, CSATMESSHANDLER_GETTERMINALPROFILESTATUS_TD, "CSatMessHandler::GetTerminalProfileStatus" );
return iTerminalProfileSent;
}
// -----------------------------------------------------------------------------
// CSatMessHandler::GetClut
// Get clut data
// -----------------------------------------------------------------------------
//
const TDesC8& CSatMessHandler::GetClut()
{
TFLOGSTRING("TSY: CSatMessHandler::SetImageInstanceRequestStatus");
OstTrace0( TRACE_NORMAL, CSATMESSHANDLER_GETCLUT_TD, "CSatMessHandler::GetClut" );
return iClutData;
}
// End of file
| [
"dalarub@localhost",
"[email protected]",
"mikaruus@localhost"
]
| [
[
[
1,
1
],
[
3,
13
],
[
15,
46
],
[
49,
49
],
[
51,
117
],
[
119,
122
],
[
124,
125
],
[
128,
186
],
[
188,
200
],
[
202,
219
],
[
221,
255
],
[
257,
268
],
[
270,
281
],
[
283,
298
],
[
300,
333
],
[
335,
337
],
[
339,
342
],
[
345,
356
],
[
358,
365
],
[
367,
373
],
[
375,
377
],
[
380,
386
],
[
388,
399
],
[
401,
432
],
[
434,
478
],
[
480,
481
],
[
485,
485
],
[
488,
490
],
[
500,
521
],
[
523,
542
],
[
544,
562
],
[
564,
591
],
[
593,
629
],
[
631,
663
],
[
665,
786
],
[
788,
867
],
[
869,
901
],
[
903,
938
],
[
940,
999
],
[
1001,
1054
],
[
1056,
1095
],
[
1097,
1130
],
[
1132,
1167
],
[
1169,
1176
],
[
1178,
1182
],
[
1185,
1228
],
[
1230,
1256
],
[
1258,
1293
],
[
1295,
1327
],
[
1329,
1362
],
[
1364,
1398
],
[
1400,
1441
],
[
1443,
1492
],
[
1494,
1545
],
[
1547,
1550
],
[
1553,
1560
],
[
1563,
1601
],
[
1604,
1644
],
[
1649,
1652
],
[
1657,
1657
],
[
1660,
1675
],
[
1677,
1717
],
[
1719,
1766
],
[
1768,
1835
],
[
1842,
1922
],
[
1924,
1934
],
[
1936,
1950
],
[
1952,
1975
],
[
1977,
1981
],
[
1983,
1997
],
[
1999,
2004
],
[
2006,
2009
],
[
2011,
2015
],
[
2020,
2022
],
[
2026,
2026
],
[
2045,
2045
],
[
2047,
2058
],
[
2060,
2082
],
[
2084,
2087
],
[
2089,
2201
],
[
2203,
2211
],
[
2213,
2213
],
[
2215,
2217
],
[
2219,
2232
],
[
2234,
2234
],
[
2236,
2241
],
[
2243,
2246
],
[
2248,
2249
],
[
2251,
2251
],
[
2255,
2267
],
[
2271,
2272
],
[
2274,
2276
],
[
2278,
2281
],
[
2283,
2284
],
[
2286,
2286
],
[
2290,
2299
],
[
2301,
2301
],
[
2303,
2305
],
[
2307,
2322
],
[
2326,
2327
],
[
2329,
2342
],
[
2345,
2354
],
[
2356,
2356
],
[
2358,
2360
],
[
2362,
2376
],
[
2378,
2435
],
[
2437,
2481
],
[
2483,
2503
],
[
2505,
2534
],
[
2536,
2539
],
[
2541,
2541
],
[
2544,
2555
],
[
2560,
2564
],
[
2566,
2568
],
[
2581,
2584
],
[
2586,
2590
],
[
2593,
2596
],
[
2598,
2599
],
[
2601,
2604
],
[
2606,
2607
],
[
2609,
2614
],
[
2617,
2654
],
[
2656,
2672
],
[
2674,
2692
],
[
2694,
2701
],
[
2703,
2711
],
[
2713,
2770
],
[
2772,
2836
],
[
2838,
2842
],
[
2844,
2894
],
[
2896,
2923
],
[
2925,
2927
],
[
2951,
2964
],
[
2966,
2967
],
[
2970,
2970
],
[
2976,
2976
],
[
2998,
3004
],
[
3006,
3015
],
[
3017,
3041
],
[
3044,
3059
],
[
3061,
3081
],
[
3087,
3088
],
[
3090,
3094
],
[
3096,
3096
],
[
3098,
3098
],
[
3100,
3100
],
[
3115,
3115
],
[
3124,
3124
],
[
3150,
3155
],
[
3157,
3160
],
[
3167,
3167
],
[
3169,
3183
],
[
3185,
3202
],
[
3204,
3205
],
[
3207,
3245
],
[
3247,
3253
],
[
3255,
3273
],
[
3275,
3281
],
[
3283,
3303
],
[
3305,
3306
],
[
3308,
3330
],
[
3332,
3349
],
[
3351,
3381
],
[
3383,
3403
],
[
3405,
3424
],
[
3426,
3464
],
[
3466,
3507
],
[
3509,
3539
],
[
3541,
3562
],
[
3564,
3604
],
[
3606,
3631
],
[
3633,
3655
],
[
3657,
3686
],
[
3688,
3709
],
[
3711,
3740
],
[
3742,
3772
],
[
3774,
3815
],
[
3817,
3834
],
[
3836,
3836
],
[
3838,
3838
],
[
3840,
3856
],
[
3858,
3884
],
[
3886,
3899
],
[
3901,
3947
],
[
3949,
3959
],
[
3961,
3985
],
[
3987,
4020
],
[
4022,
4031
],
[
4038,
4041
],
[
4043,
4045
],
[
4049,
4052
],
[
4054,
4055
],
[
4071,
4161
],
[
4163,
4165
],
[
4167,
4170
],
[
4173,
4214
],
[
4217,
4225
],
[
4227,
4230
],
[
4232,
4280
],
[
4282,
4283
],
[
4285,
4287
],
[
4289,
4292
],
[
4295,
4301
],
[
4303,
4303
],
[
4305,
4339
],
[
4342,
4342
],
[
4344,
4348
],
[
4351,
4353
],
[
4357,
4360
],
[
4363,
4377
],
[
4380,
4383
],
[
4386,
4396
],
[
4399,
4402
],
[
4405,
4415
],
[
4418,
4424
],
[
4426,
4429
],
[
4432,
4434
],
[
4438,
4446
],
[
4449,
4465
],
[
4467,
4476
],
[
4478,
4519
],
[
4521,
4533
],
[
4535,
4554
],
[
4556,
4570
],
[
4585,
4585
],
[
4587,
4589
],
[
4592,
4592
],
[
4606,
4614
],
[
4616,
4684
],
[
4686,
4983
],
[
4985,
5018
],
[
5020,
5084
],
[
5086,
5088
],
[
5090,
5090
],
[
5093,
5112
],
[
5114,
5116
],
[
5118,
5150
],
[
5152,
5213
],
[
5215,
5230
],
[
5232,
5258
],
[
5265,
5272
],
[
5274,
5281
],
[
5283,
5296
],
[
5298,
5323
],
[
5325,
5331
],
[
5333,
5347
],
[
5349,
5362
],
[
5364,
5374
],
[
5376,
5388
],
[
5390,
5401
],
[
5403,
5414
],
[
5416,
5420
]
],
[
[
2,
2
],
[
14,
14
],
[
47,
48
],
[
50,
50
],
[
126,
127
],
[
269,
269
],
[
1546,
1546
],
[
1552,
1552
],
[
1561,
1562
],
[
1602,
1602
],
[
1645,
1645
],
[
1647,
1648
],
[
1653,
1653
],
[
1655,
1656
],
[
1658,
1659
],
[
1836,
1841
],
[
2016,
2019
],
[
2023,
2025
],
[
2027,
2028
],
[
2030,
2043
],
[
2088,
2088
],
[
2202,
2202
],
[
2212,
2212
],
[
2214,
2214
],
[
2235,
2235
],
[
2242,
2242
],
[
2247,
2247
],
[
2250,
2250
],
[
2252,
2254
],
[
2269,
2270
],
[
2273,
2273
],
[
2277,
2277
],
[
2282,
2282
],
[
2285,
2285
],
[
2287,
2289
],
[
2300,
2300
],
[
2302,
2302
],
[
2324,
2325
],
[
2328,
2328
],
[
2343,
2344
],
[
2355,
2355
],
[
2357,
2357
],
[
2843,
2843
],
[
3005,
3005
],
[
3083,
3086
],
[
3089,
3089
],
[
3095,
3095
],
[
3097,
3097
],
[
3099,
3099
],
[
3101,
3114
],
[
3116,
3123
],
[
3125,
3144
],
[
3146,
3149
],
[
3156,
3156
],
[
3161,
3166
],
[
3168,
3168
],
[
3206,
3206
],
[
3274,
3274
],
[
3282,
3282
],
[
3307,
3307
],
[
3331,
3331
],
[
4590,
4590
]
],
[
[
118,
118
],
[
123,
123
],
[
187,
187
],
[
201,
201
],
[
220,
220
],
[
256,
256
],
[
282,
282
],
[
299,
299
],
[
334,
334
],
[
338,
338
],
[
343,
344
],
[
357,
357
],
[
366,
366
],
[
374,
374
],
[
378,
379
],
[
387,
387
],
[
400,
400
],
[
433,
433
],
[
479,
479
],
[
482,
484
],
[
486,
487
],
[
491,
499
],
[
522,
522
],
[
543,
543
],
[
563,
563
],
[
592,
592
],
[
630,
630
],
[
664,
664
],
[
787,
787
],
[
868,
868
],
[
902,
902
],
[
939,
939
],
[
1000,
1000
],
[
1055,
1055
],
[
1096,
1096
],
[
1131,
1131
],
[
1168,
1168
],
[
1177,
1177
],
[
1183,
1184
],
[
1229,
1229
],
[
1257,
1257
],
[
1294,
1294
],
[
1328,
1328
],
[
1363,
1363
],
[
1399,
1399
],
[
1442,
1442
],
[
1493,
1493
],
[
1551,
1551
],
[
1603,
1603
],
[
1646,
1646
],
[
1654,
1654
],
[
1676,
1676
],
[
1718,
1718
],
[
1767,
1767
],
[
1923,
1923
],
[
1935,
1935
],
[
1951,
1951
],
[
1976,
1976
],
[
1982,
1982
],
[
1998,
1998
],
[
2005,
2005
],
[
2010,
2010
],
[
2029,
2029
],
[
2044,
2044
],
[
2046,
2046
],
[
2059,
2059
],
[
2083,
2083
],
[
2218,
2218
],
[
2233,
2233
],
[
2268,
2268
],
[
2306,
2306
],
[
2323,
2323
],
[
2361,
2361
],
[
2377,
2377
],
[
2436,
2436
],
[
2482,
2482
],
[
2504,
2504
],
[
2535,
2535
],
[
2540,
2540
],
[
2542,
2543
],
[
2556,
2559
],
[
2565,
2565
],
[
2569,
2580
],
[
2585,
2585
],
[
2591,
2592
],
[
2597,
2597
],
[
2600,
2600
],
[
2605,
2605
],
[
2608,
2608
],
[
2615,
2616
],
[
2655,
2655
],
[
2673,
2673
],
[
2693,
2693
],
[
2702,
2702
],
[
2712,
2712
],
[
2771,
2771
],
[
2837,
2837
],
[
2895,
2895
],
[
2924,
2924
],
[
2928,
2950
],
[
2965,
2965
],
[
2968,
2969
],
[
2971,
2975
],
[
2977,
2997
],
[
3016,
3016
],
[
3042,
3043
],
[
3060,
3060
],
[
3082,
3082
],
[
3145,
3145
],
[
3184,
3184
],
[
3203,
3203
],
[
3246,
3246
],
[
3254,
3254
],
[
3304,
3304
],
[
3350,
3350
],
[
3382,
3382
],
[
3404,
3404
],
[
3425,
3425
],
[
3465,
3465
],
[
3508,
3508
],
[
3540,
3540
],
[
3563,
3563
],
[
3605,
3605
],
[
3632,
3632
],
[
3656,
3656
],
[
3687,
3687
],
[
3710,
3710
],
[
3741,
3741
],
[
3773,
3773
],
[
3816,
3816
],
[
3835,
3835
],
[
3837,
3837
],
[
3839,
3839
],
[
3857,
3857
],
[
3885,
3885
],
[
3900,
3900
],
[
3948,
3948
],
[
3960,
3960
],
[
3986,
3986
],
[
4021,
4021
],
[
4032,
4037
],
[
4042,
4042
],
[
4046,
4048
],
[
4053,
4053
],
[
4056,
4070
],
[
4162,
4162
],
[
4166,
4166
],
[
4171,
4172
],
[
4215,
4216
],
[
4226,
4226
],
[
4231,
4231
],
[
4281,
4281
],
[
4284,
4284
],
[
4288,
4288
],
[
4293,
4294
],
[
4302,
4302
],
[
4304,
4304
],
[
4340,
4341
],
[
4343,
4343
],
[
4349,
4350
],
[
4354,
4356
],
[
4361,
4362
],
[
4378,
4379
],
[
4384,
4385
],
[
4397,
4398
],
[
4403,
4404
],
[
4416,
4417
],
[
4425,
4425
],
[
4430,
4431
],
[
4435,
4437
],
[
4447,
4448
],
[
4466,
4466
],
[
4477,
4477
],
[
4520,
4520
],
[
4534,
4534
],
[
4555,
4555
],
[
4571,
4584
],
[
4586,
4586
],
[
4591,
4591
],
[
4593,
4605
],
[
4615,
4615
],
[
4685,
4685
],
[
4984,
4984
],
[
5019,
5019
],
[
5085,
5085
],
[
5089,
5089
],
[
5091,
5092
],
[
5113,
5113
],
[
5117,
5117
],
[
5151,
5151
],
[
5214,
5214
],
[
5231,
5231
],
[
5259,
5264
],
[
5273,
5273
],
[
5282,
5282
],
[
5297,
5297
],
[
5324,
5324
],
[
5332,
5332
],
[
5348,
5348
],
[
5363,
5363
],
[
5375,
5375
],
[
5389,
5389
],
[
5402,
5402
],
[
5415,
5415
]
]
]
|
93c1db3ddb1e65f6236f490534fc4c6e8bd2817c | b2d46af9c6152323ce240374afc998c1574db71f | /cursovideojuegos/theflostiproject/3rdParty/boost/libs/config/test/no_exceptions_fail.cpp | 2b3a102d3d46a42588ab17f6754cf1ca0e231ea4 | []
| no_license | bugbit/cipsaoscar | 601b4da0f0a647e71717ed35ee5c2f2d63c8a0f4 | 52aa8b4b67d48f59e46cb43527480f8b3552e96d | refs/heads/master | 2021-01-10T21:31:18.653163 | 2011-09-28T16:39:12 | 2011-09-28T16:39:12 | 33,032,640 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,170 | cpp |
// This file was automatically generated on Sun Jul 25 11:47:49 GMTDT 2004,
// by libs/config/tools/generate
// Copyright John Maddock 2002-4.
// Use, modification and distribution are subject to the
// Boost Software License, Version 1.0. (See accompanying file
// LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt)
// See http://www.boost.org/libs/config for the most recent version.
// Test file for macro BOOST_NO_EXCEPTIONS
// This file should not compile, if it does then
// BOOST_NO_EXCEPTIONS need not be defined.
// see boost_no_exceptions.ipp for more details
// Do not edit this file, it was generated automatically by
// ../tools/generate from boost_no_exceptions.ipp on
// Sun Jul 25 11:47:49 GMTDT 2004
// Must not have BOOST_ASSERT_CONFIG set; it defeats
// the objective of this file:
#ifdef BOOST_ASSERT_CONFIG
# undef BOOST_ASSERT_CONFIG
#endif
#include <boost/config.hpp>
#include "test.hpp"
#ifdef BOOST_NO_EXCEPTIONS
#include "boost_no_exceptions.ipp"
#else
#error "this file should not compile"
#endif
int main( int, char *[] )
{
return boost_no_exceptions::test();
}
| [
"ohernandezba@71d53fa2-cca5-e1f2-4b5e-677cbd06613a"
]
| [
[
[
1,
39
]
]
]
|
e02584e7ca5f9d0fa4b10a6caa823a1ae3eeaf91 | 02cd7f7be30f7660f6928a1b8262dc935673b2d7 | / invols --username [email protected]/app_state.cpp | 76f9a095c2a8ab6a18f941f5a459ae2fcc93be00 | []
| no_license | hksonngan/invols | f0886a304ffb81594016b3b82affc58bd61c4c0b | 336b8c2d11d97892881c02afc2fa114dbf56b973 | refs/heads/master | 2021-01-10T10:04:55.844101 | 2011-11-09T07:44:24 | 2011-11-09T07:44:24 | 46,898,469 | 1 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 139 | cpp | #include "app_state.h"
namespace CT
{
int cur_loaded_file_type=0; //0-no file 1-DICOM 2-raw
wxString cur_loaded_file="";
}; | [
"[email protected]"
]
| [
[
[
1,
8
]
]
]
|
f2292c2ee54ccdd97477e37f3eee004bc95a747b | ea12fed4c32e9c7992956419eb3e2bace91f063a | /zombie/code/nebula2/src/gui/nguitextlabel_cmds.cc | 311d21a4b3b04bc7781166adce184efbc898bef3 | []
| no_license | ugozapad/TheZombieEngine | 832492930df28c28cd349673f79f3609b1fe7190 | 8e8c3e6225c2ed93e07287356def9fbdeacf3d6a | refs/heads/master | 2020-04-30T11:35:36.258363 | 2011-02-24T14:18:43 | 2011-02-24T14:18:43 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 10,068 | cc | #include "precompiled/pchngui.h"
//------------------------------------------------------------------------------
// nguitextlabel_cmds.cc
// (C) 2003 RadonLabs GmbH
//------------------------------------------------------------------------------
#include "gui/nguitextlabel.h"
static void n_setfont(void* slf, nCmd* cmd);
static void n_getfont(void* slf, nCmd* cmd);
static void n_setalignment(void* slf, nCmd* cmd);
static void n_getalignment(void* slf, nCmd* cmd);
static void n_settext(void* slf, nCmd* cmd);
static void n_gettext(void* slf, nCmd* cmd);
static void n_gettextextent(void* slf, nCmd* cmd);
static void n_setint(void* slf, nCmd* cmd);
static void n_getint(void* slf, nCmd* cmd);
static void n_setborder(void* slf, nCmd* cmd);
static void n_getborder(void* slf, nCmd* cmd);
static void n_setclipping(void* slf, nCmd* cmd);
static void n_getclipping(void* slf, nCmd* cmd);
static void n_setwordbreak(void* slf, nCmd* cmd);
static void n_getwordbreak(void* slf, nCmd* cmd);
static void n_setvcenter(void* slf, nCmd* cmd);
static void n_calculatenumberoflines(void* slf, nCmd* cmd);
//-----------------------------------------------------------------------------
/**
@scriptclass
nguitextlabel
@cppclass
nGuiTextLabel
@superclass
nguilabel
@classinfo
A gui label which can render ASCII text with optional background bitmap.
*/
void
n_initcmds_nGuiTextLabel(nClass* cl)
{
cl->BeginCmds();
cl->AddCmd("v_setfont_s", 'SFNT', n_setfont);
cl->AddCmd("s_getfont_v", 'GFNT', n_getfont);
cl->AddCmd("v_setalignment_s", 'SAGN', n_setalignment);
cl->AddCmd("s_getalignment_v", 'GAGN', n_getalignment);
cl->AddCmd("v_settext_s", 'STXT', n_settext);
cl->AddCmd("s_gettext_v", 'GTXT', n_gettext);
cl->AddCmd("ff_gettextextent_v", 'GEXT', n_gettextextent);
cl->AddCmd("v_setint_i", 'SINT', n_setint);
cl->AddCmd("i_getint_v", 'GINT', n_getint);
cl->AddCmd("v_setborder_ff", 'SBRD', n_setborder);
cl->AddCmd("ff_getborder_v", 'GBRD', n_getborder);
cl->AddCmd("v_setclipping_b", 'SCLP', n_setclipping);
cl->AddCmd("b_getclipping_v", 'GCLP', n_getclipping);
cl->AddCmd("v_setwordbreak_b", 'SWBR', n_setwordbreak);
cl->AddCmd("b_getwordbreak_v", 'GWBR', n_getwordbreak);
cl->AddCmd("v_setvcenter_b", 'SVCR', n_setvcenter);
cl->AddCmd("i_calculatenumberoflines_ff", 'CNOL', n_calculatenumberoflines);
cl->EndCmds();
}
//-----------------------------------------------------------------------------
/**
@cmd
setfont
@input
s(FontName)
@output
v
@info
Set the font name. The font must have been registered with the
gui server with the nguiserver.addfont command.
*/
static void
n_setfont(void* slf, nCmd* cmd)
{
nGuiTextLabel* self = (nGuiTextLabel*) slf;
self->SetFont(cmd->In()->GetS());
}
//-----------------------------------------------------------------------------
/**
@cmd
getfont
@input
v
@output
s(FontName)
@info
Get the font name.
*/
static void
n_getfont(void* slf, nCmd* cmd)
{
nGuiTextLabel* self = (nGuiTextLabel*) slf;
cmd->Out()->SetS(self->GetFont());
}
//-----------------------------------------------------------------------------
/**
@cmd
setalignment
@input
s(Alignment = left | center | right)
@output
v
@info
Set the (horizontal) text alignment in the text widget.
*/
static void
n_setalignment(void* slf, nCmd* cmd)
{
nGuiTextLabel* self = (nGuiTextLabel*) slf;
const char* str = cmd->In()->GetS();
nGuiTextLabel::Alignment align;
if (strcmp("left", str) == 0) align = nGuiTextLabel::Left;
else if (strcmp("right", str) == 0) align = nGuiTextLabel::Right;
else if (strcmp("center", str) == 0) align = nGuiTextLabel::Center;
else
{
align = nGuiTextLabel::Center;
n_error("nguitextlabel.setalign: Invalid align string '%s'", str);
}
self->SetAlignment(align);
}
//-----------------------------------------------------------------------------
/**
@cmd
getalignment
@input
v
@output
s(Alignment = left | center | right)
@info
Get the (horizontal) text alignment in the text widget.
*/
static void
n_getalignment(void* slf, nCmd* cmd)
{
nGuiTextLabel* self = (nGuiTextLabel*) slf;
switch (self->GetAlignment())
{
case nGuiTextLabel::Left: cmd->Out()->SetS("left"); break;
case nGuiTextLabel::Center: cmd->Out()->SetS("center"); break;
default: cmd->Out()->SetS("right"); break;
}
}
//-----------------------------------------------------------------------------
/**
@cmd
settext
@input
s(TextString)
@output
v
@info
Set the label text as string.
*/
static void
n_settext(void* slf, nCmd* cmd)
{
nGuiTextLabel* self = (nGuiTextLabel*) slf;
self->SetText(cmd->In()->GetS());
}
//-----------------------------------------------------------------------------
/**
@cmd
gettext
@input
v
@output
s(TextString)
@info
Get the label text as string.
*/
static void
n_gettext(void* slf, nCmd* cmd)
{
nGuiTextLabel* self = (nGuiTextLabel*) slf;
cmd->Out()->SetS(self->GetText());
}
//-----------------------------------------------------------------------------
/**
@cmd
gettextextent
@input
v
@output
f(X), f(Y)
@info
Get the text extent for the currently set text and font.
*/
static void
n_gettextextent(void* slf, nCmd* cmd)
{
nGuiTextLabel* self = (nGuiTextLabel*) slf;
const vector2& extent = self->GetTextExtent();
cmd->Out()->SetF(extent.x);
cmd->Out()->SetF(extent.y);
}
//-----------------------------------------------------------------------------
/**
@cmd
setint
@input
i(IntegerValue)
@output
v
@info
Set the label text as an integer.
*/
static void
n_setint(void* slf, nCmd* cmd)
{
nGuiTextLabel* self = (nGuiTextLabel*) slf;
self->SetInt(cmd->In()->GetI());
}
//-----------------------------------------------------------------------------
/**
@cmd
getint
@input
v
@output
i(IntegerValue)
@info
Get the label text as integer.
*/
static void
n_getint(void* slf, nCmd* cmd)
{
nGuiTextLabel* self = (nGuiTextLabel*) slf;
cmd->Out()->SetI(self->GetInt());
}
//-----------------------------------------------------------------------------
/**
@cmd
setborder
@input
f(BorderX), f(BorderY)
@output
v
@info
Set the label's border size.
*/
static void
n_setborder(void* slf, nCmd* cmd)
{
nGuiTextLabel* self = (nGuiTextLabel*) slf;
vector2 v;
v.x = cmd->In()->GetF();
v.y = cmd->In()->GetF();
self->SetBorder(v);
}
//-----------------------------------------------------------------------------
/**
@cmd
getborder
@input
v
@output
f(BorderX), f(BorderY)
@info
Get the label's border size.
*/
static void
n_getborder(void* slf, nCmd* cmd)
{
nGuiTextLabel* self = (nGuiTextLabel*) slf;
const vector2& v = self->GetBorder();
cmd->Out()->SetF(v.x);
cmd->Out()->SetF(v.y);
}
//-----------------------------------------------------------------------------
/**
@cmd
setclipping
@input
b(ClippingFlag)
@output
v
@info
Enable/disable text clipping. Default is enabled.
*/
static void
n_setclipping(void* slf, nCmd* cmd)
{
nGuiTextLabel* self = (nGuiTextLabel*) slf;
self->SetClipping(cmd->In()->GetB());
}
//-----------------------------------------------------------------------------
/**
@cmd
getclipping
@input
v
@output
b(ClippingFlag)
@info
Get the text clipping flag.
*/
static void
n_getclipping(void* slf, nCmd* cmd)
{
nGuiTextLabel* self = (nGuiTextLabel*) slf;
cmd->Out()->SetB(self->GetClipping());
}
//-----------------------------------------------------------------------------
/**
@cmd
setvcenter
@input
b(vertical centering flag)
@output
v
@info
Enable/disable vertical text centering. Default is enabled.
*/
static void
n_setvcenter(void* slf, nCmd* cmd)
{
nGuiTextLabel* self = (nGuiTextLabel*) slf;
self->SetVCenter(cmd->In()->GetB());
}
//-----------------------------------------------------------------------------
/**
@cmd
setwordbreak
@input
b(WordBreakFlag)
@output
v
@info
Enable/disable word break. Default is disabled.
*/
static void
n_setwordbreak(void* slf, nCmd* cmd)
{
nGuiTextLabel* self = (nGuiTextLabel*) slf;
self->SetWordBreak(cmd->In()->GetB());
}
//-----------------------------------------------------------------------------
/**
@cmd
getwordbreak
@input
v
@output
b(WordBreakFlag)
@info
Get the word break flag.
*/
static void
n_getwordbreak(void* slf, nCmd* cmd)
{
nGuiTextLabel* self = (nGuiTextLabel*) slf;
cmd->Out()->SetB(self->GetWordBreak());
}
//-----------------------------------------------------------------------------
/**
@cmd
calculatenumberoflines
@input
f(SizeX)
f(SizeY)
@output
i(NumberOfLines)
@info
Calculate number of lines for given size rectangle
*/
static void
n_calculatenumberoflines(void* slf, nCmd* cmd)
{
nGuiTextLabel* self = (nGuiTextLabel*) slf;
float sizeX = cmd->In()->GetF();
float sizeY = cmd->In()->GetF();
int numLines = self->CalculateNumberOfLines(vector2( sizeX, sizeY ) );
cmd->Out()->SetI( numLines );
}
| [
"magarcias@c1fa4281-9647-0410-8f2c-f027dd5e0a91"
]
| [
[
[
1,
393
]
]
]
|
27da341738dff480ccae224305e2bef1f2b99a70 | 465943c5ffac075cd5a617c47fd25adfe496b8b4 | /FLIGHTPA.CPP | 8d70b924ab2598141729f9b86f073749556a1eda | []
| no_license | paulanthonywilson/airtrafficcontrol | 7467f9eb577b24b77306709d7b2bad77f1b231b7 | 6c579362f30ed5f81cabda27033f06e219796427 | refs/heads/master | 2016-08-08T00:43:32.006519 | 2009-04-09T21:33:22 | 2009-04-09T21:33:22 | 172,292 | 1 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,711 | cpp | /*
Flight path class function definitions ver 0.0
Paul Wilson
5/4/96
*/
# include "flightpa.h"
/***************************************************************************/
FlightPath::FlightPath
(
Position Start_i,
Position Finish_i
) :
Start_c (Start_i),
Finish_c (Finish_i),
AngleToFinish_c (Start_c.AngleTo (Finish_c)),
DistToFinishSquared_c ((Finish_c.X() - Start_c.X()) *
(Finish_c.X() - Start_c.X()) + (Finish_c.Y() - Start_c.Y()) *
(Finish_c.Y() - Start_c.Y()))
{
assert (Start_i != Finish_c);
assert (Start_i.inField());
assert (Finish_i.inField());
assert (Start_i.AngleTo (Finish_i) % DEG_STEP == 0);
}
/***************************************************************************/
Position FlightPath::Start() {
return Start_c;
}
/***************************************************************************/
Position FlightPath::Finish() {
return Finish_c;
}
/***************************************************************************/
Boolean FlightPath::OnFlightPath (Position Position_i) {
Boolean OnAngle, InRange;
int AngleToPosition;
int DistToPositionSquared;
if (Position_i == Start_c) {
OnAngle = True;
InRange = True;
} else {
AngleToPosition = Start_c.AngleTo (Position_i);
OnAngle = (AngleToPosition == AngleToFinish_c);
if (OnAngle) {
DistToPositionSquared = (Position_i.X() - Start_c.X()) *
(Position_i.X() - Start_c.X()) +
(Position_i.Y() - Start_c.Y()) *
(Position_i.Y() - Start_c.Y());
InRange = (DistToPositionSquared <= DistToFinishSquared_c);
}
}
return OnAngle && InRange;
}
/**/ | [
"[email protected]"
]
| [
[
[
1,
76
]
]
]
|
8cf842bbc06ebe5b0bf4c8f97b2d3ab04cdbd259 | f7d5fcb47d370751163d253ac0d705d52bd3c5d5 | /trunk/Sources/source/hapticgraphclasses/HapticConstraint.h | e98f1c8241527e0ba7468f14e0d959954bf1cc95 | []
| no_license | BackupTheBerlios/phantom-graphs-svn | b830eadf54c49ccecf2653e798e3a82af7e0e78d | 6a585ecde8432394c732a72e4860e136d68cc4b4 | refs/heads/master | 2021-01-02T09:21:18.231965 | 2006-02-06T08:44:57 | 2006-02-06T08:44:57 | 40,820,960 | 0 | 0 | null | null | null | null | ISO-8859-1 | C++ | false | false | 4,419 | h | //*******************************************************************************
/// @file HapticConstraint.h
/// @author Katharina Greiner, Matr.-Nr. 943471
/// @date Erstellt am 02.01.2006
/// @date Letzte Änderung 08.01.2006
//*******************************************************************************
// Änderungen:
// 08.01.06 - renderConstraint() hat neuen Parameter pObj bekommen
// - Doku geschrieben
#ifndef _HAPTICCONSTRAINT_H_
#define _HAPTICCONSTRAINT_H_
// Haptic Library includes
#include <HL/hl.h>
class HapticObject;
//...............................................................................
/// @author Katharina Greiner, Matr.-Nr. 943471
///
/// @brief Klasse, die ein HLAPI-Constraint zu einem HapticObject darstellen kann.
///
/// Das Objekt wirkt auf das Phantom-Device je nach dem Wert der snapDistance
/// mehr oder weniger magnetisch, wenn ihm ein HapticConstraint zugeordnet
/// ist.
//...............................................................................
class HapticConstraint
{
protected:
//.......................................................................
/// @brief Der Abstand zwischen der Oberfläche und der Position des Phantom
/// der überschritten werden muss, um das Phantom von der Constraint-
/// Oberfläche zu lösen in Millimetern in Workspace-Koordinaten.
//.......................................................................
HLfloat m_SnapDistance;
//.......................................................................
/// @brief ID, mit der die Constraint-Shape bei HLAPI bekannt ist.
//.......................................................................
const HLuint m_HLConstraintID;
//.......................................................................
/// @brief Flag, das angibt, ob der Constraint gerendert werden soll.
//.......................................................................
bool m_Enabled;
public:
//.......................................................................
/// @brief Konstruktor: Registriert die Constraint-Shape bei HLAPI und
/// initialisiert das Objekt mit den angegebenen Werten.
/// Der Constraint ist defaultmäßig aktiviert.
/// @param snapDist Abstand von der Oberfläche, den das Phantom
/// überschreiten muss, um sich von ihr zu lösen. Defaultwert ist
/// 0.0, was bedeutet, dass kein Constraint wirkt.
//.......................................................................
HapticConstraint( HLfloat snapDist = 0.0 );
//.......................................................................
/// @brief Destruktor: Meldet die Constraint-Shape bei HLAPI ab.
//.......................................................................
virtual ~HapticConstraint();
//.......................................................................
/// @brief Setzt den Wert der m_SnapDistance.
/// @param value Neuer Wert der m_SnapDistance.
//.......................................................................
void setSnapDistance( HLfloat value );
//.......................................................................
/// @brief Rendert ein Constraint für das mit pObj bezeichnete Objekt als
/// eigenständige HLAPI-Shape. Darf nicht innerhalb eines
/// hlBeginShape()/hlEndShape-Blockes aufgerufen werden.
/// @param pObj HapticObject, für das ein Constraint gerendert werden
/// soll.
//.......................................................................
void renderConstraint( HapticObject* pObj );
//.......................................................................
/// @brief Sorgt dafür, dass das Constraint bei einem Aufruf von
/// renderConstraint() gerendert wird.
/// @return Gibt den vorherigen Aktivierungsstatus zurück.
//.......................................................................
bool enable();
//.......................................................................
/// @brief Verhindert, dass das Constraint bei einem Aufruf von
/// renderConstraint() gerendert wird.
/// @return Gibt den vorherigen Aktivierungsstatus zurück.
//.......................................................................
bool disable();
};
#endif // _HAPTICCONSTRAINT_H_ | [
"frosch@a1b688d3-ce07-0410-8a3f-c797401f78de"
]
| [
[
[
1,
99
]
]
]
|
1bd83a03ce6f1f5578f3167a5670c1923abf1be9 | f7d5fcb47d370751163d253ac0d705d52bd3c5d5 | /trunk/Sources/source/hapticgraphclasses/SpringForceEffect.h | c3ce2bcae3e2a37f6d826d79216fcae3e4864a34 | []
| no_license | BackupTheBerlios/phantom-graphs-svn | b830eadf54c49ccecf2653e798e3a82af7e0e78d | 6a585ecde8432394c732a72e4860e136d68cc4b4 | refs/heads/master | 2021-01-02T09:21:18.231965 | 2006-02-06T08:44:57 | 2006-02-06T08:44:57 | 40,820,960 | 0 | 0 | null | null | null | null | ISO-8859-1 | C++ | false | false | 4,160 | h | //*******************************************************************************
/// @file SpringForceEffect.h
/// @author Katharina Greiner, Matr.-Nr. 943471
/// @date Erstellt am 28.01.2006
/// @date Letzte Änderung 05.02.2006
//*******************************************************************************
// Änderungen:
// 05.02.06 - Doku vervollständigt.
#ifndef _SPRINGFORCEEFFECT_H_
#define _SPRINGFORCEEFFECT_H_
// Haptic Library includes
#include <HDU/hduVector.h>
#include "HapticEffect.h"
#include "Utilities.h"
//...............................................................................
/// @author Katharina Greiner, Matr.-Nr. 943471
///
/// @brief Klasse zur Ausgabe einer Federkraft auf dem Phantom Device.
//...............................................................................
class SpringForceEffect : public HapticEffect
{
protected:
//.......................................................................
/// @brief "Größe" der Kraft.
///
/// Für weiterführende Erkärungen s. "API Reference" des
/// OpenHaptics Toolkit.
//.......................................................................
double m_Magnitude;
//.......................................................................
/// @brief Zunahme der Kraft.
///
/// Für weiterführende Erkärungen s. "API Reference" des
/// OpenHaptics Toolkit.
//.......................................................................
double m_Gain;
//.......................................................................
/// @brief Ankerpunkt der dargestellten Federkraft.
//.......................................................................
hduVector3Dd m_AnchorPosition;
//=======================================================================
// von HapticEffect geerbte Methoden
//=======================================================================
//.......................................................................
/// @brief Spezifiziert die Eigenschaften des Effektes für HLAPI.
//.......................................................................
virtual void renderProperties();
//=======================================================================
public:
//.......................................................................
/// @brief Konstruktor: Initialisiert den Effekt mit den angegebenen Werten.
/// @param magnitude "Größe" der Kraft.
/// @param gain Zunahme der Kraft.
/// @param anchor Ankerpunkt der dargestellten Federkraft.
//.......................................................................
SpringForceEffect( double magnitude, double gain, Position anchor );
//.......................................................................
/// @brief Destruktor: Gibt die Resourcen des Objekts frei.
//.......................................................................
virtual ~SpringForceEffect();
//.......................................................................
/// @brief Setzt den Wert für die Magnitude der Kraft.
/// @param value Neuer Wert für die Magnitude der Kraft.
//.......................................................................
void setMagnitude( double value );
//.......................................................................
/// @brief Setzt den Wert für die Zunahme der Kraft.
/// @param value Neuer Wert für die Zunahme der Kraft.
//.......................................................................
virtual void setGain( double value );
//.......................................................................
/// @brief Ändert den Ankerpunkt der dargestellten Federkraft.
/// @param x x-Koordinate des neuen Ankerpunktes.
/// @param y y-Koordinate des neuen Ankerpunktes.
/// @param z z-Koordinate des neuen Ankerpunktes.
//.......................................................................
void setAnchorPosition( double x, double y, double z );
};
#endif // _SPRINGFORCEEFFECT_H_ | [
"frosch@a1b688d3-ce07-0410-8a3f-c797401f78de"
]
| [
[
[
1,
99
]
]
]
|
1cf65d7ef450e265c3587e0cf9a44c453f40501d | 9a48be80edc7692df4918c0222a1640545384dbb | /Libraries/Boost1.40/libs/wave/test/testwave/testfiles/t_1_004.cpp | b6c85a5fd2dcf1f2fe6c895f8289f5688aa4c06c | [
"BSL-1.0"
]
| permissive | fcrick/RepSnapper | 05e4fb1157f634acad575fffa2029f7f655b7940 | a5809843f37b7162f19765e852b968648b33b694 | refs/heads/master | 2021-01-17T21:42:29.537504 | 2010-06-07T05:38:05 | 2010-06-07T05:38:05 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 2,269 | cpp | /*=============================================================================
Boost.Wave: A Standard compliant C++ preprocessor library
http://www.boost.org/
Copyright (c) 2001-2009 Hartmut Kaiser. Distributed under the Boost
Software License, Version 1.0. (See accompanying file
LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt)
=============================================================================*/
//O --variadics
// Tests macro expansion order in conjunction with the need to skip expansion
// of the same macro as it is currently expanded.
#define CONCAT(a, b) a ## b
#define CONCAT_INDIRECT() CONCAT
//R #line 20 "t_1_004.cpp"
//R CONCAT(1, 2)
CONCAT(CON, CAT)(1, 2)
//R #line 23 "t_1_004.cpp"
//R CONCAT(1, 2)
CONCAT(CON, CAT(1, 2))
//R #line 26 "t_1_004.cpp"
//R 12
CONCAT(CONCAT_, INDIRECT)()(1, 2)
//R #line 29 "t_1_004.cpp"
//R CONCAT(1, 2)
CONCAT(CONCAT_, INDIRECT())(1, 2)
//R #line 32 "t_1_004.cpp"
//R 1 CONCAT(2, 3)
CONCAT(1, CONCAT(2, 3))
//H 10: t_1_004.cpp(15): #define
//H 08: t_1_004.cpp(15): CONCAT(a, b)=a ## b
//H 10: t_1_004.cpp(16): #define
//H 08: t_1_004.cpp(16): CONCAT_INDIRECT()=CONCAT
//H 00: t_1_004.cpp(20): CONCAT(CON, CAT), [t_1_004.cpp(15): CONCAT(a, b)=a ## b]
//H 02: CONCAT
//H 03: CONCAT
//H 00: t_1_004.cpp(23): CONCAT(CON, CAT(1, 2)), [t_1_004.cpp(15): CONCAT(a, b)=a ## b]
//H 02: CONCAT(1, 2)
//H 03: CONCAT(1, 2)
//H 00: t_1_004.cpp(26): CONCAT(CONCAT_, INDIRECT), [t_1_004.cpp(15): CONCAT(a, b)=a ## b]
//H 02: CONCAT_INDIRECT
//H 03: CONCAT_INDIRECT
//H 00: t_1_004.cpp(26): CONCAT_INDIRECT(), [t_1_004.cpp(16): CONCAT_INDIRECT()=CONCAT]
//H 02: CONCAT
//H 03: CONCAT
//H 00: t_1_004.cpp(16): CONCAT(1, 2), [t_1_004.cpp(15): CONCAT(a, b)=a ## b]
//H 02: 12
//H 03: 12
//H 00: t_1_004.cpp(29): CONCAT(CONCAT_, INDIRECT()), [t_1_004.cpp(15): CONCAT(a, b)=a ## b]
//H 02: CONCAT_INDIRECT()
//H 00: t_1_004.cpp(29): CONCAT_INDIRECT(), [t_1_004.cpp(16): CONCAT_INDIRECT()=CONCAT]
//H 02: CONCAT
//H 03: CONCAT
//H 03: CONCAT
//H 00: t_1_004.cpp(32): CONCAT(1, CONCAT(2, 3)), [t_1_004.cpp(15): CONCAT(a, b)=a ## b]
//H 02: 1CONCAT(2, 3)
//H 03: 1CONCAT(2, 3)
| [
"metrix@Blended.(none)"
]
| [
[
[
1,
88
]
]
]
|
3141ebd74155d6fac76fe39d82d212e1c99e185a | b7c9a0c9ef8ad8d7275ebfa24ba21d55caec3f77 | /samples/demo4/test.cpp | a29a2723429f5b7c955383ac36ce3616f45922a9 | []
| no_license | KapLex/libnge2 | bde1aaf683c1501a298e038cd4d3df3ffa98e21f | bdccf1f01d93bf46241625e29a57cba84c0c5be5 | refs/heads/master | 2021-05-29T18:11:12.642465 | 2011-10-15T10:15:21 | 2011-10-15T10:15:21 | null | 0 | 0 | null | null | null | null | GB18030 | C++ | false | false | 927 | cpp | #include "libnge2.h"
#include "cAnimation.h"
#include <stdio.h>
/**
* nge_test:最简单的nge程序:显示一张图片
*/
//退出标识
int game_quit = 0;
//背景图片
image_p p_bg = NULL;
extern "C"
int main(int argc, char* argv[])
{
//初始化NGE分为VIDEO,AUDIO,这里是只初始化VIDEO,如果初始化所有用INIT_VIDEO|INIT_AUDIO,或者INIT_ALL
NGE_Init(INIT_VIDEO);
//最后一个参数是psp swizzle优化,通常填1
p_bg = image_load("images/demo4_bg.png",DISPLAY_PIXEL_FORMAT_8888,1);
if(p_bg == NULL)
printf("can not open file!\n");
CAnimation* ani = new CAnimation("images/demo4_man.png");
while ( !game_quit )
{
ShowFps();
ani->Input();
ani->Update();
//draw target
BeginScene(1);
ImageToScreen(p_bg,0,0);
ani->Show();
EndScene();
LimitFps(60);
}
image_free(p_bg);
NGE_Quit();
delete ani;
return 0;
}
| [
"[email protected]",
"[email protected]"
]
| [
[
[
1,
2
],
[
4,
49
]
],
[
[
3,
3
]
]
]
|
8f0a64472f42f01c73a73ca5d05cf33f85ded130 | 0f8559dad8e89d112362f9770a4551149d4e738f | /Wall_Destruction/Havok/Source/Physics/Utilities/Constraint/Chain/hkpConstraintChainUtil.h | f2b75834bc54d724f3edabe94885fd9c3153aa91 | []
| no_license | TheProjecter/olafurabertaymsc | 9360ad4c988d921e55b8cef9b8dcf1959e92d814 | 456d4d87699342c5459534a7992f04669e75d2e1 | refs/heads/master | 2021-01-10T15:15:49.289873 | 2010-09-20T12:58:48 | 2010-09-20T12:58:48 | 45,933,002 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 4,246 | h | /*
*
* Confidential Information of Telekinesys Research Limited (t/a Havok). Not for disclosure or distribution without Havok's
* prior written consent. This software contains code, techniques and know-how which is confidential and proprietary to Havok.
* Level 2 and Level 3 source code contains trade secrets of Havok. Havok Software (C) Copyright 1999-2009 Telekinesys Research Limited t/a Havok. All Rights Reserved. Use of this software is subject to the terms of an end user license agreement.
*
*/
#ifndef HK_UTILITIES_CONSTRAINT_CHIAN_UTIL_H
#define HK_UTILITIES_CONSTRAINT_CHIAN_UTIL_H
#include <Common/Base/hkBase.h>
class hkpConstraintInstance;
class hkpConstraintMotor;
class hkpPositionConstraintMotor;
class hkpConstraintChainInstance;
class hkpBallSocketChainData;
class hkpEntity;
class hkVector4;
class hkpConstraintInstance;
class hkpConstraintMotor;
class hkpPositionConstraintMotor;
class hkpConstraintChainInstance;
class hkpBallSocketChainData;
class hkpEntity;
class hkVector4;
class hkQuaternion;
/// Constraint chain utility functions.
class hkpConstraintChainUtil
{
public:
//
// Chain construction functions
//
/// This function builds a constraint chain instance, and a powered chain data.
/// These are build from the ordered constraints list.
/// All the constraints are assumed to be powered ragdoll/hinge constraints.
/// The function triggers an assert otherwise.
static hkpConstraintChainInstance* HK_CALL buildPoweredChain(hkArray<hkpConstraintInstance*>& constraints, hkBool cloneMotors);
/// This function adds a new constraint to a ball-socket constraint chain.
static void HK_CALL addConstraintToBallSocketChain( hkpConstraintChainInstance* instance, hkpEntity* entityToAppend, const hkVector4& pivotWs );
/// This function adds a new constraint to a powered constraint chain.
static void HK_CALL addConstraintToPoweredChain( hkpConstraintChainInstance* instance, hkpEntity* entityToAppend, const hkVector4& pivotWs, hkpConstraintMotor* motor0, hkpConstraintMotor* motor1, hkpConstraintMotor* motor2 );
/// This function adds a new constraint to a ball-socket constraint chain.
static hkResult HK_CALL addConstraintToChain(hkpConstraintInstance* newChildInstance, hkpConstraintChainInstance* chainInstance, hkpBallSocketChainData* chainData);
//
// Helper functions
//
/// This attempts to find a connection from entityA to entityB along the constraints in the allConstraint list.
/// Upon success, the function return HK_SUCCESS value and fills the entitiesOut and constraintsOut with ordered lists
/// of entities and constraints visited on the shortes path.
/// The function returns HK_FAILURE when no path connects entityA and entityB.
static hkResult HK_CALL findConstraintLinkBetweenEntities(const hkArray<hkpConstraintInstance*>& allConstraints, hkpEntity* entityA, hkpEntity* entityB, hkArray<hkpEntity*>& entitiesOut, hkArray<hkpConstraintInstance*>& constraintsOut);
/// This returns a list of hkEntities linked to the specified entity by any of the constraints in the allConstraints list.
/// The entities found are placed in the entitiesOut array, and the constraintsOut array contains the corresponding constraints, which lead to those entities.
static void HK_CALL getAdjointEntities(const hkArray<hkpConstraintInstance*>& allConstraints, const hkpEntity* entity, hkArray<hkpEntity*>& entitiesOut, hkArray<hkpConstraintInstance*>& constraintsOut);
};
#endif // HK_UTILITIES_CONSTRAINT_CHIAN_UTIL_H
/*
* Havok SDK - NO SOURCE PC DOWNLOAD, BUILD(#20091222)
*
* Confidential Information of Havok. (C) Copyright 1999-2009
* Telekinesys Research Limited t/a Havok. All Rights Reserved. The Havok
* Logo, and the Havok buzzsaw logo are trademarks of Havok. Title, ownership
* rights, and intellectual property rights in the Havok software remain in
* Havok and/or its suppliers.
*
* Use of this software for evaluation purposes is subject to and indicates
* acceptance of the End User licence Agreement for this product. A copy of
* the license is included with this software and is also available at www.havok.com/tryhavok.
*
*/
| [
"[email protected]"
]
| [
[
[
1,
87
]
]
]
|
448a1fe340d411fd3b850dccc0a646ad437be20d | 0f8559dad8e89d112362f9770a4551149d4e738f | /Wall_Destruction/Havok/Source/Physics/Collide/Shape/Compound/Tree/Mopp/Modifiers/hkpRemoveTerminalsMoppModifier.h | a422e92591eeceb5618ecfb7dfe20f70ff3911b8 | []
| no_license | TheProjecter/olafurabertaymsc | 9360ad4c988d921e55b8cef9b8dcf1959e92d814 | 456d4d87699342c5459534a7992f04669e75d2e1 | refs/heads/master | 2021-01-10T15:15:49.289873 | 2010-09-20T12:58:48 | 2010-09-20T12:58:48 | 45,933,002 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 5,204 | h | /*
*
* Confidential Information of Telekinesys Research Limited (t/a Havok). Not for disclosure or distribution without Havok's
* prior written consent. This software contains code, techniques and know-how which is confidential and proprietary to Havok.
* Level 2 and Level 3 source code contains trade secrets of Havok. Havok Software (C) Copyright 1999-2009 Telekinesys Research Limited t/a Havok. All Rights Reserved. Use of this software is subject to the terms of an end user license agreement.
*
*/
//
//
#ifndef HK_COLLIDE2_MOPP_REMOVE_TERMINALS_MODIFIER_H
#define HK_COLLIDE2_MOPP_REMOVE_TERMINALS_MODIFIER_H
#include <Physics/Internal/Collide/Mopp/Machine/hkpMoppModifier.h>
class hkpMoppCode;
class hkpShapeCollection;
class hkBitField;
extern const hkClass hkpRemoveTerminalsMoppModifierClass;
/// This class allows you to efficiently remove terminals from a mopp.
/// You can use many instances of this class so long as each instance removes different
/// terminals from the mopp. This class queries the mopp with the AABB of all terminals
/// being removed to speed up the building of the internal tables. To get good performance,
/// the triangles to remove should be all in the same area (so that the AABB is small).
/// The construction of a hkpRemoveTerminalsMoppModifier does the AABB query described
/// above, so is not as fast as the actual removal, or you can use a precalculated AABB.
/// Since applying a modifier (via the applyRemoveTerminals() method) modifies the mopp
/// code in-place, to 'undo' a removal (for example on level restart/reload) you must use
/// the same modifier and call the undoRemoveTerminals() method.
/// N.B. Modifiers must be 'undone' in the *reverse order* to that in which they were applied.
class hkpRemoveTerminalsMoppModifier: public hkReferencedObject, public hkpMoppModifier
{
public:
HK_DECLARE_CLASS_ALLOCATOR( HK_MEMORY_CLASS_MOPP );
HK_DECLARE_REFLECTION();
/// Build this modifier (which does an aabb query on the mopp) but does not
/// alter the moppCode yet, so you can pre-construct this object.
/// It calculates the quety aabb based on the shapes in the shapesContainer using keysToRemove
hkpRemoveTerminalsMoppModifier( const hkpMoppCode* moppCode, const hkpShapeContainer* shapeContainer, const hkArray<hkpShapeKey>& keysToRemove );
/// Build this modifier (which does an aabb query on the mopp) but does not
/// alter the moppCode yet, so you can pre-construct this object. This version
/// uses a precalculated aabb and is roughly 2-10 times faster than the other constructor
hkpRemoveTerminalsMoppModifier( const hkpMoppCode* moppCode, const hkAabb& precalculatedAabb, const hkArray<hkpShapeKey>& keysToRemove );
virtual ~hkpRemoveTerminalsMoppModifier();
hkpRemoveTerminalsMoppModifier (hkFinishLoadedObjectFlag f) : hkReferencedObject(f), m_removeInfo(f) {}
/// Actually remove the terminals from the moppCode. This function is very fast.
void applyRemoveTerminals( hkpMoppCode* moppCode );
/// Undo the removal of the terminals.
/// N.B. Modifiers must be 'undone' in the reverse order to that in which they
/// were 'applied'. This function is very fast.
void undoRemoveTerminals( hkpMoppCode* moppCode );
protected:
hkpRemoveTerminalsMoppModifier(): m_tempShapesToRemove(HK_NULL) { }
// hkpMoppModifier interface implementation
virtual hkBool shouldTerminalBeRemoved( hkUint32 id, const hkUint32 *properties );
// hkpMoppModifier interface implementation
virtual void addTerminalRemoveInfo( hkInt32 relativeMoppAddress );
protected:
/// This member stores history of what has been removed from the MOPP code.
/// Bits 0-7: The original MOPP code instruction.
/// Bits 8-31: The offset in the MOPP where the instruction was located.
hkArray<hkUint32> m_removeInfo;
/// for construction only
const hkArray<hkpShapeKey>* m_tempShapesToRemove; //+nosave
};
class hkpRemoveTerminalsMoppModifier2: public hkpRemoveTerminalsMoppModifier
{
public:
/// Scan the entire mopp and remove everything which is not set in enabledKeys
hkpRemoveTerminalsMoppModifier2( const hkpMoppCode* moppCode, const hkBitField& enabledKeys );
protected:
// hkpMoppModifier interface implementation
virtual hkBool shouldTerminalBeRemoved( hkUint32 id, const hkUint32 *properties );
protected:
const hkBitField* m_enabledKeys;
};
#endif // HK_COLLIDE2_MOPP_REMOVE_TERMINALS_MODIFIER_H
/*
* Havok SDK - NO SOURCE PC DOWNLOAD, BUILD(#20091222)
*
* Confidential Information of Havok. (C) Copyright 1999-2009
* Telekinesys Research Limited t/a Havok. All Rights Reserved. The Havok
* Logo, and the Havok buzzsaw logo are trademarks of Havok. Title, ownership
* rights, and intellectual property rights in the Havok software remain in
* Havok and/or its suppliers.
*
* Use of this software for evaluation purposes is subject to and indicates
* acceptance of the End User licence Agreement for this product. A copy of
* the license is included with this software and is also available at www.havok.com/tryhavok.
*
*/
| [
"[email protected]"
]
| [
[
[
1,
114
]
]
]
|
572373707e26224cd153fbde4ca7682a35ad7f01 | e5f7a02c92c5a60c924e07813bc0b7b8944c2ce8 | /4-functional/4.3-c/test.cpp | 235f1167e9cc684fc493e92037e786ab991c48d8 | []
| no_license | 7shi/thunkben | b8fe8f29b43c030721e8a08290c91275c9f455fe | 9bc99c5a957e087bb41bd6f87cf7dfa44e7b55f6 | refs/heads/main | 2022-12-27T19:53:39.322464 | 2011-11-30T16:57:45 | 2011-11-30T16:57:45 | 303,163,701 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 698 | cpp | #include <functional>
#include <stdio.h>
struct Test1 {
int n;
Test1(int n) : n(n) {}
void show() {
printf("%d\n", n);
}
};
struct Test2 {
int n;
Test2(int n) : n(n) {}
void show() {
printf("%d\n", n);
}
};
struct Test3 {
static void show() {
printf("?\n");
}
};
void show() {
printf("!\n");
}
void call(const std::function<void()> &f) {
f();
}
int main() {
Test1 t1(1);
Test2 t2(2);
auto f1 = std::bind(&Test1::show, &t1);
auto f2 = [&] { t2.show(); };
auto f3 = Test3::show;
auto f4 = show;
call(f1);
call(f2);
call(f3);
call(f4);
}
| [
"[email protected]"
]
| [
[
[
1,
45
]
]
]
|
6292b176daeae6e5aff55a494bba32ad648a2175 | f4d39655394aebbb524146cc7a61f93505289ce7 | /parallel/ParallelPollard.h | 9b85e568f7cd1c13707adac94c7097cffdcd568d | []
| no_license | pjacosta/ECDLP-Pollard | b9ded826e7f9d07791a6b8a5e4b8e7bd6259266a | d0a4ebf0dc241cf0fc108a639c4c4e52b89ffba9 | refs/heads/master | 2023-03-19T14:59:15.270344 | 2010-04-20T23:39:07 | 2010-04-20T23:39:07 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 650 | h | #ifndef _PARALLELPOLLARD_H
#define _PARALLELPOLLARD_H
#include <fstream>
#include "ParallelIdentity.h"
// Need some classes
class gf2n;
class ecurve;
class bint;
class epoint;
class ParallelPollard
{
public:
/* Constructors */
ParallelPollard(const ParallelIdentity &identity);
/* Destructors */
virtual ~ParallelPollard();
/* Accessor methods */
const ParallelIdentity &get_identity(void) const;
/* Worker methods */
virtual void run(void);
protected:
ParallelIdentity identity;
gf2n *field;
ecurve *curve;
bint *functionA;
bint *functionB;
epoint *functionR;
int instance;
};
#endif
| [
"grizenko.a@211633f8-0eb2-11df-8d37-15e3504968c6"
]
| [
[
[
1,
40
]
]
]
|
8d3a39d01925e6e5f86877b4f56a562cca407f42 | 7956f4ceddbbcbabd3dd0ae211899cfa5934fc7a | /metaballs3d/trunk/OgreMetaballs/MarchingCubesImpl.h | d1fc20316dfdfadfd6d6bf18b05654921ab6b7da | []
| no_license | pranavsureshpn/gpusphsim | 8d77cde45f5951aee65a13d1ea7edcb5837c6caa | 723d950efbd0d2643edb4b99845bcc658ce38f20 | refs/heads/master | 2021-01-10T05:18:21.705120 | 2011-09-08T01:58:38 | 2011-09-08T01:58:38 | 50,779,129 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 862 | h | #pragma once
#include "Common.h"
#include "ScalarField3D.h"
#include <vector>
#include "MarchingCubesInterface.h"
class MarchingCubesImpl : public MarchingCubesInterface
{
public:
MarchingCubesImpl(DynamicMesh* meshBuilder);
virtual ~MarchingCubesImpl();
protected:
virtual void SampleSpace();
virtual void March();
virtual void SampleCube(SamplingGridCube& cube);
virtual void ResetGridVertexBuffer(const size_t elementNum);
virtual void ResetGridCubesBuffer(const size_t elementNum);
virtual void freeGridVertexBuffer();
virtual void freeGridCubesBuffer();
virtual SamplingGridVertice& GetGridVertice(int i, int j, int k);
virtual SamplingGridCube& GetGridCube(int i, int j, int k);
private:
std::vector<SamplingGridVertice> m_samplingGridVertices;
std::vector<SamplingGridCube> m_samplingGridCubes;
};
| [
"yaoyansi@cd07e373-eec6-1eb2-8c47-9a5824a9cb26"
]
| [
[
[
1,
34
]
]
]
|
bc03de3cfe011ac1b416e2afc0f5ca4c719a239e | 009a66e07afff717cc8d6d5223d8a3019df8c3ca | /item.cpp | 3b6cdbb404bca202738f48be06039d7e4dbbcafb | []
| no_license | zorbathut/purebackup | a974c19ecacf82578b2f65c332674377828ad706 | 6983fb9245b4ea78707555bfd545a78b0d97c5ba | refs/heads/master | 2020-02-26T15:12:01.298029 | 2011-05-03T05:53:33 | 2011-05-03T05:53:33 | 1,694,845 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 7,458 | cpp | /*
PureBackup - human-readable backup output
Copyright (C) 2005 Ben Wilhelm
This program is free software; you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation; version 2 of the license only.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program; if not, write to the Free Software
Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301
*/
#include "item.h"
#include "debug.h"
#include "parse.h"
#include <openssl/sha.h>
string Metadata::toKvd() const {
kvData kvd;
kvd.category = "metadata";
kvd.kv["timestamp"] = StringPrintf("%lld", timestamp);
return putkvDataInlineString(kvd);
}
Metadata metaParseFromKvd(kvData kvd) {
CHECK(kvd.category == "metadata");
Metadata mtd;
sscanf(kvd.consume("timestamp").c_str(), "%lld", &mtd.timestamp);
return mtd;
}
#ifdef WIN32API
void ItemShunt::seek(long long pos) {
LONG low = pos;
LONG high = pos >> 32;
SetFilePointer(local_file, low, &high, FILE_BEGIN);
CHECK(GetLastError() == NO_ERROR);
}
int ItemShunt::read(char *buffer, int len) {
DWORD out;
if(!ReadFile(local_file, buffer, len, &out, NULL)) {
printf("Problem with reading from %s\n", fname.c_str());
CHECK(0);
}
return out;
}
ItemShunt* ItemShunt::LocalFile(const string &local_fname) {
HANDLE local_file = CreateFile(local_fname.c_str(), GENERIC_READ, FILE_SHARE_READ | FILE_SHARE_WRITE, NULL, OPEN_EXISTING, 0, NULL);
if(local_file == INVALID_HANDLE_VALUE) {
printf("Failure at opening %s!\n", local_fname.c_str());
return NULL;
}
ItemShunt *isr = new ItemShunt;
isr->local_file = local_file;
isr->fname = local_fname;
return isr;
}
ItemShunt::ItemShunt() {
local_file = NULL;
}
ItemShunt::~ItemShunt() {
CloseHandle(local_file);
}
#else
void ItemShunt::seek(long long pos) {
fseeko(local_file, pos, SEEK_SET);
}
int ItemShunt::read(char *buffer, int len) {
return fread(buffer, 1, len, local_file);
}
ItemShunt::ItemShunt(const string &local_fname) {
local_file = fopen(local_fname.c_str(), "rb");
CHECK(local_file);
}
ItemShunt::~ItemShunt() {
fclose(local_file);
}
#endif
ItemShunt *Item::open() const {
CHECK(type == MTI_LOCAL);
return ItemShunt::LocalFile(local_path);
}
Checksum Item::signature() const {
return signaturePart(size());
}
Checksum Item::signaturePart(long long len) const {
if(!isReadable()) {
printf("Isn't readable: %s\n", local_path.c_str());
CHECK(0);
}
for(int i = 0; i < sss.size(); i++) {
if(sss[i].first == len)
return sss[i].second;
}
for(int i = 0; i < css.size(); i++) {
if(css[i].first == len) {
Checksum cst = css[i].second;
memset(cst.bytes, 0, sizeof(cst.bytes));
sss.push_back(make_pair(len, cst));
return cst;
}
}
CHECK(type == MTI_LOCAL);
Checksum tcs;
memset(tcs.bytes, 0, sizeof(tcs.bytes));
memset(tcs.signature, 0, sizeof(tcs.signature));
long long poss = (len - sizeof(tcs.signature)) / 2;
if(poss < 0)
poss = 0;
long long pose = poss + 32;
if(pose > size())
pose = size();
ItemShunt *snt = open();
snt->seek(poss);
snt->read((char*)tcs.signature, pose - poss);
delete snt;
sss.push_back(make_pair(len, tcs));
return tcs;
}
Checksum Item::checksum() const {
return checksumPart(size());
}
extern long long cssi;
Checksum Item::checksumPart(long long len) const {
if(!isReadable()) {
printf("Isn't readable: %s", local_path.c_str());
CHECK(0);
}
for(int i = 0; i < css.size(); i++) {
if(css[i].first == len)
return css[i].second;
}
if(type != MTI_LOCAL) {
printf("Invalid type %d, size %lld\n", type, size());
for(int i = 0; i < css.size(); i++)
printf("Css %lld\n", css[i].first);
CHECK(0);
}
//printf("Doing full checksum of %s\n", local_path.c_str());
long long bytu = 0;
SHA_CTX c;
SHA1_Init(&c);
ItemShunt *phil = open();
if(!phil) {
printf("Couldn't open %s during checksum\n", local_path.c_str());
CHECK(isReadable());
CHECK(0);
}
while(1) {
char buf[1024*512];
int rv = phil->read(buf, sizeof(buf));
if(bytu + rv >= len) {
SHA1_Update(&c, buf, len - bytu);
Checksum tcs = signaturePart(len);
SHA1_Final(tcs.bytes, &c);
delete phil;
cssi += len;
css.push_back(make_pair(len, tcs));
return tcs;
} else {
SHA1_Update(&c, buf, rv);
}
if(rv != sizeof(buf)) {
printf("Trying to read %lld from %s, only picked up %lld, last value %d!\n", len, local_path.c_str(), bytu + rv, rv);
CHECK(0);
}
bytu += rv;
}
CHECK(0);
}
void Item::addVersion(int x) {
needed_versions.insert(x);
}
const set<int> &Item::getVersions() const {
return needed_versions;
}
bool Item::isReadable() const {
if(readable == -1) {
if(type == MTI_LOCAL) {
readable = 1;
ItemShunt *fil = open();
if(!fil) {
printf("Cannot read %s\n", local_path.c_str());
readable = 0;
} else {
delete fil;
}
} else if(type == MTI_ORIGINAL) {
readable = 1; // for certain definitions of readable, I suppose
} else {
CHECK(0);
}
}
return readable == 1;
};
bool Item::isChecksummable() const {
return css.size() || isReadable();
}
string Item::toString() const {
return StringPrintf("%lld %lld %s", size(), metadata().timestamp, checksum().toString().c_str());
}
Item Item::MakeLocal(const string &full_path, long long size, const Metadata &meta) {
Item item;
item.type = MTI_LOCAL;
item.local_path = full_path;
item.p_size = size;
item.p_metadata = meta;
return item;
}
Item Item::MakeOriginal(long long size, const Metadata &meta, const Checksum &checksum, const set<int> &versions) {
Item item;
item.type = MTI_ORIGINAL;
item.p_size = size;
item.p_metadata = meta;
item.css.push_back(make_pair(size, checksum));
item.needed_versions = versions;
return item;
}
/*
Item Item::MakeSsh(const string &user, const string &pass, const string &host, const string &full_path, long long size, const Metadata &meta) {
Item item;
item.type = MTI_SSH;
item.p_size = size;
item.p_metadata = meta;
item.ssh_user = user;
item.ssh_pass = pass;
item.ssh_host = host;
item.ssh_path = full_path;
return item;
}*/
Item::Item() {
type = MTI_NONEXISTENT;
readable = -1;
}
int if_presig = 0;
int if_mid = 0;
int if_full = 0;
bool identicalFile(const Item &lhs, const Item &rhs, long long bytes) {
if(bytes == -1) {
if(lhs.size() != rhs.size())
return false; // this shouldn't actually happen
if_presig++;
if(!(lhs.signature() == rhs.signature()))
return false;
if_mid++;
if(!(lhs.checksum() == rhs.checksum())) {
//Checksum cs = lhs.signature();
//printf("%s\n", cs.toString().c_str());
//printf("%s and %s\n", lhs.local_path.c_str(), rhs.local_path.c_str());
return false;
}
if_full++;
return true;
}
return lhs.signaturePart(bytes) == rhs.signaturePart(bytes) && lhs.checksumPart(bytes) == rhs.checksumPart(bytes);
}
| [
"[email protected]"
]
| [
[
[
1,
298
]
]
]
|
f965feb0a74faf6920ae6e09100c76da0accee39 | 6d680e20e4a703f0aa0d4bb5e50568143241f2d5 | /src/passuello/ProvaFirst/ui_ProvaFirst.h | 30a6781e1a0aa8f81640317f448e2d541d280b8a | []
| no_license | sirnicolaz/MobiHealt | f7771e53a4a80dcea3d159eca729e9bd227e8660 | bbfd61209fb683d5f75f00bbf81b24933922baac | refs/heads/master | 2021-01-20T12:21:17.215536 | 2010-04-21T14:21:16 | 2010-04-21T14:21:16 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,347 | h | /********************************************************************************
** Form generated from reading UI file 'ProvaFirst.ui'
**
** Created: Thu 18. Feb 16:14:38 2010
** by: Qt User Interface Compiler version 4.6.2
**
** WARNING! All changes made in this file will be lost when recompiling UI file!
********************************************************************************/
#ifndef UI_PROVAFIRST_H
#define UI_PROVAFIRST_H
#include <QtCore/QVariant>
#include <QtGui/QAction>
#include <QtGui/QApplication>
#include <QtGui/QButtonGroup>
#include <QtGui/QHeaderView>
#include <QtGui/QWidget>
QT_BEGIN_NAMESPACE
class Ui_ProvaFirst
{
public:
void setupUi(QWidget *ProvaFirst)
{
if (ProvaFirst->objectName().isEmpty())
ProvaFirst->setObjectName(QString::fromUtf8("ProvaFirst"));
ProvaFirst->resize(400, 300);
retranslateUi(ProvaFirst);
QMetaObject::connectSlotsByName(ProvaFirst);
} // setupUi
void retranslateUi(QWidget *ProvaFirst)
{
ProvaFirst->setWindowTitle(QApplication::translate("ProvaFirst", "ProvaFirst", 0, QApplication::UnicodeUTF8));
} // retranslateUi
};
namespace Ui {
class ProvaFirst: public Ui_ProvaFirst {};
} // namespace Ui
QT_END_NAMESPACE
#endif // UI_PROVAFIRST_H
| [
"[email protected]"
]
| [
[
[
1,
50
]
]
]
|
92d840e0da9a7560b2417b325e372640148202bb | fc4946d917dc2ea50798a03981b0274e403eb9b7 | /gentleman/gentleman/WindowsAPICodePack/WindowsAPICodePack/DirectX/DirectX/Direct3D10/D3D10InputAssemblerPipelineStage.h | 2150a9b0fbf27f2895be429591d9a0bea5c24227 | []
| no_license | midnite8177/phever | f9a55a545322c9aff0c7d0c45be3d3ddd6088c97 | 45529e80ebf707e7299887165821ca360aa1907d | refs/heads/master | 2020-05-16T21:59:24.201346 | 2010-07-12T23:51:53 | 2010-07-12T23:51:53 | 34,965,829 | 3 | 2 | null | null | null | null | UTF-8 | C++ | false | false | 7,343 | h | //Copyright (c) Microsoft Corporation. All rights reserved.
#pragma once
#include "D3D10PipelineStage.h"
namespace Microsoft { namespace WindowsAPICodePack { namespace DirectX { namespace Direct3D10 {
/// <summary>
/// InputAssembler pipeline stage.
/// </summary>
public ref class InputAssemblerPipelineStage : PipelineStage
{
public:
/// <summary>
/// Get the index buffer that is bound to the input-assembler stage.
/// <para>(Also see DirectX SDK: ID3D10Device::IAGetIndexBuffer)</para>
/// </summary>
/// <param name="outFormat">The format of the data in the index buffer (see <see cref="Format"/>)<seealso cref="Format"/>. These formats provide the size and type of the data in the buffer. The only formats allowed for index buffer data are 16-bit (Format_R16_UINT) and 32-bit (Format_R32_UINT) integers.</param>
/// <param name="outOffset">Offset (in bytes) from the start of the index buffer, to the first index to use.</param>
/// <returns>An index buffer returned by the method (see <see cref="D3DBuffer"/>)<seealso cref="D3DBuffer"/>.</returns>
D3DBuffer^ GetIndexBuffer( [System::Runtime::InteropServices::Out] Format %outFormat, [System::Runtime::InteropServices::Out] UInt32 %outOffset);
/// <summary>
/// Get the input-layout object that is bound to the input-assembler stage.
/// <para>(Also see DirectX SDK: ID3D10Device::IAGetInputLayout)</para>
/// </summary>
/// <returns>The input-layout object (see <see cref="InputLayout"/>)<seealso cref="InputLayout"/>, which describes the input buffers that will be read by the IA stage.</returns>
InputLayout^ GetInputLayout();
/// <summary>
/// Get information about the primitive type, and data order that describes input data for the input assembler stage.
/// <para>(Also see DirectX SDK: ID3D10Device::IAGetPrimitiveTopology)</para>
/// </summary>
/// <returns>The type of primitive, and ordering of the primitive data (see <see cref="PrimitiveTopology"/>)<seealso cref="PrimitiveTopology"/>.</returns>
PrimitiveTopology GetPrimitiveTopology();
/// <summary>
/// Get the vertex buffers bound to the input-assembler stage.
/// <para>(Also see DirectX SDK: ID3D10Device::IAGetVertexBuffers)</para>
/// </summary>
/// <param name="startSlot">The input slot of the first vertex buffer to get. The first vertex buffer is explicitly bound to the start slot; this causes each additional vertex buffer in the array to be implicitly bound to each subsequent input slot. There are 16 input slots.</param>
/// <param name="numBuffers">The number of vertex buffers to get starting at the offset. The number of buffers (plus the starting slot) cannot exceed the total number of IA-stage input slots.</param>
/// <param name="strides">A collection of stride values returned by the method; one stride value for each buffer in the vertex-buffer array. Each stride value is the size (in bytes) of the elements that are to be used from that vertex buffer.</param>
/// <param name="offsets">A collection of offset values returned by the method; one offset value for each buffer in the vertex-buffer array. Each offset is the number of bytes between the first element of a vertex buffer and the first element that will be used.</param>
/// <returns>A collection of vertex buffers returned by the method (see <see cref="D3DBuffer"/>)<seealso cref="D3DBuffer"/>.</returns>
ReadOnlyCollection<D3DBuffer^>^ GetVertexBuffers(UInt32 startSlot, UInt32 numBuffers, [System::Runtime::InteropServices::Out] array<UInt32>^ %strides, [System::Runtime::InteropServices::Out] array<UInt32>^ %offsets);
/// <summary>
/// Bind an index buffer to the input-assembler stage.
/// <para>(Also see DirectX SDK: ID3D10Device::IASetIndexBuffer)</para>
/// </summary>
/// <param name="indexBuffer">A D3DBuffer object, that contains indices. The index buffer must have been created with the indexBuffer flag.</param>
/// <param name="format">A Format that specifies the format of the data in the index buffer. The only formats allowed for index buffer data are 16-bit (Format_R16_UINT) and 32-bit (Format_R32_UINT) integers.</param>
/// <param name="offset">Offset (in bytes) from the start of the index buffer to the first index to use.</param>
/// <remarks>Calling this method using a buffer that is currently bound for writing (i.e. bound to the stream output pipeline stage) will effectively
/// bind null instead because a buffer cannot be bound as both an input and an output at the same time.</remarks>
void SetIndexBuffer(D3DBuffer^ indexBuffer, Format format, UInt32 offset);
/// <summary>
/// Bind an input-layout object to the input-assembler stage.
/// <para>(Also see DirectX SDK: ID3D10Device::IASetInputLayout)</para>
/// </summary>
/// <param name="inputLayout">The input-layout object (see <see cref="InputLayout"/>)<seealso cref="InputLayout"/>, which describes the input buffers that will be read by the IA stage.</param>
void SetInputLayout(InputLayout^ inputLayout);
/// <summary>
/// Bind information about the primitive type, and data order that describes input data for the input assembler stage.
/// <para>(Also see DirectX SDK: ID3D10Device::IASetPrimitiveTopology)</para>
/// </summary>
/// <param name="topology">The type of primitive and ordering of the primitive data (see <see cref="PrimitiveTopology"/>)<seealso cref="PrimitiveTopology"/>.</param>
void SetPrimitiveTopology(PrimitiveTopology topology);
/// <summary>
/// Bind an array of vertex buffers to the input-assembler stage.
/// <para>(Also see DirectX SDK: ID3D10Device::IASetVertexBuffers)</para>
/// </summary>
/// <param name="startSlot">The first input slot for binding. The first vertex buffer is explicitly bound to the start slot; this causes each additional vertex buffer in the array to be implicitly bound to each subsequent input slot. There are 16 input slots (ranges from 0 to D3D10_IA_VERTEX_INPUT_RESOURCE_SLOT_COUNT - 1).</param>
/// <param name="vertexBuffers">A collection of vertex buffers (see <see cref="D3DBuffer"/>)<seealso cref="D3DBuffer"/>.
/// The number of buffers (plus the starting slot) cannot exceed the total number of IA-stage input slots (ranges from 0 to D3D10_IA_VERTEX_INPUT_RESOURCE_SLOT_COUNT - startSlot).
/// The vertex buffers must have been created with the VertexBuffer flag.</param>
/// <param name="strides">An array of stride values; one stride value for each buffer in the vertex-buffer array. Each stride is the size (in bytes) of the elements that are to be used from that vertex buffer.</param>
/// <param name="offsets">An array of offset values; one offset value for each buffer in the vertex-buffer array. Each offset is the number of bytes between the first element of a vertex buffer and the first element that will be used.</param>
void SetVertexBuffers(UInt32 startSlot, IEnumerable<D3DBuffer^>^ vertexBuffers, array<UInt32>^ strides, array<UInt32>^ offsets);
internal:
InputAssemblerPipelineStage() {}
internal:
InputAssemblerPipelineStage(D3DDevice^ parent) : PipelineStage(parent)
{
}
};
} } } }
| [
"lucemia@9e708c16-f4dd-11de-aa3c-59de0406b4f5"
]
| [
[
[
1,
91
]
]
]
|
a89b59a8931711140d54bdbd976ef2df88d7ad11 | 011359e589f99ae5fe8271962d447165e9ff7768 | /src/burn/misc/post90s/d_m92.cpp | c88cbece01a4a0f91713db92019748c66d362bfe | []
| no_license | PS3emulators/fba-next-slim | 4c753375fd68863c53830bb367c61737393f9777 | d082dea48c378bddd5e2a686fe8c19beb06db8e1 | refs/heads/master | 2021-01-17T23:05:29.479865 | 2011-12-01T18:16:02 | 2011-12-01T18:16:02 | 2,899,840 | 1 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 59,005 | cpp | // Irem M92 system games:
//
// port from MAME by OopsWare
//
#include "burnint.h"
#include "burn_ym2151.h"
#include "vez.h"
#include "irem_cpu.h"
static unsigned char *Mem = NULL, *MemEnd = NULL;
static unsigned char *RamStart, *RamEnd;
static unsigned char *RomV33;
static unsigned char *RomV30;
static unsigned char *RomGfx01;
static unsigned char *RomGfx02;
static unsigned char *RamVideo;
static unsigned char *RamV33;
static unsigned char *RamV30;
static unsigned char *RamSpr;
static unsigned char *RamSprCpy;
static unsigned char *RamPal;
static unsigned short *RamCurPal;
static unsigned char DrvButton[8] = {0, 0, 0, 0, 0, 0, 0, 0};
static unsigned char DrvJoy1[8] = {0, 0, 0, 0, 0, 0, 0, 0};
static unsigned char DrvJoy2[8] = {0, 0, 0, 0, 0, 0, 0, 0};
static unsigned char DrvJoy3[8] = {0, 0, 0, 0, 0, 0, 0, 0};
static unsigned char DrvJoy4[8] = {0, 0, 0, 0, 0, 0, 0, 0};
static unsigned char DrvInput[8] = {0, 0, 0, 0, 0, 0, 0, 0};
static unsigned char bRecalcPalette = 0;
static unsigned char DrvReset = 0;
static int m92_irq_vectorbase;
static unsigned int PalBank;
static unsigned char pf1_control[8],pf2_control[8],pf3_control[8],pf4_control[8];
static int pf1_enable,pf2_enable,pf3_enable;
static int pf1_shape,pf2_shape,pf3_shape;
static int pf1_rowscroll,pf2_rowscroll,pf3_rowscroll;
static int pf1_vram_ptr,pf2_vram_ptr,pf3_vram_ptr;
static int m92_sprite_list;
static unsigned char sound_status[2];
static unsigned char sound_latch[2];
static unsigned char irqvector;
static unsigned char m92_sprite_buffer_busy;
static int m92_sprite_buffer_timer;
static int m92_raster_irq_position = 0;
//static int m92_raster_enable = 1;
inline static unsigned int CalcCol(int offs)
{
// xBBBBBGGGGGRRRRR
int nColour = RamPal[offs + 0] | (RamPal[offs + 1] << 8);
int r, g, b;
r = (nColour & 0x001F) << 3; // Red
r |= r >> 5;
g = (nColour & 0x03E0) >> 2; // Green
g |= g >> 5;
b = (nColour & 0x7C00) >> 7; // Blue
b |= b >> 5;
return BurnHighCol(r, g, b, 0);
}
static struct BurnInputInfo hookInputList[] = {
{"P1 Coin", BIT_DIGITAL, DrvButton + 2, "p1 coin"},
{"P1 Start", BIT_DIGITAL, DrvButton + 0, "p1 start"},
{"P1 Up", BIT_DIGITAL, DrvJoy1 + 3, "p1 up"},
{"P1 Down", BIT_DIGITAL, DrvJoy1 + 2, "p1 down"},
{"P1 Left", BIT_DIGITAL, DrvJoy1 + 1, "p1 left"},
{"P1 Right", BIT_DIGITAL, DrvJoy1 + 0, "p1 right"},
{"P1 Button 1", BIT_DIGITAL, DrvJoy1 + 7, "p1 fire 1"},
{"P1 Button 2", BIT_DIGITAL, DrvJoy1 + 6, "p1 fire 2"},
{"P2 Coin", BIT_DIGITAL, DrvButton + 3, "p2 coin"},
{"P2 Start", BIT_DIGITAL, DrvButton + 1, "p2 start"},
{"P2 Up", BIT_DIGITAL, DrvJoy2 + 3, "p2 up"},
{"P2 Down", BIT_DIGITAL, DrvJoy2 + 2, "p2 down"},
{"P2 Left", BIT_DIGITAL, DrvJoy2 + 1, "p2 left"},
{"P2 Right", BIT_DIGITAL, DrvJoy2 + 0, "p2 right"},
{"P2 Button 1", BIT_DIGITAL, DrvJoy2 + 7, "p2 fire 1"},
{"P2 Button 2", BIT_DIGITAL, DrvJoy2 + 6, "p2 fire 2"},
{"P3 Coin", BIT_DIGITAL, DrvJoy3 + 5, "p3 coin"},
{"P3 Start", BIT_DIGITAL, DrvJoy3 + 4, "p3 start"},
{"P3 Up", BIT_DIGITAL, DrvJoy3 + 3, "p3 up"},
{"P3 Down", BIT_DIGITAL, DrvJoy3 + 2, "p3 down"},
{"P3 Left", BIT_DIGITAL, DrvJoy3 + 1, "p3 left"},
{"P3 Right", BIT_DIGITAL, DrvJoy3 + 0, "p3 right"},
{"P3 Button 1", BIT_DIGITAL, DrvJoy3 + 7, "p3 fire 1"},
{"P3 Button 2", BIT_DIGITAL, DrvJoy3 + 6, "p3 fire 2"},
{"P4 Coin", BIT_DIGITAL, DrvJoy4 + 5, "p4 coin"},
{"P4 Start", BIT_DIGITAL, DrvJoy4 + 4, "p4 start"},
{"P4 Up", BIT_DIGITAL, DrvJoy4 + 3, "p4 up"},
{"P4 Down", BIT_DIGITAL, DrvJoy4 + 2, "p4 down"},
{"P4 Left", BIT_DIGITAL, DrvJoy4 + 1, "p4 left"},
{"P4 Right", BIT_DIGITAL, DrvJoy4 + 0, "p4 right"},
{"P4 Button 1", BIT_DIGITAL, DrvJoy4 + 7, "p4 fire 1"},
{"P4 Button 2", BIT_DIGITAL, DrvJoy4 + 6, "p4 fire 2"},
{"Reset", BIT_DIGITAL, &DrvReset, "reset"},
{"Dip A", BIT_DIPSWITCH, DrvInput + 5, "dip"},
{"Dip B", BIT_DIPSWITCH, DrvInput + 6, "dip"},
{"Dip C", BIT_DIPSWITCH, DrvInput + 7, "dip"},
};
STDINPUTINFO(hook)
static struct BurnDIPInfo hookDIPList[] = {
// Defaults
{0x21, 0xFF, 0xFF, 0x00, NULL},
{0x22, 0xFF, 0xFF, 0x00, NULL},
{0x23, 0xFF, 0xFF, 0x00, NULL},
{0, 0xFE, 0, 2, "Flip Screen"},
{0x21, 0x01, 0x01, 0x00, "Off"},
{0x21, 0x01, 0x01, 0x01, "On"},
{0, 0xFE, 0, 2, "Cabinet"},
{0x21, 0x01, 0x02, 0x00, "2 Players"},
{0x21, 0x01, 0x02, 0x02, "4 Players"},
{0, 0xFE, 0, 2, "Coin Slots"},
{0x21, 0x01, 0x04, 0x00, "Common"},
{0x21, 0x01, 0x04, 0x04, "Separate"},
{0, 0xFE, 0, 2, "Coin Mode"},
{0x21, 0x01, 0x08, 0x00, "1"},
{0x21, 0x01, 0x08, 0x08, "2"},
{0, 0xFE, 0, 16, "Coinage"},
{0x21, 0x01, 0xf0, 0x00, "1C_1C"},
{0x21, 0x01, 0xf0, 0x10, "2C_1C"},
{0x21, 0x01, 0xf0, 0x20, "3C_1C"},
{0x21, 0x01, 0xf0, 0x30, "4C_1C"},
{0x21, 0x01, 0xf0, 0x40, "5C_1C"},
{0x21, 0x01, 0xf0, 0x50, "6C_1C"},
{0x21, 0x01, 0xf0, 0x60, "1C_2C"},
{0x21, 0x01, 0xf0, 0x70, "1C_3C"},
{0x21, 0x01, 0xf0, 0x80, "1C_4C"},
{0x21, 0x01, 0xf0, 0x90, "1C_5C"},
{0x21, 0x01, 0xf0, 0xa0, "1C_6C"},
{0x21, 0x01, 0xf0, 0xb0, "2C_3C"},
{0x21, 0x01, 0xf0, 0xc0, "3C_2C"},
{0x21, 0x01, 0xf0, 0xd0, "4C_3C"},
{0x21, 0x01, 0xf0, 0xe0, "2 Coins to Start, 1 to Continue"},
{0x21, 0x01, 0xf0, 0xf0, "Free Play"},
// DIP 2
{0, 0xFE, 0, 4, "Lives"},
{0x22, 0x01, 0x03, 0x00, "2"},
{0x22, 0x01, 0x03, 0x01, "3"},
{0x22, 0x01, 0x03, 0x02, "4"},
{0x22, 0x01, 0x03, 0x03, "1"},
{0, 0xFE, 0, 4, "Difficulty"},
{0x22, 0x01, 0x0C, 0x00, "Normal"},
{0x22, 0x01, 0x0C, 0x04, "Easy"},
{0x22, 0x01, 0x0C, 0x08, "Hard"},
{0x22, 0x01, 0x0C, 0x0C, "Very Easy"},
{0, 0xFE, 0, 2, "Any Button to Start"},
{0x22, 0x01, 0x20, 0x00, "Yes"},
{0x22, 0x01, 0x20, 0x20, "No"},
{0, 0xFE, 0, 2, "Demo Sounds"},
{0x22, 0x01, 0x40, 0x00, "Off"},
{0x22, 0x01, 0x40, 0x40, "On"},
{0, 0xFE, 0, 2, "Service"},
{0x22, 0x01, 0x80, 0x00, "Off"},
{0x22, 0x01, 0x80, 0x80, "On"},
};
STDDIPINFO(hook)
static struct BurnInputInfo inthuntInputList[] = {
{"P1 Coin", BIT_DIGITAL, DrvButton + 2, "p1 coin"},
{"P1 Start", BIT_DIGITAL, DrvButton + 0, "p1 start"},
{"P1 Up", BIT_DIGITAL, DrvJoy1 + 3, "p1 up"},
{"P1 Down", BIT_DIGITAL, DrvJoy1 + 2, "p1 down"},
{"P1 Left", BIT_DIGITAL, DrvJoy1 + 1, "p1 left"},
{"P1 Right", BIT_DIGITAL, DrvJoy1 + 0, "p1 right"},
{"P1 Button 1", BIT_DIGITAL, DrvJoy1 + 7, "p1 fire 1"},
{"P1 Button 2", BIT_DIGITAL, DrvJoy1 + 6, "p1 fire 2"},
{"P2 Coin", BIT_DIGITAL, DrvButton + 3, "p2 coin"},
{"P2 Start", BIT_DIGITAL, DrvButton + 1, "p2 start"},
{"P2 Up", BIT_DIGITAL, DrvJoy2 + 3, "p2 up"},
{"P2 Down", BIT_DIGITAL, DrvJoy2 + 2, "p2 down"},
{"P2 Left", BIT_DIGITAL, DrvJoy2 + 1, "p2 left"},
{"P2 Right", BIT_DIGITAL, DrvJoy2 + 0, "p2 right"},
{"P2 Button 1", BIT_DIGITAL, DrvJoy2 + 7, "p2 fire 1"},
{"P2 Button 2", BIT_DIGITAL, DrvJoy2 + 6, "p2 fire 2"},
{"Reset", BIT_DIGITAL, &DrvReset, "reset"},
{"Dip A", BIT_DIPSWITCH, DrvInput + 5, "dip"},
{"Dip B", BIT_DIPSWITCH, DrvInput + 6, "dip"},
{"Dip C", BIT_DIPSWITCH, DrvInput + 7, "dip"},
};
STDINPUTINFO(inthunt)
static struct BurnDIPInfo inthuntDIPList[] = {
// Defaults
{0x11, 0xFF, 0xFF, 0x00, NULL},
{0x12, 0xFF, 0xFF, 0x00, NULL},
{0x13, 0xFF, 0xFF, 0x00, NULL},
{0, 0xFE, 0, 2, "Flip Screen"},
{0x11, 0x01, 0x01, 0x00, "Off"},
{0x11, 0x01, 0x01, 0x01, "On"},
// {0, 0xFE, 0, 2, "Unknown"},
// {0x11, 0x01, 0x02, 0x00, "Off"},
// {0x11, 0x01, 0x02, 0x02, "On"},
{0, 0xFE, 0, 2, "Coin Slots"},
{0x11, 0x01, 0x04, 0x00, "Common"},
{0x11, 0x01, 0x04, 0x04, "Separate"},
{0, 0xFE, 0, 2, "Coin Mode"},
{0x11, 0x01, 0x08, 0x00, "1"},
{0x11, 0x01, 0x08, 0x08, "2"},
{0, 0xFE, 0, 16, "Coinage"},
{0x11, 0x01, 0xf0, 0x00, "1C_1C"},
{0x11, 0x01, 0xf0, 0x10, "2C_1C"},
{0x11, 0x01, 0xf0, 0x20, "3C_1C"},
{0x11, 0x01, 0xf0, 0x30, "4C_1C"},
{0x11, 0x01, 0xf0, 0x40, "5C_1C"},
{0x11, 0x01, 0xf0, 0x50, "6C_1C"},
{0x11, 0x01, 0xf0, 0x60, "1C_2C"},
{0x11, 0x01, 0xf0, 0x70, "1C_3C"},
{0x11, 0x01, 0xf0, 0x80, "1C_4C"},
{0x11, 0x01, 0xf0, 0x90, "1C_5C"},
{0x11, 0x01, 0xf0, 0xa0, "1C_6C"},
{0x11, 0x01, 0xf0, 0xb0, "2C_3C"},
{0x11, 0x01, 0xf0, 0xc0, "3C_2C"},
{0x11, 0x01, 0xf0, 0xd0, "4C_3C"},
{0x11, 0x01, 0xf0, 0xe0, "2 Coins to Start, 1 to Continue"},
{0x11, 0x01, 0xf0, 0xf0, "Free Play"},
// DIP 2
{0, 0xFE, 0, 4, "Lives"},
{0x12, 0x01, 0x03, 0x00, "2"},
{0x12, 0x01, 0x03, 0x01, "3"},
{0x12, 0x01, 0x03, 0x02, "4"},
{0x12, 0x01, 0x03, 0x03, "1"},
{0, 0xFE, 0, 4, "Difficulty"},
{0x12, 0x01, 0x0C, 0x00, "Normal"},
{0x12, 0x01, 0x0C, 0x04, "Easy"},
{0x12, 0x01, 0x0C, 0x08, "Hard"},
{0x12, 0x01, 0x0C, 0x0C, "Very Easy"},
{0, 0xFE, 0, 2, "Any Button to Start"},
{0x12, 0x01, 0x20, 0x00, "Yes"},
{0x12, 0x01, 0x20, 0x20, "No"},
{0, 0xFE, 0, 2, "Demo Sounds"},
{0x12, 0x01, 0x40, 0x00, "Off"},
{0x12, 0x01, 0x40, 0x40, "On"},
{0, 0xFE, 0, 2, "Service"},
{0x12, 0x01, 0x80, 0x00, "Off"},
{0x12, 0x01, 0x80, 0x80, "On"},
};
STDDIPINFO(inthunt)
// Rom information
static struct BurnRomInfo hookRomDesc[] = {
{ "h-h0-d.3h", 0x040000, 0x40189ff6, BRF_ESS | BRF_PRG }, // CPU 0, V33
{ "h-l0-d.3h", 0x040000, 0x14567690, BRF_ESS | BRF_PRG },
{ "h-h1.rom", 0x020000, 0x264ba1f0, BRF_ESS | BRF_PRG },
{ "h-l1.rom", 0x020000, 0xf9913731, BRF_ESS | BRF_PRG },
{ "h-sh0.rom", 0x010000, 0x86a4e56e, BRF_ESS | BRF_PRG }, // CPU 1, V30
{ "h-sl0.rom", 0x010000, 0x10fd9676, BRF_ESS | BRF_PRG },
{ "hook-c0.rom", 0x040000, 0xdec63dcf, BRF_GRA }, // Tiles
{ "hook-c1.rom", 0x040000, 0xe4eb0b92, BRF_GRA },
{ "hook-c2.rom", 0x040000, 0xa52b320b, BRF_GRA },
{ "hook-c3.rom", 0x040000, 0x7ef67731, BRF_GRA },
{ "hook-000.rom", 0x100000, 0xccceac30, BRF_GRA }, // Sprites
{ "hook-010.rom", 0x100000, 0x8ac8da67, BRF_GRA },
{ "hook-020.rom", 0x100000, 0x8847af9a, BRF_GRA },
{ "hook-030.rom", 0x100000, 0x239e877e, BRF_GRA },
{ "hook-da.rom", 0x080000, 0x88cd0212, BRF_SND }, // Sound
};
STD_ROM_PICK(hook)
STD_ROM_FN(hook)
static struct BurnRomInfo hookuRomDesc[] = {
{ "h-h0-c.3h", 0x040000, 0x84cc239e, BRF_ESS | BRF_PRG }, // CPU 0, V33
{ "h-l0-c.5h", 0x040000, 0x45e194fe, BRF_ESS | BRF_PRG },
{ "h-h1.rom", 0x020000, 0x264ba1f0, BRF_ESS | BRF_PRG },
{ "h-l1.rom", 0x020000, 0xf9913731, BRF_ESS | BRF_PRG },
{ "h-sh0.rom", 0x010000, 0x86a4e56e, BRF_ESS | BRF_PRG }, // CPU 1, V30
{ "h-sl0.rom", 0x010000, 0x10fd9676, BRF_ESS | BRF_PRG },
{ "hook-c0.rom", 0x040000, 0xdec63dcf, BRF_GRA }, // Tiles
{ "hook-c1.rom", 0x040000, 0xe4eb0b92, BRF_GRA },
{ "hook-c2.rom", 0x040000, 0xa52b320b, BRF_GRA },
{ "hook-c3.rom", 0x040000, 0x7ef67731, BRF_GRA },
{ "hook-000.rom", 0x100000, 0xccceac30, BRF_GRA }, // Sprites
{ "hook-010.rom", 0x100000, 0x8ac8da67, BRF_GRA },
{ "hook-020.rom", 0x100000, 0x8847af9a, BRF_GRA },
{ "hook-030.rom", 0x100000, 0x239e877e, BRF_GRA },
{ "hook-da.rom", 0x080000, 0x88cd0212, BRF_SND }, // Sound
};
STD_ROM_PICK(hooku)
STD_ROM_FN(hooku)
static struct BurnRomInfo hookjRomDesc[] = {
{ "h-h0-g.3h", 0x040000, 0x5964c886, BRF_ESS | BRF_PRG }, // CPU 0, V33
{ "h-l0-g.5h", 0x040000, 0x7f7433f2, BRF_ESS | BRF_PRG },
{ "h-h1.rom", 0x020000, 0x264ba1f0, BRF_ESS | BRF_PRG },
{ "h-l1.rom", 0x020000, 0xf9913731, BRF_ESS | BRF_PRG },
{ "h-sh0-a.3l", 0x010000, 0xbd3d1f61, BRF_ESS | BRF_PRG }, // CPU 1, V30
{ "h-sl0-a.3n", 0x010000, 0x76371def, BRF_ESS | BRF_PRG },
{ "hook-c0.rom", 0x040000, 0xdec63dcf, BRF_GRA }, // Tiles
{ "hook-c1.rom", 0x040000, 0xe4eb0b92, BRF_GRA },
{ "hook-c2.rom", 0x040000, 0xa52b320b, BRF_GRA },
{ "hook-c3.rom", 0x040000, 0x7ef67731, BRF_GRA },
{ "hook-000.rom", 0x100000, 0xccceac30, BRF_GRA }, // Sprites
{ "hook-010.rom", 0x100000, 0x8ac8da67, BRF_GRA },
{ "hook-020.rom", 0x100000, 0x8847af9a, BRF_GRA },
{ "hook-030.rom", 0x100000, 0x239e877e, BRF_GRA },
{ "hook-da.rom", 0x080000, 0x88cd0212, BRF_SND }, // Sound
};
STD_ROM_PICK(hookj)
STD_ROM_FN(hookj)
static struct BurnRomInfo inthuntRomDesc[] = {
{ "ith-h0-d.bin", 0x040000, 0x52f8e7a6, BRF_ESS | BRF_PRG }, // CPU 0, V33
{ "ith-l0-d.bin", 0x040000, 0x5db79eb7, BRF_ESS | BRF_PRG },
{ "ith-h1-b.bin", 0x020000, 0xfc2899df, BRF_ESS | BRF_PRG },
{ "ith-l1-b.bin", 0x020000, 0x955a605a, BRF_ESS | BRF_PRG },
{ "ith-sh0.rom", 0x010000, 0x209c8b7f, BRF_ESS | BRF_PRG }, // CPU 1, V30
{ "ith-sl0.rom", 0x010000, 0x18472d65, BRF_ESS | BRF_PRG },
{ "ith_ic26.rom", 0x080000, 0x4c1818cf, BRF_GRA }, // Tiles
{ "ith_ic25.rom", 0x080000, 0x91145bae, BRF_GRA },
{ "ith_ic24.rom", 0x080000, 0xfc03fe3b, BRF_GRA },
{ "ith_ic23.rom", 0x080000, 0xee156a0a, BRF_GRA },
{ "ith_ic34.rom", 0x100000, 0xa019766e, BRF_GRA }, // Sprites
{ "ith_ic35.rom", 0x100000, 0x3fca3073, BRF_GRA },
{ "ith_ic36.rom", 0x100000, 0x20d1b28b, BRF_GRA },
{ "ith_ic37.rom", 0x100000, 0x90b6fd4b, BRF_GRA },
{ "ith_ic9.rom", 0x080000, 0x318ee71a, BRF_SND }, // Sound
};
STD_ROM_PICK(inthunt)
STD_ROM_FN(inthunt)
static struct BurnRomInfo inthuntuRomDesc[] = {
{ "ith-h0-c.bin", 0x040000, 0x563dcec0, BRF_ESS | BRF_PRG }, // CPU 0, V33
{ "ith-l0-c.bin", 0x040000, 0x1638c705, BRF_ESS | BRF_PRG },
{ "ith-h1-a.bin", 0x020000, 0x0253065f, BRF_ESS | BRF_PRG },
{ "ith-l1-a.bin", 0x020000, 0xa57d688d, BRF_ESS | BRF_PRG },
{ "ith-sh0.rom", 0x010000, 0x209c8b7f, BRF_ESS | BRF_PRG }, // CPU 1, V30
{ "ith-sl0.rom", 0x010000, 0x18472d65, BRF_ESS | BRF_PRG },
{ "ith_ic26.rom", 0x080000, 0x4c1818cf, BRF_GRA }, // Tiles
{ "ith_ic25.rom", 0x080000, 0x91145bae, BRF_GRA },
{ "ith_ic24.rom", 0x080000, 0xfc03fe3b, BRF_GRA },
{ "ith_ic23.rom", 0x080000, 0xee156a0a, BRF_GRA },
{ "ith_ic34.rom", 0x100000, 0xa019766e, BRF_GRA }, // Sprites
{ "ith_ic35.rom", 0x100000, 0x3fca3073, BRF_GRA },
{ "ith_ic36.rom", 0x100000, 0x20d1b28b, BRF_GRA },
{ "ith_ic37.rom", 0x100000, 0x90b6fd4b, BRF_GRA },
{ "ith_ic9.rom", 0x080000, 0x318ee71a, BRF_SND }, // Sound
};
STD_ROM_PICK(inthuntu)
STD_ROM_FN(inthuntu)
static struct BurnRomInfo kaiteidsRomDesc[] = {
{ "ith-h0j.bin", 0x040000, 0xdc1dec36, BRF_ESS | BRF_PRG }, // CPU 0, V33
{ "ith-l0j.bin", 0x040000, 0x8835d704, BRF_ESS | BRF_PRG },
{ "ith-h1j.bin", 0x020000, 0x5a7b212d, BRF_ESS | BRF_PRG },
{ "ith-l1j.bin", 0x020000, 0x4c084494, BRF_ESS | BRF_PRG },
{ "ith-sh0.rom", 0x010000, 0x209c8b7f, BRF_ESS | BRF_PRG }, // CPU 1, V30
{ "ith-sl0.rom", 0x010000, 0x18472d65, BRF_ESS | BRF_PRG },
{ "ith_ic26.rom", 0x080000, 0x4c1818cf, BRF_GRA }, // Tiles
{ "ith_ic25.rom", 0x080000, 0x91145bae, BRF_GRA },
{ "ith_ic24.rom", 0x080000, 0xfc03fe3b, BRF_GRA },
{ "ith_ic23.rom", 0x080000, 0xee156a0a, BRF_GRA },
{ "ith_ic34.rom", 0x100000, 0xa019766e, BRF_GRA }, // Sprites
{ "ith_ic35.rom", 0x100000, 0x3fca3073, BRF_GRA },
{ "ith_ic36.rom", 0x100000, 0x20d1b28b, BRF_GRA },
{ "ith_ic37.rom", 0x100000, 0x90b6fd4b, BRF_GRA },
{ "ith_ic9.rom", 0x080000, 0x318ee71a, BRF_SND }, // Sound
};
STD_ROM_PICK(kaiteids)
STD_ROM_FN(kaiteids)
static struct BurnRomInfo rtypeleoRomDesc[] = {
{ "rtl-h0-c.bin", 0x040000, 0x5fef7fa1, BRF_ESS | BRF_PRG }, // CPU 0, V33
{ "rtl-l0-c.bin", 0x040000, 0x8156456b, BRF_ESS | BRF_PRG },
{ "rtl-h1-d.bin", 0x020000, 0x352ff444, BRF_ESS | BRF_PRG },
{ "rtl-l1-d.bin", 0x020000, 0xfd34ea46, BRF_ESS | BRF_PRG },
{ "rtl-sh0a.bin", 0x010000, 0xe518b4e3, BRF_ESS | BRF_PRG }, // CPU 1, V30
{ "rtl-sl0a.bin", 0x010000, 0x896f0d36, BRF_ESS | BRF_PRG },
{ "rtl-c0.bin", 0x080000, 0xfb588d7c, BRF_GRA }, // Tiles
{ "rtl-c1.bin", 0x080000, 0xe5541bff, BRF_GRA },
{ "rtl-c2.bin", 0x080000, 0xfaa9ae27, BRF_GRA },
{ "rtl-c3.bin", 0x080000, 0x3a2343f6, BRF_GRA },
{ "rtl-000.bin", 0x100000, 0x82a06870, BRF_GRA }, // Sprites
{ "rtl-010.bin", 0x100000, 0x417e7a56, BRF_GRA },
{ "rtl-020.bin", 0x100000, 0xf9a3f3a1, BRF_GRA },
{ "rtl-030.bin", 0x100000, 0x03528d95, BRF_GRA },
{ "rtl-da.bin", 0x080000, 0xdbebd1ff, BRF_SND }, // Sound
};
STD_ROM_PICK(rtypeleo)
STD_ROM_FN(rtypeleo)
static struct BurnRomInfo rtypelejRomDesc[] = {
{ "rtl-h0-d.bin", 0x040000, 0x3dbac89f, BRF_ESS | BRF_PRG }, // CPU 0, V33
{ "rtl-l0-d.bin", 0x040000, 0xf85a2537, BRF_ESS | BRF_PRG },
{ "rtl-h1-d.bin", 0x020000, 0x352ff444, BRF_ESS | BRF_PRG },
{ "rtl-l1-d.bin", 0x020000, 0xfd34ea46, BRF_ESS | BRF_PRG },
{ "rtl-sh0a.bin", 0x010000, 0xe518b4e3, BRF_ESS | BRF_PRG }, // CPU 1, V30
{ "rtl-sl0a.bin", 0x010000, 0x896f0d36, BRF_ESS | BRF_PRG },
{ "rtl-c0.bin", 0x080000, 0xfb588d7c, BRF_GRA }, // Tiles
{ "rtl-c1.bin", 0x080000, 0xe5541bff, BRF_GRA },
{ "rtl-c2.bin", 0x080000, 0xfaa9ae27, BRF_GRA },
{ "rtl-c3.bin", 0x080000, 0x3a2343f6, BRF_GRA },
{ "rtl-000.bin", 0x100000, 0x82a06870, BRF_GRA }, // Sprites
{ "rtl-010.bin", 0x100000, 0x417e7a56, BRF_GRA },
{ "rtl-020.bin", 0x100000, 0xf9a3f3a1, BRF_GRA },
{ "rtl-030.bin", 0x100000, 0x03528d95, BRF_GRA },
{ "rtl-da.bin", 0x080000, 0xdbebd1ff, BRF_SND }, // Sound
};
STD_ROM_PICK(rtypelej)
STD_ROM_FN(rtypelej)
// Irem GA20 Sound chip
#define MAX_VOL 256
static struct IremGA20_chip
{
//const struct IremGA20_interface *intf;
//unsigned char *rom;
//int rom_size;
//sound_stream * stream;
unsigned char regs[0x40];
struct IremGA20_channel {
unsigned int rate;
unsigned int size;
unsigned int start;
unsigned int pos;
unsigned int frac;
unsigned int end;
unsigned int volume;
unsigned int pan;
unsigned int effect;
unsigned int play;
} channel[4];
} * chip = 0;
unsigned char IremGA20_r(int offset)
{
int chl = offset >> 4;
switch (offset & 0xf) {
case 0xe: // voice status. bit 0 is 1 if active. (routine around 0xccc in rtypeleo)
return chip->channel[chl].play ? 1 : 0;
break;
default:
//logerror("GA20: read unk. register %d, channel %d\n", offset & 0xf, channel);
break;
}
return 0;
}
void IremGA20_w(int offset, unsigned char data)
{
chip->regs[offset] = data;
int chl = offset >> 4;
switch ( offset & 0xf ) {
case 0x0:
chip->channel[chl].start = ((chip->channel[chl].start)&0xff000) | (data<< 4);
break;
case 0x2:
chip->channel[chl].start = ((chip->channel[chl].start)&0x00ff0) | (data<<12);
break;
case 0x4:
chip->channel[chl].end = ((chip->channel[chl].end)&0xff000) | (data<< 4);
break;
case 0x6:
chip->channel[chl].end = ((chip->channel[chl].end)&0x00ff0) | (data<<12);
break;
case 0x8:
chip->channel[chl].rate = 0x1000000 / (256 - data);
break;
case 0xa:
chip->channel[chl].volume = (data * MAX_VOL) / (data + 10);
break;
case 0xc:
chip->channel[chl].play = data;
chip->channel[chl].pos = chip->channel[chl].start;
chip->channel[chl].frac = 0;
break;
}
}
int IremGA20_update(short * /*pBuffer*/, int /*len*/)
{
#if 0
bprintf(PRINT_NORMAL, _T("GA20 %d%d%d%d\n"),
chip->channel[0].play,
chip->channel[1].play,
chip->channel[2].play,
chip->channel[3].play );
#endif
return 0;
}
static void snd_update_irq()
{
if (irqvector & 0x2) /* YM2151 has precedence */
VezSetIRQLine(0x18 * 4, VEZ_IRQSTATUS_ACK);
else if (irqvector & 0x1) /* V30 */
VezSetIRQLine(0x19 * 4, VEZ_IRQSTATUS_ACK);
}
static void m92YM2151IRQHandler(int nStatus)
{
// bprintf(PRINT_NORMAL, _T("m92YM2151IRQHandler nStatus %x\n"), nStatus);
if (nStatus)irqvector |= 2;
else irqvector &= ~2;
snd_update_irq();
}
unsigned char __fastcall m92ReadByte(unsigned int vezAddress)
{
// Palette Read
if ((vezAddress & 0xFF800) == 0xF8800 )
return RamPal[ vezAddress - 0xF8800 + PalBank ];
// V33 Start vector
if ((vezAddress & 0xFFFF0) == 0xFFFF0 )
return RomV33[ vezAddress - 0xFFFF0 + 0x7FFF0 ];
// switch (vezAddress) {
// default:
// bprintf(PRINT_NORMAL, _T("Attempt to read byte value of location %x\n"), vezAddress);
// }
return 0;
}
void __fastcall m92WriteByte(unsigned int vezAddress, unsigned char byteValue)
{
static unsigned int sprite_extent;
if ((vezAddress & 0xFF800) == 0xF8800 ) {
RamPal[ vezAddress - 0xF8800 + PalBank ] = byteValue;
if (vezAddress & 1) {
int offs = (vezAddress - 0xF8800 + PalBank) >> 1;
RamCurPal[ offs ] = CalcCol( offs << 1 );
}
return;
}
switch (vezAddress) {
// 0xf9000 ~ 0xf900f : m92_spritecontrol_w
case 0xF9000:
sprite_extent = byteValue;
break;
case 0xF9004:
if (byteValue==8)
m92_sprite_list=(((0x100 - sprite_extent)&0xff)*8);
else
m92_sprite_list=0x800;
break;
case 0xF9008:
/* Pixel clock is 26.6666 MHz, we have 0x800 bytes, or 0x400 words
to copy from spriteram to the buffer. It seems safe to assume 1
word can be copied per clock. So:
1 MHz clock would be 1 word every 0.000,001s = 1000ns
26.6666MHz clock would be 1 word every 0.000,000,037 = 37 ns
Buffer should copy in about 37888 ns. */
m92_sprite_buffer_busy = 0;
m92_sprite_buffer_timer = VezCurrentCPU->reg.nec_ICount - 341; // 9000000 * 0x400 * 0.000000037;
VezCurrentCPU->reg.nec_ICount = 341;
//bprintf(PRINT_NORMAL, _T("sprite buffer copy timer start %f\n"), 100.0 * VezSegmentCycles() / (9000000 / 60) );
//memcpy(RamSprCpy, RamSpr, 0x800);
break;
case 0xF9800:
PalBank = (byteValue & 0x2 /* && m92_game_kludge!=3 */) ? 0x0800 : 0x0000;
break;
case 0xF9001:
case 0xF9002:
case 0xF9003:
case 0xF9005:
case 0xF9006:
case 0xF9007:
case 0xF9009:
case 0xF900a:
case 0xF900b:
case 0xF9801:
//if (!byteValue)
break;
// default:
//if (vezAddress >= 0xA0000)
// bprintf(PRINT_NORMAL, _T("Attempt to write byte value %x to location %x\n"), byteValue, vezAddress);
}
}
unsigned char __fastcall m92ReadPort(unsigned int vezPort)
{
switch (vezPort) {
case 0x00: return ~DrvInput[0]; // player 1
case 0x01: return ~DrvInput[1]; // player 2
case 0x03: return ~DrvInput[7]; // dip 3
case 0x04: return ~DrvInput[6]; // dip 2
case 0x05: return ~DrvInput[5]; // dip 1
case 0x06: return ~DrvInput[2]; // player 3
case 0x07: return ~DrvInput[3]; // player 4
case 0x08: return sound_status[0];
case 0x09: return sound_status[1];
case 0x88: return 0xFF;
case 0x02: return (~DrvInput[4] & 0x7F) | m92_sprite_buffer_busy;
// default:
// bprintf(PRINT_NORMAL, _T("Attempt to read byte value of port %x\n"), vezPort);
}
return 0;
}
void __fastcall m92WritePort(unsigned int vezPort, unsigned char byteValue)
{
switch (vezPort) {
case 0x00:
sound_latch[0] = byteValue;
irqvector |= 1;
snd_update_irq();
break;
case 0x01:
sound_latch[1] = byteValue;
break;
case 0x02:
case 0x03:
//m92_coincounter_w
break;
case 0x20:
// m92_bankswitch_w
// bprintf(PRINT_NORMAL, _T("CPU 0 bank change to %02x\n"), byteValue);
VezMapArea(0xa0000, 0xbffff, 0, RomV33 + 0x100000 + (byteValue&0x7)*0x10000);
VezMapArea(0xa0000, 0xbffff, 2, RomV33 + 0x100000 + (byteValue&0x7)*0x10000);
break;
case 0x21:
// m92_bankswitch_w
break;
case 0x40:
case 0x41:
case 0x42:
case 0x43:
// Interrupt controller, only written to at bootup
break;
// 0x80 ~ 0x87: m92_pf1_control_w
case 0x80: pf1_control[0] = byteValue; break;
case 0x81: pf1_control[1] = byteValue; break;
case 0x82: pf1_control[2] = byteValue; break;
case 0x83: pf1_control[3] = byteValue; break;
case 0x84: pf1_control[4] = byteValue; break;
case 0x85: pf1_control[5] = byteValue; break;
case 0x86: pf1_control[6] = byteValue; break;
case 0x87: pf1_control[7] = byteValue; break;
// 0x88 ~ 0x8f: m92_pf2_control_w
case 0x88: pf2_control[0] = byteValue; break;
case 0x89: pf2_control[1] = byteValue; break;
case 0x8a: pf2_control[2] = byteValue; break;
case 0x8b: pf2_control[3] = byteValue; break;
case 0x8c: pf2_control[4] = byteValue; break;
case 0x8d: pf2_control[5] = byteValue; break;
case 0x8e: pf2_control[6] = byteValue; break;
case 0x8f: pf2_control[7] = byteValue; break;
// 0x90 ~ 0x97: m92_pf3_control_w
case 0x90: pf3_control[0] = byteValue; break;
case 0x91: pf3_control[1] = byteValue; break;
case 0x92: pf3_control[2] = byteValue; break;
case 0x93: pf3_control[3] = byteValue; break;
case 0x94: pf3_control[4] = byteValue; break;
case 0x95: pf3_control[5] = byteValue; break;
case 0x96: pf3_control[6] = byteValue; break;
case 0x97: pf3_control[7] = byteValue; break;
// 0x98 ~ 0x9f: m92_master_control_w
case 0x98:
pf4_control[0] = byteValue;
pf1_enable = (byteValue & 0x10) ? 0 : 1;
pf1_rowscroll = (byteValue & 0x40) >> 6;
pf1_shape = (byteValue & 0x04) >> 2;
pf1_vram_ptr = 0x4000 * (byteValue & 0x03);
break;
case 0x99: pf4_control[1] = byteValue; break;
case 0x9a:
pf4_control[2] = byteValue;
pf2_enable = (byteValue & 0x10) ? 0 : 1;
pf2_rowscroll = (byteValue & 0x40) >> 6;
pf2_shape = (byteValue & 0x04) >> 2;
pf2_vram_ptr = 0x4000 * (byteValue & 0x03);
break;
case 0x9b: pf4_control[3] = byteValue; break;
case 0x9c:
pf4_control[4] = byteValue;
pf3_enable = (byteValue & 0x10) ? 0 : 1;
pf3_rowscroll = (byteValue & 0x40) >> 6;
pf3_shape = (byteValue & 0x04) >> 2;
pf3_vram_ptr = 0x4000 * (byteValue & 0x03);
break;
case 0x9d: pf4_control[5] = byteValue; break;
case 0x9e:
pf4_control[6] = byteValue;
m92_raster_irq_position = ((pf4_control[7]<<8) | pf4_control[6]) - 128;
break;
case 0x9f:
pf4_control[7] = byteValue;
m92_raster_irq_position = ((pf4_control[7]<<8) | pf4_control[6]) - 128;
//bprintf(PRINT_NORMAL, _T("m92_raster_irq_position set to %d\n"), m92_raster_irq_position);
break;
// default:
// bprintf(PRINT_NORMAL, _T("Attempt to write byte value %x to port %x\n"), byteValue, vezPort);
}
}
unsigned char __fastcall m92SndReadByte(unsigned int vezAddress)
{
if (vezAddress >= 0xa8000 && vezAddress <= 0xa803f )
return IremGA20_r( vezAddress - 0xa8000 );
switch (vezAddress) {
case 0xa8042:
return BurnYM2151ReadStatus();
//case 0xa8043:
// YM2151_status_port_0_r
// break;
case 0xa8044:
return sound_latch[0];
case 0xa8045:
return sound_latch[1];
// default:
// bprintf(PRINT_NORMAL, _T("V30 Attempt to read byte value of location %x\n"), vezAddress);
}
return 0;
}
void __fastcall m92SndWriteByte(unsigned int vezAddress, unsigned char byteValue)
{
if (vezAddress >= 0xa8000 && vezAddress <= 0xa803f ) {
IremGA20_w( vezAddress - 0xa8000, byteValue );
return;
}
if (vezAddress >= 0x9ff00 && vezAddress <= 0x9ffff ) {
// NOP
return;
}
switch (vezAddress) {
case 0xa8040:
BurnYM2151SelectRegister(byteValue);
break;
//case 0xa8041:
// YM2151_register_port_0_w
// break;
case 0xa8042:
BurnYM2151WriteRegister(byteValue);
break;
//case 0xa8043:
// YM2151_data_port_0_w
// break;
case 0xa8044:
irqvector &= ~1;
snd_update_irq();
break;
//case 0xa8045:
// m92_sound_irq_ack_w
// break;
case 0xa8046:
// m92_sound_status_w
sound_status[0] = byteValue;
// VezOpen(0);
// VezSetIRQLine(m92_irq_vectorbase + 12, VEZ_IRQSTATUS_ACK); // IRQ 3
// VezRun(400);
// VezOpen(1);
//bprintf(PRINT_NORMAL, _T("m92_sound_status_w %x, and set M92_IRQ_3\n"), byteValue);
break;
case 0xa8047:
sound_status[1] = byteValue;
break;
// default:
// bprintf(PRINT_NORMAL, _T("V30 Attempt to write byte value %x to location %x\n"), byteValue, vezAddress);
}
}
static int DrvDoReset()
{
VezOpen(0);
VezReset();
VezOpen(1);
VezReset();
BurnYM2151Reset();
memset(pf1_control, 0, sizeof(pf1_control));
memset(pf2_control, 0, sizeof(pf2_control));
memset(pf3_control, 0, sizeof(pf3_control));
memset(pf4_control, 0, sizeof(pf4_control));
pf1_enable = pf2_enable = pf3_enable = 0;
pf1_shape = pf2_shape = pf3_shape = 0;
pf1_rowscroll = pf2_rowscroll = pf3_rowscroll = 0;
pf1_vram_ptr = pf2_vram_ptr = pf3_vram_ptr = 0;
m92_sprite_buffer_busy = 0x80;
m92_sprite_buffer_timer = 0;
irqvector = 0;
return 0;
}
static int loadDecodeGfx01(unsigned char *tmp, int rid, int shift, int size)
{
unsigned char * pgfx = RomGfx01;
BurnLoadRom(tmp, rid, 1);
for (int i=0; i<(size/8); i++) {
for( int y=0;y<8;y++) {
pgfx[0] |= ((tmp[0]>>7)&1)<<shift;
pgfx[1] |= ((tmp[0]>>6)&1)<<shift;
pgfx[2] |= ((tmp[0]>>5)&1)<<shift;
pgfx[3] |= ((tmp[0]>>4)&1)<<shift;
pgfx[4] |= ((tmp[0]>>3)&1)<<shift;
pgfx[5] |= ((tmp[0]>>2)&1)<<shift;
pgfx[6] |= ((tmp[0]>>1)&1)<<shift;
pgfx[7] |= ((tmp[0]>>0)&1)<<shift;
tmp ++;
pgfx += 8;
}
}
return 0;
}
static int loadDecodeGfx02(unsigned char *tmp, int rid, int shift, int size)
{
unsigned char * pgfx = RomGfx02;
BurnLoadRom(tmp, rid, 1);
for (int i=0; i<(size/32); i++) {
for( int y=0;y<16;y++) {
pgfx[ 0] |= ((tmp[ 0]>>7)&1)<<shift;
pgfx[ 1] |= ((tmp[ 0]>>6)&1)<<shift;
pgfx[ 2] |= ((tmp[ 0]>>5)&1)<<shift;
pgfx[ 3] |= ((tmp[ 0]>>4)&1)<<shift;
pgfx[ 4] |= ((tmp[ 0]>>3)&1)<<shift;
pgfx[ 5] |= ((tmp[ 0]>>2)&1)<<shift;
pgfx[ 6] |= ((tmp[ 0]>>1)&1)<<shift;
pgfx[ 7] |= ((tmp[ 0]>>0)&1)<<shift;
pgfx[ 8] |= ((tmp[16]>>7)&1)<<shift;
pgfx[ 9] |= ((tmp[16]>>6)&1)<<shift;
pgfx[10] |= ((tmp[16]>>5)&1)<<shift;
pgfx[11] |= ((tmp[16]>>4)&1)<<shift;
pgfx[12] |= ((tmp[16]>>3)&1)<<shift;
pgfx[13] |= ((tmp[16]>>2)&1)<<shift;
pgfx[14] |= ((tmp[16]>>1)&1)<<shift;
pgfx[15] |= ((tmp[16]>>0)&1)<<shift;
tmp ++;
pgfx += 16;
}
tmp += 16;
}
return 0;
}
static int MemIndex()
{
unsigned char *Next; Next = Mem;
RomV33 = Next; Next += 0x0C0000; // V33
RomV30 = Next; Next += 0x020000 * 2; // V30
RomGfx01 = Next; Next += 0x200000; // char
RomGfx02 = Next; Next += 0x800000; // spr
//MSM6295ROM = Next; Next += 0x080000;
RamStart = Next;
RamVideo = Next; Next += 0x010000;
RamV33 = Next; Next += 0x010000;
RamV30 = Next; Next += 0x004000;
RamSpr = Next; Next += 0x000800;
RamSprCpy = Next; Next += 0x000800;
RamPal = Next; Next += 0x001000; // 2 bank of 0x0800
chip = (struct IremGA20_chip *) Next;
Next += sizeof( struct IremGA20_chip );
RamEnd = Next;
RamCurPal = (unsigned short *) Next; Next += 0x001000;
MemEnd = Next;
return 0;
}
static int hookInit()
{
int nRet;
Mem = NULL;
MemIndex();
int nLen = MemEnd - (unsigned char *)0;
if ((Mem = (unsigned char *)malloc(nLen)) == NULL) return 1;
memset(Mem, 0, nLen); // blank all memory
MemIndex();
nRet = BurnLoadRom(RomV33 + 0x000001, 0, 2); if (nRet != 0) return 1;
nRet = BurnLoadRom(RomV33 + 0x000000, 1, 2); if (nRet != 0) return 1;
nRet = BurnLoadRom(RomV33 + 0x080001, 2, 2); if (nRet != 0) return 1;
nRet = BurnLoadRom(RomV33 + 0x080000, 3, 2); if (nRet != 0) return 1;
unsigned char *tmp = (unsigned char *) malloc (0x100000);
if ( tmp == 0 )
{
return 1;
}
nRet = BurnLoadRom(tmp + 0x000001, 4, 2); if (nRet != 0) return 1;
nRet = BurnLoadRom(tmp + 0x000000, 5, 2); if (nRet != 0) return 1;
//irem_cpu_decrypt(RomV30, 0x20000, hook_decryption_table );
irem_cpu_decrypt(0,hook_decryption_table,tmp,RomV30,0x20000 );
free(tmp);
// load and decode tile
tmp = (unsigned char *) malloc (0x100000);
if ( tmp == 0 )
{
return 1;
}
loadDecodeGfx01(tmp, 6, 0, 0x040000);
loadDecodeGfx01(tmp, 7, 1, 0x040000);
loadDecodeGfx01(tmp, 8, 2, 0x040000);
loadDecodeGfx01(tmp, 9, 3, 0x040000);
loadDecodeGfx02(tmp, 10, 0, 0x100000);
loadDecodeGfx02(tmp, 11, 1, 0x100000);
loadDecodeGfx02(tmp, 12, 2, 0x100000);
loadDecodeGfx02(tmp, 13, 3, 0x100000);
free(tmp);
{
unsigned int cpu_types[] = { 0, 8 };
VezInit(2, &cpu_types[0]);
VezOpen(0);
VezMapArea(0x00000, 0x9ffff, 0, RomV33 + 0x00000); // CPU 0 ROM
VezMapArea(0x00000, 0x9ffff, 2, RomV33 + 0x00000); // CPU 0 ROM
VezMapArea(0xa0000, 0xbffff, 0, RomV33 + 0xa0000); // rom bank
VezMapArea(0xa0000, 0xbffff, 2, RomV33 + 0xa0000); // rom bank
VezMapArea(0xd0000, 0xdffff, 0, RamVideo);
VezMapArea(0xd0000, 0xdffff, 1, RamVideo);
VezMapArea(0xe0000, 0xeffff, 0, RamV33); // system ram
VezMapArea(0xe0000, 0xeffff, 1, RamV33);
VezMapArea(0xf8000, 0xf87ff, 0, RamSpr); // sprites ram
VezMapArea(0xf8000, 0xf87ff, 1, RamSpr);
VezSetReadHandler(m92ReadByte);
VezSetWriteHandler(m92WriteByte);
VezSetReadPort(m92ReadPort);
VezSetWritePort(m92WritePort);
VezOpen(1);
VezMapArea(0x00000, 0x1ffff, 0, RomV30 + 0x00000); // CPU 1 ROM
VezMapArea(0x00000, 0x1ffff, 2, RomV30 + 0x20000, RomV30 + 0x00000);
VezMapArea(0xa0000, 0xa3fff, 0, RamV30); // system ram
VezMapArea(0xa0000, 0xa3fff, 1, RamV30);
// V30 Startup vector
VezMapArea(0xff800, 0xfffff, 0, RomV30 + 0x1f800);
VezMapArea(0xff800, 0xfffff, 2, RomV30 + 0x3f800, RomV30 + 0x1f800);
VezSetReadHandler(m92SndReadByte);
VezSetWriteHandler(m92SndWriteByte);
}
m92_irq_vectorbase = 0x80;
PalBank = 0;
BurnYM2151Init(3579545, 80.0); // 3.5795 MHz
YM2151SetIrqHandler(0, &m92YM2151IRQHandler);
DrvDoReset();
return 0;
}
static int hookExit()
{
BurnYM2151Exit();
VezExit();
free(Mem);
Mem = NULL;
return 0;
}
#define TILE_LAYER_1(xx) \
if (d[xx]) p[xx] = pal[ d[xx] | c ];
#define TILE_LAYER_1_E(xx) \
if (d[xx] && (x + xx)>=0 && (x + xx)<320 ) p[xx] = pal[ d[xx] | c ];
#define TILE_LAYER_1_LINE \
TILE_LAYER_1(0) \
TILE_LAYER_1(1) \
TILE_LAYER_1(2) \
TILE_LAYER_1(3) \
TILE_LAYER_1(4) \
TILE_LAYER_1(5) \
TILE_LAYER_1(6) \
TILE_LAYER_1(7)
#define TILE_LAYER_1_LINE_E \
if ( (y+k)>=0 && (y+k)<240 ) { \
TILE_LAYER_1_E(0) \
TILE_LAYER_1_E(1) \
TILE_LAYER_1_E(2) \
TILE_LAYER_1_E(3) \
TILE_LAYER_1_E(4) \
TILE_LAYER_1_E(5) \
TILE_LAYER_1_E(6) \
TILE_LAYER_1_E(7) \
}
static void tileLayer_1()
{
/* T--- -YX- Pccc cccc tttt tttt tttt tttt */
unsigned short * pal = RamCurPal;
int offs, mx, my, x, y;
mx = -1;
my = 0;
for (offs = 0; offs < 64*64*4; offs+=4) {
mx++;
if (mx == 64) {
mx = 0;
my++;
}
x = mx * 8 - ((80 + (short)((pf1_control[5]<<8) | pf1_control[4])) & 0x1ff);
if (x < -16) x += 512;
y = my * 8 - ((136 + (short)((pf1_control[1]<<8) | pf1_control[0])) & 0x1ff);
if (y < -16) y += 512;
if ( x<=-8 || x>=320 || y<=-8 || y>= 240 )
continue;
int tile_index = offs + pf1_vram_ptr;
unsigned int tileno = RamVideo[tile_index] | (RamVideo[tile_index+1] << 8) | ((RamVideo[tile_index+3] & 0x80) << 9);
if (tileno == 0) continue;
unsigned int c = (RamVideo[tile_index+2] & 0x7F) << 4;
unsigned short * p = (unsigned short *) pBurnDraw + y * 320 + x;
unsigned char * d = RomGfx01 + (tileno * 64);
if ( x >=0 && x <= (320-8) && y >= 0 && y <= (240-8)) {
//unsigned char * pp = RamPri + y * 320 + x;
for (int k=0;k<8;k++) {
TILE_LAYER_1_LINE
d += 8;
p += 320;
}
} else {
for (int k=0;k<8;k++) {
TILE_LAYER_1_LINE_E
d += 8;
p += 320;
}
}
}
}
static void tileLayer_2()
{
/* T--- -YX- Pccc cccc tttt tttt tttt tttt */
unsigned short * pal = RamCurPal;
int offs, mx, my, x, y;
mx = -1;
my = 0;
for (offs = 0; offs < 64*64*4; offs+=4) {
mx++;
if (mx == 64) {
mx = 0;
my++;
}
x = mx * 8 - ((80 - 2 + (short)((pf2_control[5]<<8) | pf2_control[4])) & 0x1ff);
if (x < -16) x += 512;
y = my * 8 - ((136 + (short)((pf2_control[1]<<8) | pf2_control[0])) & 0x1ff);
if (y < -16) y += 512;
if ( x<=-8 || x>=320 || y<=-8 || y>= 240 )
continue;
int tile_index = offs + pf2_vram_ptr;
unsigned int tileno = RamVideo[tile_index] | (RamVideo[tile_index+1] << 8) | ((RamVideo[tile_index+3] & 0x80) << 9);
if (tileno == 0) continue;
//if ((RamVideo[tile_index+2] & 0x80) ^ pri) continue;
unsigned int c = (RamVideo[tile_index+2] & 0x7F) << 4;
unsigned short * p = (unsigned short *) pBurnDraw + y * 320 + x;
unsigned char * d = RomGfx01 + (tileno * 64);
//unsigned char * pp = RamPri + y * 320 + x;
if ( x >=0 && x <= (320-8) && y >= 0 && y <= (240-8)) {
for (int k=0;k<8;k++) {
TILE_LAYER_1_LINE
d += 8;
p += 320;
}
} else {
for (int k=0;k<8;k++) {
TILE_LAYER_1_LINE_E
d += 8;
p += 320;
}
}
}
}
#define TILE_LAYER_3(xx) \
p[xx] = pal[ d[xx] | c ];
#define TILE_LAYER_3_E(xx) \
if ((x + xx)>=0 && (x + xx)<320 ) p[xx] = pal[ d[xx] | c ];
#define TILE_LAYER_3_LINE \
TILE_LAYER_3(0) \
TILE_LAYER_3(1) \
TILE_LAYER_3(2) \
TILE_LAYER_3(3) \
TILE_LAYER_3(4) \
TILE_LAYER_3(5) \
TILE_LAYER_3(6) \
TILE_LAYER_3(7)
#define TILE_LAYER_3_LINE_E \
if ( (y+k)>=0 && (y+k)<240 ) { \
TILE_LAYER_3_E(0) \
TILE_LAYER_3_E(1) \
TILE_LAYER_3_E(2) \
TILE_LAYER_3_E(3) \
TILE_LAYER_3_E(4) \
TILE_LAYER_3_E(5) \
TILE_LAYER_3_E(6) \
TILE_LAYER_3_E(7) \
}
static void tileLayer_3()
{
/* T--- -YX- Pccc cccc tttt tttt tttt tttt */
unsigned short * pal = RamCurPal;
int offs, mx, my, x, y;
mx = -1;
my = 0;
for (offs = 0; offs < 64*64*4; offs+=4) {
mx++;
if (mx == 64) {
mx = 0;
my++;
}
x = mx * 8 - ((80 - 4 + (short)((pf3_control[5]<<8) | pf3_control[4])) & 0x1ff);
if (x < -16) x += 512;
y = my * 8 - ((136 + (short)((pf3_control[1]<<8) | pf3_control[0])) & 0x1ff);
if (y < -16) y += 512;
if ( x<=-8 || x>=320 || y<=-8 || y>= 240 )
continue;
int tile_index = offs + pf3_vram_ptr;
unsigned int tileno = RamVideo[tile_index] | (RamVideo[tile_index+1] << 8) | ((RamVideo[tile_index+3] & 0x80) << 9);
//if (tileno == 0) continue;
unsigned int c = (RamVideo[tile_index+2] & 0x7F) << 4;
unsigned short * p = (unsigned short *) pBurnDraw + y * 320 + x;
unsigned char * d = RomGfx01 + (tileno * 64);
//unsigned char * pp = RamPri + y * 320 + x;
if ( x >=0 && x <= (320-8) && y >= 0 && y <= (240-8)) {
for (int k=0;k<8;k++) {
TILE_LAYER_3_LINE
d += 8;
p += 320;
}
} else {
for (int k=0;k<8;k++) {
TILE_LAYER_3_LINE_E
d += 8;
p += 320;
}
}
}
}
#define TILE_SPR_NORMAL(x) \
if (q[x]) p[x]=pal[q[x]|color];
#define TILE_SPR_FLIP_X(x) \
if (q[x]) p[15-x]=pal[q[x]|color];
#define TILE_SPR_NORMAL_E(x) \
if (q[x]&&((sx+x)>=0)&&((sx+x)<320)) p[x]=pal[q[x]|color];
#define TILE_SPR_FLIP_X_E(x) \
if (q[x]&&((sx+15-x)>=0)&&((sx+15-x)<320)) p[15-x]=pal[q[x]|color];
#define TILE_SPR_NORMAL_LINE \
TILE_SPR_NORMAL( 0) \
TILE_SPR_NORMAL( 1) \
TILE_SPR_NORMAL( 2) \
TILE_SPR_NORMAL( 3) \
TILE_SPR_NORMAL( 4) \
TILE_SPR_NORMAL( 5) \
TILE_SPR_NORMAL( 6) \
TILE_SPR_NORMAL( 7) \
TILE_SPR_NORMAL( 8) \
TILE_SPR_NORMAL( 9) \
TILE_SPR_NORMAL(10) \
TILE_SPR_NORMAL(11) \
TILE_SPR_NORMAL(12) \
TILE_SPR_NORMAL(13) \
TILE_SPR_NORMAL(14) \
TILE_SPR_NORMAL(15)
#define TILE_SPR_FLIP_X_LINE \
TILE_SPR_FLIP_X( 0) \
TILE_SPR_FLIP_X( 1) \
TILE_SPR_FLIP_X( 2) \
TILE_SPR_FLIP_X( 3) \
TILE_SPR_FLIP_X( 4) \
TILE_SPR_FLIP_X( 5) \
TILE_SPR_FLIP_X( 6) \
TILE_SPR_FLIP_X( 7) \
TILE_SPR_FLIP_X( 8) \
TILE_SPR_FLIP_X( 9) \
TILE_SPR_FLIP_X(10) \
TILE_SPR_FLIP_X(11) \
TILE_SPR_FLIP_X(12) \
TILE_SPR_FLIP_X(13) \
TILE_SPR_FLIP_X(14) \
TILE_SPR_FLIP_X(15)
#define TILE_SPR_NORMAL_LINE_E \
TILE_SPR_NORMAL_E( 0) \
TILE_SPR_NORMAL_E( 1) \
TILE_SPR_NORMAL_E( 2) \
TILE_SPR_NORMAL_E( 3) \
TILE_SPR_NORMAL_E( 4) \
TILE_SPR_NORMAL_E( 5) \
TILE_SPR_NORMAL_E( 6) \
TILE_SPR_NORMAL_E( 7) \
TILE_SPR_NORMAL_E( 8) \
TILE_SPR_NORMAL_E( 9) \
TILE_SPR_NORMAL_E(10) \
TILE_SPR_NORMAL_E(11) \
TILE_SPR_NORMAL_E(12) \
TILE_SPR_NORMAL_E(13) \
TILE_SPR_NORMAL_E(14) \
TILE_SPR_NORMAL_E(15)
#define TILE_SPR_FLIP_X_LINE_E \
TILE_SPR_FLIP_X_E( 0) \
TILE_SPR_FLIP_X_E( 1) \
TILE_SPR_FLIP_X_E( 2) \
TILE_SPR_FLIP_X_E( 3) \
TILE_SPR_FLIP_X_E( 4) \
TILE_SPR_FLIP_X_E( 5) \
TILE_SPR_FLIP_X_E( 6) \
TILE_SPR_FLIP_X_E( 7) \
TILE_SPR_FLIP_X_E( 8) \
TILE_SPR_FLIP_X_E( 9) \
TILE_SPR_FLIP_X_E(10) \
TILE_SPR_FLIP_X_E(11) \
TILE_SPR_FLIP_X_E(12) \
TILE_SPR_FLIP_X_E(13) \
TILE_SPR_FLIP_X_E(14) \
TILE_SPR_FLIP_X_E(15)
static void pdrawgfx(unsigned int code,unsigned int color,int flipx,int flipy,int sx,int sy,int /*pri*/)
{
unsigned short * p = (unsigned short *) pBurnDraw;
// unsigned char * pp = RamPri;
unsigned char * q = RomGfx02 + (code << 8);
unsigned short *pal = RamCurPal;
sx -= 80;
sy -= 136;
p += sy * 320 + sx;
// pp += sy * 320 + sx;
if (sx < 0 || sx >= (320-16) || sy < 0 || sy >= (240-16) ) {
if ((sx <= -16) || (sx >= 320) || (sy <= -16) || (sy >= 240))
return;
if (flipy) {
p += 320 * 15;
//pp += 320 * 15;
if (flipx) {
for (int i=15;i>=0;i--) {
if (((sy+i)>=0) && ((sy+i)<240)) {
TILE_SPR_FLIP_X_LINE_E
}
p -= 320;
//pp -= 320;
q += 16;
}
} else {
for (int i=15;i>=0;i--) {
if (((sy+i)>=0) && ((sy+i)<240)) {
TILE_SPR_NORMAL_LINE_E
}
p -= 320;
//pp -= 320;
q += 16;
}
}
} else {
if (flipx) {
for (int i=0;i<16;i++) {
if (((sy+i)>=0) && ((sy+i)<240)) {
TILE_SPR_FLIP_X_LINE_E
}
p += 320;
//pp += 320;
q += 16;
}
} else {
for (int i=0;i<16;i++) {
if (((sy+i)>=0) && ((sy+i)<240)) {
TILE_SPR_NORMAL_LINE_E
}
p += 320;
//pp += 320;
q += 16;
}
}
}
return;
}
if (flipy) {
p += 320 * 15;
//pp += 320 * 15;
if (flipx) {
for (int i=0;i<16;i++) {
TILE_SPR_FLIP_X_LINE
p -= 320;
//pp -= 320;
q += 16;
}
} else {
for (int i=0;i<16;i++) {
TILE_SPR_NORMAL_LINE
p -= 320;
//pp -= 320;
q += 16;
}
}
} else {
if (flipx) {
for (int i=0;i<16;i++) {
TILE_SPR_FLIP_X_LINE
p += 320;
//pp += 320;
q += 16;
}
} else {
for (int i=0;i<16;i++) {
TILE_SPR_NORMAL_LINE
p += 320;
//pp += 320;
q += 16;
}
}
}
}
static void drawSprites()
{
int offs = m92_sprite_list - 8;
while (offs >= 0) {
int x,y,sprite,colour,fx,fy,x_multi,y_multi,i,j,s_ptr,pri;
y=(RamSprCpy[offs+0] | (RamSprCpy[offs+1]<<8))&0x1ff;
x=(RamSprCpy[offs+6] | (RamSprCpy[offs+7]<<8))&0x1ff;
if ((RamSprCpy[offs+4]&0x80)==0x80) pri=0; else pri=2;
x = x - 16;
y = 512 - 16 - y;
sprite=(RamSprCpy[offs+2] | (RamSprCpy[offs+3]<<8));
colour= (RamSprCpy[offs+4]&0x7f) << 4;
fx=RamSprCpy[offs+5]&1;
fy=(RamSprCpy[offs+5]&2)>>1;
y_multi=(RamSprCpy[offs+1]>>1)&0x3;
x_multi=(RamSprCpy[offs+1]>>3)&0x3;
y_multi=1 << y_multi; /* 1, 2, 4 or 8 */
x_multi=1 << x_multi; /* 1, 2, 4 or 8 */
if (fx) x+=16 * (x_multi - 1);
for (j=0; j<x_multi; j++) {
s_ptr=8 * j;
if (!fy) s_ptr+=y_multi-1;
for (i=0; i<y_multi; i++) {
pdrawgfx(sprite + s_ptr, colour, fx, fy, x, y-i*16 ,pri);
if (fy) s_ptr++; else s_ptr--;
}
if (fx) x-=16; else x+=16;
offs-=8;
}
}
}
static void DrvDraw()
{
#ifdef FBA_DEBUG
if (nBurnLayer & 8) {
#endif
if (pf3_enable)
tileLayer_3();
else
memset(pBurnDraw, 0, 320 * 240 * 2);
#ifdef FBA_DEBUG
} else
memset(pBurnDraw, 0, 320 * 240 * 2);
#endif
#ifdef FBA_DEBUG
if (nBurnLayer & 4)
#endif
if (pf2_enable)
tileLayer_2();
drawSprites();
#ifdef FBA_DEBUG
if (nBurnLayer & 2)
#endif
if (pf1_enable)
tileLayer_1();
#if 0
bprintf(PRINT_NORMAL, _T("E:%d%d%d S:%d%d%d P:%d%d%d %04x %04x %04x R: %04x %04x, %04x %04x, %04x %04x\n"),
pf1_enable, pf2_enable, pf3_enable,
pf1_rowscroll, pf2_rowscroll, pf3_rowscroll,
pf1_shape, pf2_shape, pf3_shape,
pf1_vram_ptr, pf2_vram_ptr, pf3_vram_ptr,
(pf1_control[5]<<8)+pf1_control[4], (pf1_control[1]<<8) + pf1_control[0],
(pf2_control[5]<<8)+pf2_control[4], (pf2_control[1]<<8) + pf2_control[0],
(pf3_control[5]<<8)+pf3_control[4], (pf3_control[1]<<8) + pf3_control[0] );
#endif
}
static int hookFrame()
{
if (DrvReset) DrvDoReset();
if (bRecalcPalette) {
for (int i=0; i<0x800;i++)
RamCurPal[i] = CalcCol(i<<1);
bRecalcPalette = 0;
}
DrvInput[0] = 0x00;
DrvInput[1] = 0x00;
DrvInput[2] = 0x00;
DrvInput[3] = 0x00;
DrvInput[4] = 0x00;
for (int i=0; i<8; i++) {
DrvInput[0] |= (DrvJoy1[i] & 1) << i;
DrvInput[1] |= (DrvJoy2[i] & 1) << i;
DrvInput[2] |= (DrvJoy3[i] & 1) << i;
DrvInput[3] |= (DrvJoy4[i] & 1) << i;
DrvInput[4] |= (DrvButton[i] & 1) << i;
}
#if 0
VezOpen(0);
VezRun(9000000 / 60);
if ( m92_sprite_buffer_busy == 0 ) {
m92_sprite_buffer_busy = 0x80;
memcpy(RamSprCpy, RamSpr, 0x800);
VezSetIRQLine((m92_irq_vectorbase + 4), VEZ_IRQSTATUS_ACK);
VezRun( m92_sprite_buffer_timer );
}
VezSetIRQLine((m92_irq_vectorbase + 0), VEZ_IRQSTATUS_ACK);
VezOpen(1);
VezRun(7159090 / 60);
if (pBurnDraw) DrvDraw();
if (pBurnSoundOut) {
BurnYM2151Render(pBurnSoundOut, nBurnSoundLen);
IremGA20_update(pBurnSoundOut, nBurnSoundLen);
}
#else
for (int i=0; i<32; i++ ) {
VezOpen(0);
VezRun(9000000 / 60 / 32);
if ( m92_sprite_buffer_busy == 0 ) {
m92_sprite_buffer_busy = 0x80;
memcpy(RamSprCpy, RamSpr, 0x800);
VezSetIRQLine((m92_irq_vectorbase + 4), VEZ_IRQSTATUS_ACK);
VezRun( m92_sprite_buffer_timer );
}
VezOpen(1);
VezRun(7159090 / 60 / 32);
}
VezOpen(0);
VezSetIRQLine((m92_irq_vectorbase + 0), VEZ_IRQSTATUS_ACK);
VezOpen(1);
if (pBurnDraw) DrvDraw();
if (pBurnSoundOut) {
BurnYM2151Render(pBurnSoundOut, nBurnSoundLen);
IremGA20_update(pBurnSoundOut, nBurnSoundLen);
}
#endif
return 0;
}
static int DrvScan(int nAction,int *pnMin)
{
if ( pnMin ) *pnMin = 0x029671;
struct BurnArea ba;
if (nAction & ACB_MEMORY_RAM) { // Scan all memory, devices & variables
memset(&ba, 0, sizeof(ba));
ba.Data = RamStart;
ba.nLen = RamEnd-RamStart;
ba.szName = "All Ram";
BurnAcb(&ba);
if (nAction & ACB_WRITE)
bRecalcPalette = 1;
}
if (nAction & ACB_DRIVER_DATA) {
VezScan(nAction); // Scan 68000 state
SCAN_VAR(DrvInput);
SCAN_VAR(m92_irq_vectorbase);
SCAN_VAR(PalBank);
SCAN_VAR(pf1_control);
SCAN_VAR(pf2_control);
SCAN_VAR(pf3_control);
SCAN_VAR(pf4_control);
SCAN_VAR(pf1_enable);
SCAN_VAR(pf2_enable);
SCAN_VAR(pf3_enable);
SCAN_VAR(pf1_shape);
SCAN_VAR(pf2_shape);
SCAN_VAR(pf3_shape);
SCAN_VAR(pf1_rowscroll);
SCAN_VAR(pf2_rowscroll);
SCAN_VAR(pf3_rowscroll);
SCAN_VAR(pf1_vram_ptr);
SCAN_VAR(pf2_vram_ptr);
SCAN_VAR(pf3_vram_ptr);
SCAN_VAR(m92_sprite_list);
//SCAN_VAR(sound_status);
//SCAN_VAR(m92_sprite_buffer_busy);
//SCAN_VAR(m92_sprite_buffer_timer);
}
return 0;
}
struct BurnDriverD BurnDrvHook = {
"hook", NULL, NULL, "1992",
"Hook (World)\0", "Preliminary driver", "Irem", "Miscellaneous",
NULL, NULL, NULL, NULL,
BDF_GAME_WORKING | BDF_16BIT_ONLY, 4, HARDWARE_MISC_MISC,
NULL, hookRomInfo, hookRomName, hookInputInfo, hookDIPInfo,
hookInit, hookExit, hookFrame, NULL, DrvScan, &bRecalcPalette,
320, 240, 4, 3
};
struct BurnDriverD BurnDrvHooku = {
"hooku", "hook", NULL, "1992",
"Hook (US)\0", "Preliminary driver", "Irem America", "Miscellaneous",
NULL, NULL, NULL, NULL,
BDF_GAME_WORKING | BDF_CLONE | BDF_16BIT_ONLY, 4, HARDWARE_MISC_MISC,
NULL, hookuRomInfo, hookuRomName, hookInputInfo, hookDIPInfo,
hookInit, hookExit, hookFrame, NULL, DrvScan, &bRecalcPalette,
320, 240, 4, 3
};
struct BurnDriverD BurnDrvHookj = {
"hookj", "hook", NULL, "1992",
"Hook (Japan)\0", "Preliminary driver", "Irem", "Miscellaneous",
NULL, NULL, NULL, NULL,
BDF_GAME_WORKING | BDF_CLONE | BDF_16BIT_ONLY, 4, HARDWARE_MISC_MISC,
NULL, hookjRomInfo, hookjRomName, hookInputInfo, hookDIPInfo,
hookInit, hookExit, hookFrame, NULL, DrvScan, &bRecalcPalette,
320, 240, 4, 3
};
static int MemIndex2()
{
unsigned char *Next; Next = Mem;
RomV33 = Next; Next += 0x0C0000; // V33
RomV30 = Next; Next += 0x100000; // V30
RomGfx01 = Next; Next += 0x400000; // char
RomGfx02 = Next; Next += 0x800000; // spr
//MSM6295ROM = Next; Next += 0x080000;
RamStart = Next;
RamVideo = Next; Next += 0x010000;
RamV33 = Next; Next += 0x010000;
RamSpr = Next; Next += 0x000800;
RamSprCpy = Next; Next += 0x000800;
RamPal = Next; Next += 0x001000; // 2 bank of 0x0800
chip = (struct IremGA20_chip *) Next;
Next += sizeof( struct IremGA20_chip );
RamEnd = Next;
RamCurPal = (unsigned short *) Next; Next += 0x001000;
MemEnd = Next;
return 0;
}
static int inthuntInit()
{
int nRet;
Mem = NULL;
MemIndex2();
int nLen = MemEnd - (unsigned char *)0;
if ((Mem = (unsigned char *)malloc(nLen)) == NULL) return 1;
memset(Mem, 0, nLen); // blank all memory
MemIndex2();
nRet = BurnLoadRom(RomV33 + 0x000001, 0, 2); if (nRet != 0) return 1;
nRet = BurnLoadRom(RomV33 + 0x000000, 1, 2); if (nRet != 0) return 1;
nRet = BurnLoadRom(RomV33 + 0x080001, 2, 2); if (nRet != 0) return 1;
nRet = BurnLoadRom(RomV33 + 0x080000, 3, 2); if (nRet != 0) return 1;
nRet = BurnLoadRom(RomV30 + 0x000001, 4, 2); if (nRet != 0) return 1;
nRet = BurnLoadRom(RomV30 + 0x000000, 5, 2); if (nRet != 0) return 1;
// load and decode tile
unsigned char *tmp = (unsigned char *) malloc (0x100000);
if ( tmp == 0 ) return 1;
loadDecodeGfx01(tmp, 6, 0, 0x080000);
loadDecodeGfx01(tmp, 7, 1, 0x080000);
loadDecodeGfx01(tmp, 8, 2, 0x080000);
loadDecodeGfx01(tmp, 9, 3, 0x080000);
loadDecodeGfx02(tmp, 10, 0, 0x100000);
loadDecodeGfx02(tmp, 11, 1, 0x100000);
loadDecodeGfx02(tmp, 12, 2, 0x100000);
loadDecodeGfx02(tmp, 13, 3, 0x100000);
free(tmp);
{
unsigned int cpu_types[] = { 0, 8 };
VezInit(2, &cpu_types[0]);
VezOpen(0);
VezMapArea(0x00000, 0x9ffff, 0, RomV33 + 0x00000); // CPU 0 ROM
VezMapArea(0x00000, 0x9ffff, 2, RomV33 + 0x00000);
VezMapArea(0xa0000, 0xbffff, 0, RomV33 + 0xa0000); // rom bank
VezMapArea(0xa0000, 0xbffff, 2, RomV33 + 0xa0000);
VezMapArea(0xc0000, 0xcffff, 0, RomV33 + 0x00000); // Mirror, Used by In The Hunt as protection
VezMapArea(0xc0000, 0xcffff, 2, RomV33 + 0x00000);
VezMapArea(0xd0000, 0xdffff, 0, RamVideo);
VezMapArea(0xd0000, 0xdffff, 1, RamVideo);
VezMapArea(0xe0000, 0xeffff, 0, RamV33); // system ram
VezMapArea(0xe0000, 0xeffff, 1, RamV33);
VezMapArea(0xf8000, 0xf87ff, 0, RamSpr); // sprites ram
VezMapArea(0xf8000, 0xf87ff, 1, RamSpr);
VezSetReadHandler(m92ReadByte);
VezSetWriteHandler(m92WriteByte);
VezSetReadPort(m92ReadPort);
VezSetWritePort(m92WritePort);
}
m92_irq_vectorbase = 0x80;
PalBank = 0;
BurnYM2151Init(3579545, 80.0); // 3.5795 MHz
YM2151SetIrqHandler(0, &m92YM2151IRQHandler);
DrvDoReset();
return 0;
}
static int inthuntFrame()
{
if (DrvReset) DrvDoReset();
if (bRecalcPalette) {
for (int i=0; i<0x800;i++)
RamCurPal[i] = CalcCol(i<<1);
bRecalcPalette = 0;
}
DrvInput[0] = 0x00;
DrvInput[1] = 0x00;
DrvInput[2] = 0x00;
DrvInput[3] = 0x00;
DrvInput[4] = 0x00;
for (int i = 0; i < 8; i++) {
DrvInput[0] |= (DrvJoy1[i] & 1) << i;
DrvInput[1] |= (DrvJoy2[i] & 1) << i;
DrvInput[2] |= (DrvJoy3[i] & 1) << i;
DrvInput[3] |= (DrvJoy4[i] & 1) << i;
DrvInput[4] |= (DrvButton[i] & 1) << i;
}
VezOpen(0);
//
for (int i=255; i>=0; i--) {
VezRun(9000000 / 60 / 256);
if ( m92_sprite_buffer_busy == 0 ) {
m92_sprite_buffer_busy = 0x80;
memcpy(RamSprCpy, RamSpr, 0x800);
VezSetIRQLine(m92_irq_vectorbase + 4, VEZ_IRQSTATUS_ACK);
VezRun( m92_sprite_buffer_timer );
}
if (i == m92_raster_irq_position)
VezSetIRQLine(m92_irq_vectorbase + 8, VEZ_IRQSTATUS_ACK); // IRQ 2
else
if (i == 249) {
VezSetIRQLine(m92_irq_vectorbase + 0, VEZ_IRQSTATUS_ACK); // IRQ 0
}
}
if (pBurnDraw) DrvDraw();
return 0;
}
struct BurnDriverD BurnDrvInthunt = {
"inthunt", NULL, NULL, "1993",
"In The Hunt (World)\0", "Preliminary driver", "Irem", "Miscellaneous",
NULL, NULL, NULL, NULL,
BDF_GAME_WORKING | BDF_16BIT_ONLY, 2, HARDWARE_MISC_MISC,
NULL, inthuntRomInfo, inthuntRomName, inthuntInputInfo, inthuntDIPInfo,
inthuntInit, hookExit, inthuntFrame, NULL, DrvScan, &bRecalcPalette,
320, 240, 4, 3
};
struct BurnDriverD BurnDrvInthuntu = {
"inthuntu", "inthunt", NULL, "1993",
"In The Hunt (US)\0", "Preliminary driver", "Irem America", "Miscellaneous",
NULL, NULL, NULL, NULL,
BDF_GAME_WORKING | BDF_CLONE | BDF_16BIT_ONLY, 2, HARDWARE_MISC_MISC,
NULL, inthuntuRomInfo, inthuntuRomName, inthuntInputInfo, inthuntDIPInfo,
inthuntInit, hookExit, inthuntFrame, NULL, DrvScan, &bRecalcPalette,
320, 240, 4, 3
};
struct BurnDriverD BurnDrvKaiteids = {
"kaiteids", "inthunt", NULL, "1993",
"Kaitei Daisensou (Japan)\0", "Preliminary driver", "Irem", "Miscellaneous",
NULL, NULL, NULL, NULL,
BDF_GAME_WORKING | BDF_CLONE | BDF_16BIT_ONLY, 2, HARDWARE_MISC_MISC,
NULL, kaiteidsRomInfo, kaiteidsRomName, inthuntInputInfo, inthuntDIPInfo,
inthuntInit, hookExit, inthuntFrame, NULL, DrvScan, &bRecalcPalette,
320, 240, 4, 3
};
static int rtypeleoExit()
{
VezExit();
free(Mem);
Mem = NULL;
return 0;
}
static int rtypeleoInit()
{
int nRet;
Mem = NULL;
MemIndex2();
int nLen = MemEnd - (unsigned char *)0;
if ((Mem = (unsigned char *)malloc(nLen)) == NULL) return 1;
memset(Mem, 0, nLen); // blank all memory
MemIndex2();
nRet = BurnLoadRom(RomV33 + 0x000001, 0, 2); if (nRet != 0) return 1;
nRet = BurnLoadRom(RomV33 + 0x000000, 1, 2); if (nRet != 0) return 1;
nRet = BurnLoadRom(RomV33 + 0x080001, 2, 2); if (nRet != 0) return 1;
nRet = BurnLoadRom(RomV33 + 0x080000, 3, 2); if (nRet != 0) return 1;
nRet = BurnLoadRom(RomV30 + 0x000001, 4, 2); if (nRet != 0) return 1;
nRet = BurnLoadRom(RomV30 + 0x000000, 5, 2); if (nRet != 0) return 1;
// load and decode tile
unsigned char *tmp = (unsigned char *) malloc (0x100000);
if ( tmp == 0 ) return 1;
loadDecodeGfx01(tmp, 6, 0, 0x080000);
loadDecodeGfx01(tmp, 7, 1, 0x080000);
loadDecodeGfx01(tmp, 8, 2, 0x080000);
loadDecodeGfx01(tmp, 9, 3, 0x080000);
loadDecodeGfx02(tmp, 10, 0, 0x100000);
loadDecodeGfx02(tmp, 11, 1, 0x100000);
loadDecodeGfx02(tmp, 12, 2, 0x100000);
loadDecodeGfx02(tmp, 13, 3, 0x100000);
free(tmp);
{
unsigned int cpu_types[] = { 0, 8 };
VezInit(2, &cpu_types[0]);
VezOpen(0);
VezMapArea(0x00000, 0x9ffff, 0, RomV33 + 0x00000); // CPU 0 ROM
VezMapArea(0x00000, 0x9ffff, 2, RomV33 + 0x00000); // CPU 0 ROM
VezMapArea(0xa0000, 0xbffff, 0, RomV33 + 0xa0000); // rom bank
VezMapArea(0xa0000, 0xbffff, 2, RomV33 + 0xa0000); // rom bank
VezMapArea(0xd0000, 0xdffff, 0, RamVideo);
VezMapArea(0xd0000, 0xdffff, 1, RamVideo);
VezMapArea(0xe0000, 0xeffff, 0, RamV33); // system ram
VezMapArea(0xe0000, 0xeffff, 1, RamV33);
VezMapArea(0xf8000, 0xf87ff, 0, RamSpr); // sprites ram
VezMapArea(0xf8000, 0xf87ff, 1, RamSpr);
VezSetReadHandler(m92ReadByte);
VezSetWriteHandler(m92WriteByte);
VezSetReadPort(m92ReadPort);
VezSetWritePort(m92WritePort);
}
m92_irq_vectorbase = 0x20;
PalBank = 0;
DrvDoReset();
return 0;
}
static int rtypeleoFrame()
{
if (DrvReset) DrvDoReset();
if (bRecalcPalette) {
for (int i=0; i<0x800;i++)
RamCurPal[i] = CalcCol(i<<1);
bRecalcPalette = 0;
}
DrvInput[0] = 0x00;
DrvInput[1] = 0x00;
DrvInput[2] = 0x00;
DrvInput[3] = 0x00;
DrvInput[4] = 0x00;
for (int i=0; i<8; i++) {
DrvInput[0] |= (DrvJoy1[i] & 1) << i;
DrvInput[1] |= (DrvJoy2[i] & 1) << i;
DrvInput[2] |= (DrvJoy3[i] & 1) << i;
DrvInput[3] |= (DrvJoy4[i] & 1) << i;
DrvInput[4] |= (DrvButton[i] & 1) << i;
}
#if 0
VezOpen(0);
VezRun(9000000 / 60);
if ( m92_sprite_buffer_busy == 0 ) {
m92_sprite_buffer_busy = 0x80;
memcpy(RamSprCpy, RamSpr, 0x800);
VezSetIRQLine((m92_irq_vectorbase + 4), VEZ_IRQSTATUS_ACK);
VezRun( m92_sprite_buffer_timer );
}
VezSetIRQLine((m92_irq_vectorbase + 0), VEZ_IRQSTATUS_ACK);
VezOpen(1);
VezRun(7159090 / 60);
if (pBurnDraw) DrvDraw();
#else
for (int i=0; i<32; i++ ) {
VezOpen(0);
VezRun(9000000 / 60 / 32);
if ( m92_sprite_buffer_busy == 0 ) {
m92_sprite_buffer_busy = 0x80;
memcpy(RamSprCpy, RamSpr, 0x800);
VezSetIRQLine((m92_irq_vectorbase + 4), VEZ_IRQSTATUS_ACK);
VezRun( m92_sprite_buffer_timer );
}
VezOpen(1);
VezRun(7159090 / 60 / 32);
}
VezOpen(0);
VezSetIRQLine((m92_irq_vectorbase + 0), VEZ_IRQSTATUS_ACK);
VezOpen(1);
if (pBurnDraw) DrvDraw();
#endif
return 0;
}
struct BurnDriverD BurnDrvRtypeleo = {
"rtypeleo", NULL, NULL, "1992",
"R-Type Leo (World)\0", "Preliminary driver", "Irem", "Miscellaneous",
NULL, NULL, NULL, NULL,
BDF_16BIT_ONLY, 2, HARDWARE_MISC_MISC,
NULL, rtypeleoRomInfo, rtypeleoRomName, inthuntInputInfo, inthuntDIPInfo,
rtypeleoInit, rtypeleoExit, rtypeleoFrame, NULL, DrvScan, &bRecalcPalette,
320, 240, 4, 3
};
struct BurnDriverD BurnDrvRtypelej = {
"rtypeleoj", "rtypeleo", NULL, "1992",
"R-Type Leo (Japan)\0", "Preliminary driver", "Irem", "Miscellaneous",
NULL, NULL, NULL, NULL,
BDF_CLONE | BDF_16BIT_ONLY, 2, HARDWARE_MISC_MISC,
NULL, rtypelejRomInfo, rtypelejRomName, inthuntInputInfo, inthuntDIPInfo,
rtypeleoInit, rtypeleoExit, rtypeleoFrame, NULL, DrvScan, &bRecalcPalette,
320, 240, 4, 3
};
| [
"[email protected]"
]
| [
[
[
1,
2176
]
]
]
|
be2b6c967ad5a99d134e5ec3ab3219d48e3fcf04 | 105cc69f4207a288be06fd7af7633787c3f3efb5 | /HovercraftUniverse/GUI/Timer.cpp | 60dd5e5fcbe82fddac9565af560211d18b02b944 | []
| no_license | allenjacksonmaxplayio/uhasseltaacgua | 330a6f2751e1d6675d1cf484ea2db0a923c9cdd0 | ad54e9aa3ad841b8fc30682bd281c790a997478d | refs/heads/master | 2020-12-24T21:21:28.075897 | 2010-06-09T18:05:23 | 2010-06-09T18:05:23 | 56,725,792 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 565 | cpp | #include "Timer.h"
namespace HovUni {
Timer::Timer(const Ogre::String& name, const Ogre::String& fileName, int width, int height, const Hikari::Position& position, Ogre::ushort zOrder)
: BasicOverlay(name, fileName, width, height, position, zOrder) {
}
void Timer::start() {
this->callFunction("start", Hikari::Args());
}
void Timer::stop() {
this->callFunction("stop", Hikari::Args());
}
void Timer::setTime(int minutes, int seconds, int hundreds) {
this->callFunction("setTime", Hikari::Args(minutes)(seconds)(hundreds));
}
} | [
"nick.defrangh@2d55a33c-0a8f-11df-aac0-2d4c26e34a4c"
]
| [
[
[
1,
19
]
]
]
|
c889529c58c8a8937b9d62638241ddb3b2c453e6 | 02a6c89498eb7f9ac38061ae7108e9d466dea285 | /Game Framework Source/List.h | 3f546027b8b3fc62563b41f6f12d530c0c718890 | []
| no_license | PickledMonkey/Blast | d02b99c16ff3f7c0b4a05a9cfbaa41323820bd56 | dd81b7ded83b0fbb3ad09db2ab1e997aaa279003 | refs/heads/master | 2020-04-08T06:57:53.354841 | 2011-10-02T20:43:23 | 2011-10-02T20:43:23 | 2,501,110 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 5,968 | h | #pragma once
//
// List.h
// Game Framework
//
// Created by Ben Menke on 11/24/10.
// Copyright 2011 Menke. All rights reserved.
//
/*
Simple Efficient Linked list object
has a fast memory pool for them.
*/
#include <stddef.h>
namespace Framework
{
//link used to determine free and used memory in a memory pool
struct PoolLink
{
public:
PoolLink* next;
void* operator new(size_t size);
void operator delete(void* p);
};
struct LinkMemPool
{
friend struct PoolLink;
private:
int location;
int available;
void* lastDelete;
PoolLink* first;
char buffer[120000];
void PushLink(PoolLink* link);
PoolLink* PopLink();
public:
LinkMemPool();
void* GetMemory();
void ReleaseMemory(void* object);
//returns how many more links can be made
int AvailableLinks();
};
extern LinkMemPool linkMemory;
template<typename _Element>
struct Link
{
public:
Link<_Element>* next;
Link<_Element>* prev;
_Element* element;
Link()
{
next=NULL;
prev=NULL;
element=NULL;
}
void* operator new(size_t size)
{
void* address=linkMemory.GetMemory();
return address;
}
void operator delete(void* p)
{
linkMemory.ReleaseMemory(p);
}
};
template<typename _Element>
class List
{
//friend class List<_Element>; used in visual studio
private:
Link<_Element>* first;
Link<_Element> last;
int numbElement;
public:
List()
{
first=&last;
numbElement=0;
}
~List()
{
while(pop()) {}
}
int getSize()
{
return numbElement;
}
bool push(_Element* element)
{
Link<_Element>* link=new Link<_Element>;
link->element=element;
link->next=first;
first->prev=link;
first=link;
numbElement+=1;
return true;
}
bool pop()
{
if(first!=&last)
{
Link<_Element>* temp=first;
temp->next->prev=NULL;
first=temp->next;
temp->next=NULL;
temp->prev=NULL;
numbElement-=1;
delete temp;
return true;
}
return false;
}
bool pushEnd(_Element* element)
{
Link<_Element>* link=new Link<_Element>;
link->element=element;
last->prev->next=link;
link->prev=last->prev;
link->next=last;
last->prev=link;
numbElement+=1;
return true;
}
bool popEnd()
{
if(first!=last)
{
Link<_Element>* temp=last->prev;
if(temp->prev!=NULL)
{
temp->prev->next=temp->next;
temp->next->prev=temp->prev;
}
else
{
first=last;
}
temp->next=NULL;
temp->prev=NULL;
numbElement-=1;
delete temp;
return true;
}
return false;
}
bool insert(_Element* element, Link<_Element>* location, bool before=false)
{
Link<_Element>* link=new Link<_Element>();
link->element=element;
if(before)
{
link->prev=location->prev;
link->next=location;
if(location->prev!=NULL)
location->prev->next=link;
location->prev=link;
if(location==first)
first=link;
}
else
{
link->next=location->next;
if(location->next!=NULL)
location->next->prev=link;
location->next=link;
link->prev=location;
}
numbElement+=1;
return true;
}
bool remove(Link<_Element>* element)
{
if(element->next)
element->next->prev=element->prev;
if(element->prev)
element->prev->next=element->next;
if(element==first)
first=element->next;
element->next=NULL;
element->prev=NULL;
numbElement-=1;
delete element;
return true;
}
bool merge(List<_Element>* list, Link<_Element>* location)
{
if(list->last!=list->first)
{
list->last->prev->next=location->next;
location->next->prev=list->last->prev;
list->first->prev=location;
location->next=list->first;
list->first=list->last;
numbElement+=list->numbElement;
list->numbElement=0;
}
return true;
}
Link<_Element>* begin()
{
return first;
}
Link<_Element>* end()
{
return &last;
}
};
}
| [
"[email protected]"
]
| [
[
[
1,
239
]
]
]
|
208f51c4de1c3bf36bbb398e0dc8de9d067dd878 | c5ecda551cefa7aaa54b787850b55a2d8fd12387 | /src/UILayer/HtmlCtrl.h | a685a737e283028aab70367de21165d81a75d50f | []
| no_license | firespeed79/easymule | b2520bfc44977c4e0643064bbc7211c0ce30cf66 | 3f890fa7ed2526c782cfcfabb5aac08c1e70e033 | refs/heads/master | 2021-05-28T20:52:15.983758 | 2007-12-05T09:41:56 | 2007-12-05T09:41:56 | null | 0 | 0 | null | null | null | null | GB18030 | C++ | false | false | 1,514 | h | #pragma once
#include "IEManagerWnd.h"
// CHtmlCtrl Html 视图
#include "ProgressStatic.h"
class CHtmlCtrl : public CHtmlView
{
DECLARE_DYNCREATE(CHtmlCtrl)
public:
CHtmlCtrl(){ }; // 动态创建所使用的受保护的构造函数
virtual ~CHtmlCtrl()
{
}
BOOL CreateFromStatic(UINT nID, CWnd* pParent);
public:
#ifdef _DEBUG
virtual void AssertValid() const;
virtual void Dump(CDumpContext& dc) const;
#endif
protected:
virtual void DoDataExchange(CDataExchange* pDX); // DDX/DDV 支持
DECLARE_MESSAGE_MAP()
CProgressStatic m_sttcProgress;
public:
virtual void OnBeforeNavigate2(LPCTSTR lpszURL, DWORD nFlags, LPCTSTR lpszTargetFrameName, CByteArray& baPostedData, LPCTSTR lpszHeaders, BOOL* pbCancel);
afx_msg void OnDestroy();
virtual void OnDocumentComplete(LPCTSTR lpszURL);
afx_msg int OnMouseActivate(CWnd* pDesktopWnd, UINT nHitTest, UINT message);
virtual void OnNavigateComplete2(LPCTSTR strURL);
afx_msg void OnSize(UINT nType, int cx, int cy);
virtual void OnStatusTextChange(LPCTSTR lpszText);
protected:
virtual void PostNcDestroy();
public:
virtual void OnTitleChange(LPCTSTR lpszText);
virtual void OnProgressChange(long nProgress, long nProgressMax);
afx_msg int OnCreate(LPCREATESTRUCT lpCreateStruct);
virtual void OnCommandStateChange(long nCommand, BOOL bEnable);
protected:
HWND GetBrowserHwnd(void);
CIEManagerWnd m_IEManagerWnd;
public:
BOOL bForwordEnable;
BOOL bBackEnable;
};
| [
"LanceFong@4a627187-453b-0410-a94d-992500ef832d"
]
| [
[
[
1,
55
]
]
]
|
0ae0745350dc23b67bce840dbbf426c75a6b33aa | bfdfb7c406c318c877b7cbc43bc2dfd925185e50 | /compiler/hyCCompileError.h | f4957103d2e96786200156a0889d2ef99f9a9f38 | [
"MIT"
]
| permissive | ysei/Hayat | 74cc1e281ae6772b2a05bbeccfcf430215cb435b | b32ed82a1c6222ef7f4bf0fc9dedfad81280c2c0 | refs/heads/master | 2020-12-11T09:07:35.606061 | 2011-08-01T12:38:39 | 2011-08-01T12:38:39 | null | 0 | 0 | null | null | null | null | SHIFT_JIS | C++ | false | false | 2,354 | h | /* -*- coding: sjis-dos; -*- */
/*
* copyright 2010 FUKUZAWA Tadashi. All rights reserved.
*/
#ifndef m_HYCCOMPILEERROR_H_
#define m_HYCCOMPILEERROR_H_
#include "machdep.h"
namespace Hayat {
namespace Parser {
class SyntaxTree;
}
namespace Compiler {
// エラーかワーニングかを出力
extern void outEventTitle(bool bErr);
// ソース位置情報を出力
extern void outSourceInfo(hyu32 sourcePos);
// メッセージを出力
extern void outMessage(const char* fmt, ...);
extern void v_outMessage(const char* fmt, va_list ap);
extern void v_outEvent(bool ev, hyu32 sourcePos, const char* fmt, va_list ap);
// ワーニング出力
extern void outWarning(hyu32 sourcePos, const char* fmt, ...);
inline void v_outWarning(hyu32 sourcePos, const char* fmt, va_list ap) { v_outEvent(false, sourcePos, fmt, ap); }
// エラー出力
extern void outError(hyu32 sourcePos, const char* fmt, ...);
inline void v_outError(hyu32 sourcePos, const char* fmt, va_list ap) { v_outEvent(true, sourcePos, fmt, ap); }
// setCompileErrorPos()でセットされた場所を表示してエラーにする
extern void compileError(const char* fmt, ...);
extern void compileWarning(const char* fmt, ...);
// エラーの場所をセット
extern void setCompileErrorPos(hyu32 sourcePos);
extern void setCompileErrorPos(Hayat::Parser::SyntaxTree* st);
extern hyu32 getCompileErrorPos(void);
// 指定の場所を表示してエラーにする
extern void compileError_pos(hyu32 sourcePos, const char* fmt, ...);
extern void compileError_pos(Hayat::Parser::SyntaxTree* st, const char* fmt, ...);
// コンパイラ内で発生する例外クラス
class CException {
public:
CException(void) : message(NULL) {}
CException(const char* mes) : message(mes) {}
virtual ~CException() {}
static void throwEx(const char* mes) {
CException ex(mes);
throw ex;
}
public:
const char* message;
};
}
}
#endif /* m_HYCCOMPILEERROR_H_ */
| [
"[email protected]"
]
| [
[
[
1,
66
]
]
]
|
8b11e03484237ec8a766d2cbe00a090b9b6aed11 | e7c45d18fa1e4285e5227e5984e07c47f8867d1d | /Common/Models/CONTROL1/Actuator.cpp | 58053437bd1e42e6be50e3ae8500be86c00eb575 | []
| no_license | abcweizhuo/Test3 | 0f3379e528a543c0d43aad09489b2444a2e0f86d | 128a4edcf9a93d36a45e5585b70dee75e4502db4 | refs/heads/master | 2021-01-17T01:59:39.357645 | 2008-08-20T00:00:29 | 2008-08-20T00:00:29 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 30,642 | cpp | //================== SysCAD - Copyright Kenwalt (Pty) Ltd ===================
// $Nokeywords: $
//===========================================================================
#include "stdafx.h"
#include "sc_defs.h"
//#include "pgm_e.h"
#include "actuator.h"
#if !SKIPIT
//==========================================================================
enum { Fail_None = 0x0000,
Fail_Hold = 0x0001,
Fail_MinVal = 0x0002,
Fail_MaxVal = 0x0003,
Fail_LoVal = 0x0004,
Fail_HiVal = 0x0005,
Fail_Type = 0x000f,
Fail_Ramp = 0x0010,
Fail_Noise = 0x0020
};
enum { XF_None,
XF_Linear,
XF_Sqr,
XF_Sqrt
};
enum { Flt_None,
Flt_FirstOrder
};
enum { XL_None,
XL_Linear,
XL_AtoD,
XL_PulseEncode
};
const long FunctSubsStartIndex = 500;
//==========================================================================
CActuatorBlk::CActuatorBlk():
m_InputVar(BXO_Blank),
m_OutputVar(BXOptions(BXO_Blank|BXO_Funct))
{
//m_OutputVar.Init(TRUE, TRUE);
m_bValid=0;
m_iPriority=0;
m_dReqdValue=0;
m_dOutputValue=0;
m_Xform.m_iType=0;
m_Xform.m_dFactor=1;
m_Xform.m_dBias=0;
m_Flt.m_iType=0;
m_Flt.m_dTau=1;
m_Flt.m_dPrevValue=0;
m_Fail.m_iType=0;
m_Fail.m_dSlewTime=300;
m_Fail.m_dLoValue=0;
m_Fail.m_dHiValue=100;
m_Fail.m_dNoiseStdDevFrac=0.1f;
m_Fail.m_dPrevValue=0;
m_dMinValue=0;
m_dMaxValue=100;
m_dLoLimit=0;
m_dHiLimit=100;
m_bLoInvert=0;
m_bHiInvert=0;
m_bLo=0;
m_bHi=0;
m_RawXform.m_iType=0;
m_RawXform.m_dMinValue=0;
m_RawXform.m_dMaxValue=4095;
m_dOutputValue=0;
}
//--------------------------------------------------------------------------
CActuatorBlk::~CActuatorBlk()
{
}
//--------------------------------------------------------------------------
void CActuatorBlk::Init(CNodeXRefMngr * ERH, int iNo)
{
// sTagSuffix.Set("FS_%d", iNo);
m_iPriority = iNo;
//pXRM = ERH;
}
//--------------------------------------------------------------------------
/**********
inline double tx_Linear_Interpolate (double x, double x1, double y1, double x2, double y2)
//; The function will return the result of a 2D linear interpolation for x between points
//; (x1,y1) and (x2,y2). If abs(x1 - x2) < epsilon (with epsilon = 1e-10) then y1 will be
//; returned.
{
double epsilon;
double y, delta_x, gradient;
epsilon = 1e-10;
y = y1;
delta_x = fabs(x1 - x2);
if (delta_x >= epsilon)
{
gradient = (y1 - y2) / (x1 - x2);
y = y1 + gradient * (x - x1);
}
return y;
}
inline double tx_Bounded_Linear_Interpolate (double x, double x1, double y1,
double x2, double y2,
double y_min, double y_max)
//; The function will perform a 2D linear interpolation for x between points (x1,y1) and
//; (x2,y2). If abs(x1 - x2) < epsilon (with epsilon = 1e-10) the y1 will be used as result.
//; The result will be limited to the range [y_min,y_max] before being returned.
{
double y;
y = tx_Linear_Interpolate(x, x1, y1, x2, y2);
y = Range(y_min, y, y_max);
return y;
}
inline double tx_First_Order_Filter (double & current_value, double target_value, double time_constant, double dT)
//; The parameter current_value will follow the parameter target_value with first-order
//; behaviour as defined by the time constant time_constant in seconds. If
//; time_constant <= 0, current_value will follow target_value without delay.
{
double new_value;
if (time_constant <= 0)
new_value = target_value;
else
new_value = current_value + (target_value - current_value) * (1-exp(-dT / GTZ(time_constant)));
current_value=new_value;
return new_value;
}
**********/
void CActuatorBlk::ExecIns(double dT)
{
// double temp_rvalue, target_value, min_p, max_f, period, dt, max_time
// double frequency_tolerance
double Value;
Value = m_dReqdValue;
// switch (m_Flt.m_iType)
// {
// case Flt_FirstOrder:
// Value = tx_First_Order_Filter (m_Flt.m_dPrevValue, Range((double)m_dMinValue, Value, (double)m_dMaxValue), m_Flt.m_dTau, dT);
// break;
// default:;
// }
//
if ((m_Fail.m_iType & Fail_Type)!=0)
m_Fail.m_dPrevValue=Value;
switch (m_Fail.m_iType & Fail_Type)
{
case Fail_MinVal:
Value = m_dMinValue;
break;
case Fail_MaxVal:
Value = m_dMaxValue;
break;
case Fail_LoVal:
Value = m_Fail.m_dLoValue;
break;
case Fail_HiVal:
Value = m_Fail.m_dHiValue;
break;
case Fail_Hold:
Value = m_Fail.m_dPrevValue;
break;
}
if (m_Fail.m_iType & Fail_Ramp)
{
double MaxChg=(m_dMaxValue-m_dMinValue)*dT/GTZ(m_Fail.m_dSlewTime);
Value = m_dValue + Range(-MaxChg, Value-m_dValue, MaxChg);
Value = Range((double)m_dMinValue, Value, (double)m_dMaxValue);
}
switch (m_Xform.m_iType)
{
case XF_Linear:
Value = (Value - m_Xform.m_dBias)/m_Xform.m_dFactor;
break;
case XF_Sqr:
Value=Value*Value;
Value = (Value - m_Xform.m_dBias)/m_Xform.m_dFactor;
break;
case XF_Sqrt:
Value=Sqrt(GEZ(Value));
Value = (Value - m_Xform.m_dBias)/m_Xform.m_dFactor;
break;
default:;
}
m_dOutputValue = Value;
// calculate switches
m_bLo=(m_dOutputValue <= m_dLoLimit);
m_bHi=(m_dOutputValue >= m_dHiLimit);
if (m_bLoInvert)
m_bLo=!m_bLo;
if (m_bHiInvert)
m_bHi=!m_bHi;
// // calculate raw value
// switch (m_RawXform.m_iType)
// {
// case XL_Linear:
// m_dOutputValue = tx_Bounded_Linear_Interpolate (m_dValue, m_dMinValue, m_RawXform.m_dMinValue,
// m_dMaxValue, m_RawXform.m_dMaxValue,
// m_RawXform.m_dMinValue, m_RawXform.m_dMaxValue);
// break;
// case XL_AtoD:
// m_dOutputValue = tx_Bounded_Linear_Interpolate (m_dValue, m_dMinValue, m_RawXform.m_dMinValue,
// m_dMaxValue, m_RawXform.m_dMaxValue,
// m_RawXform.m_dMinValue, m_RawXform.m_dMaxValue);
// m_dOutputValue = Range((long)m_RawXform.m_dMinValue, (long)m_dOutputValue, (long)m_RawXform.m_dMaxValue);
// break;
// case XL_PulseEncode:
// /*
// if (maximum_frequency > 0)
// dt = DeltaTime()
// frequency_tolerance = 1e-10
// min_p = 2*dt
// max_f = 1 / min_p
// minimum_frequency = max(minimum_frequency,0)
// maximum_frequency = min(maximum_frequency, max_f)
// frequency = tx_Bounded_Linear_Interpolate (value, minimum_value, minimum_frequency,
// maximum_value, maximum_frequency,
// minimum_frequency, maximum_frequency)
// if (frequency < frequency_tolerance)
// frequency = 0
// endif
// if (frequency > 0)
// period = 1 / frequency
// max_time = period / 2
// timer = timer + dt
// if (timer >= max_time)
// timer = 0
// pulse = not(pulse)
// endif
// else
// timer = 0
// pulse = 0
// endif
// else
// pulse = 0
// endif
// pulse_inverse = not(pulse)
// */
// m_dOutputValue = m_dValue;
// break;
// default:
// m_dOutputValue = m_dValue;
// };
}
//==========================================================================
//
//
//
//==========================================================================
/*#D:#T:Flow Controller(1)
#X:#h<General Description>#nThis unit is used to ...
#n#n
#G:Units
*/
flag CActuator::bWithCnvComment = true;
const long MaxXMTs=20;
const long MaxIOListLen=1*MaxXMTs+1;
static IOAreaRec BaseActuatorIOArea = {NULL, NULL, CtrlIOId(0), LIO_In, nc_CLnk, 0, 1};
static CArray <IOAreaRec, IOAreaRec&> ActuatorIOAreaList;
static CSArray IONames;
double Drw_Actuator[] =
{
DD_Arc, 0,0, 1.8,
DD_TagPos, 0, -5.3,
DD_End
};
IMPLEMENT_MODELUNIT(CActuator, "Actuator", "", Drw_Actuator, "Control", "T", TOC_ALL|TOC_DYNAMICFLOW|TOC_GRP_GENERAL|TOC_STD_KENWALT,
"Control:Actuator",
"Control - Actuator.")
CActuator::CActuator(pTagObjClass pClass_, pchar TagIn, pTaggedObject pAttach, TagObjAttachment eAttach) :
FlwNode(pClass_, TagIn, pAttach, eAttach)
//, m_MXRH(this)
{
if (ActuatorIOAreaList.GetSize()==0)
{
ActuatorIOAreaList.SetSize(MaxIOListLen);
IONames.SetSize(MaxIOListLen);
int j=0;
for (int i=0; i<MaxXMTs; i++)
{
IONames[j].Set("A%i.Rqd", i);
ActuatorIOAreaList[j]=BaseActuatorIOArea;
ActuatorIOAreaList[j].m_Id=CtrlIOId(j);
ActuatorIOAreaList[j].SetIOName(IONames[j]());
ActuatorIOAreaList[j].SetIODesc("");
j++;
//IONames[j].Set("T%i.Raw", i);
//ActuatorIOAreaList[j]=BaseActuatorIOArea;
//ActuatorIOAreaList[j].Id=j;
//ActuatorIOAreaList[j].pName=IONames[j]();
//j++;
}
ActuatorIOAreaList[j++]=BaseActuatorIOArea;
}
AttachClassInfo(nc_Control, &ActuatorIOAreaList[0], &NullFlwGroup);
SetActiveOptions(true, true);
bOn = 1;
//bDoneExtRefs = 0;
bAboutToStart = 0;
//m_DataBlk.GetSize() = 0;
//m_DataBlk = NULL;
for (int i=0; i<3; i++)
m_StateLine[i] = "";
m_StateLine[0] = "OK";
//SetCount(MaxXMTs);
}
//--------------------------------------------------------------------------
CActuator::~CActuator()
{
SetCount(0);
}
//--------------------------------------------------------------------------
void CActuator::SetCount(long NewSize)
{
NewSize = Range(0L, NewSize, MaxXMTs);
if (NewSize!=m_DataBlk.GetSize())
{
m_DataBlk.SetSize(NewSize);
if (SortRqd())
Sort();
FixIOTags();
StructureChanged(this);
}
}
//--------------------------------------------------------------------------
flag CActuator::SortRqd()
{
return false; // This will prevent IO problems. - maybe improve
//for (int i=1; i<m_DataBlk.GetSize(); i++)
// {
// if (m_DataBlk[i-1]->m_iPriority>m_DataBlk[i]->m_iPriority)
// return true;
// }
//return false;
}
//--------------------------------------------------------------------------
void CActuator::Sort()
{
//for (int i=0; i<m_DataBlk.GetSize(); i++)
// {
// int MinPos = -1;
// long MinVal = m_DataBlk[i]->m_iPriority;
// for (int j=i+1; j<m_DataBlk.GetSize(); j++)
// {
// if (m_DataBlk[j]->m_iPriority<MinVal)
// {
// MinPos = j;
// MinVal = m_DataBlk[j]->m_iPriority;
// }
// }
// if (MinPos>=0)
// {
// CActuatorBlk * p = &m_DataBlk[i];
// m_DataBlk[i] = m_DataBlk[MinPos];
// m_DataBlk[MinPos] = p;
// }
// }
//StructureChanged(this);
}
//--------------------------------------------------------------------------
void CActuator::FixIOTags()
{
int N=m_DataBlk.GetSize()*1+1;
m_IOAreas.SetSize(N);
int j=0;
for (int i=0; i<m_DataBlk.GetSize(); i++)
{
CActuatorBlk * pT = m_DataBlk[i];
if (!pT->m_sID())
pT->m_sID.Set("A%i",i);
pT->m_sIDInput.Set("%s.%s.Rqd", Tag(), pT->m_sID());
pT->m_sIDOutput.Set("%s.%s.Out", Tag(), pT->m_sID());
pT->m_sTagInput.Set("%s.Cfg.[%i].%s", Tag(), i, "Rqd");
pT->m_sTagOutput.Set("%s.Cfg.[%i].%s", Tag(), i, "Out");
IOAreaRec & AV= m_IOAreas[j];
AV=BaseActuatorIOArea;
AV.SetIODesc(pT->m_sIDInput());
AV.SetIOName(IONames[j]());
AV.m_Id=CtrlIOId(j);
j++;
//IOAreaRec & AR= m_IOAreas[j];
//AR=BaseActuatorIOArea;
//AR.pDesc=pT->m_sIORaw();
//AR.pName=IONames[j]();
//AR.Id=j;
//j++;
}
m_IOAreas[j]=BaseActuatorIOArea;
AttachIOAreas(&m_IOAreas[0], NULL, NULL, false);
StructureChanged(this);
}
//--------------------------------------------------------------------------
void CActuator::ResetData(flag Complete)
{
}
//--------------------------------------------------------------------------
LPSTR CActuator::Tag()
{
return FlwNode::Tag();
};
LPSTR CActuator::SetTag(LPSTR ReqdTag, bool AllowEmptyTag)
{
FlwNode::SetTag(ReqdTag, AllowEmptyTag);
if (ReqdTag)
FixIOTags();
return FlwNode::Tag();
};
//--------------------------------------------------------------------------
void CActuator::Ctrl_ConnIDStr(int i, Strng & ID, Strng & Tg)
{
int ix=(IOId_Self(i)-CtrlIOId(0))/2;
if (ix<m_DataBlk.GetSize())
{
CActuatorBlk * pT = m_DataBlk[ix];
ID=pT->m_sIDInput();
Tg=pT->m_sTagInput();
}
else
ID=Tg=FullObjTag();
};
//--------------------------------------------------------------------------
const word idmCount = 1000;
const word idmCheckBtn = 1001;
const word idmCfgTags = 1100;
const word NoOfCfgTags = 10;
//--------------------------------------------------------------------------
void CActuator::BuildDataDefn(DataDefnBlk & DDB)
{
DDB.BeginStruct(this, "CActuator", NULL, DDB_NoPage);
DDB.Text("");
DDB.CheckBoxBtn("On", "", DC_, "", &bOn, this, isParmStopped, DDBYesNo);
DDB.CheckBoxBtn("ShowCnv", "", DC_, "", &bWithCnvComment,this, isParmStopped, DDBYesNo);
DDB.Visibility();
DDB.Long("", "Ac_Cnt", DC_, "", idmCount, this, isParmStopped/*|AffectsStruct*/);
DDB.Text("");
if (m_DataBlk.GetSize()>0)
{
DDB.Button("Check_tags", "", DC_, "", idmCheckBtn, this, isParmStopped);
DDB.Text("");
DDB.String("State", "", DC_, "", &m_StateLine[0], this, noSnap|noFile);
DDB.Text("Error:");
DDB.String("Msg_1", "", DC_, "", &m_StateLine[1], this, noSnap|noFile);
DDB.String("Msg_2", "", DC_, "", &m_StateLine[2], this, noSnap|noFile);
DDB.Text("");
}
DDB.Text("----------------------------------------");
static DDBValueLst DDBFail[]={
{Fail_None, "None" },
{Fail_Hold, "Hold" },
{Fail_Hold|Fail_Noise, "Hold,Noise" },
{Fail_MinVal, "MinVal" },
{Fail_MaxVal, "MaxVal" },
{Fail_LoVal, "LoVal" },
{Fail_HiVal, "HiVal" },
{Fail_MinVal|Fail_Ramp, "MinVal,Ramp" },
{Fail_MaxVal|Fail_Ramp, "MaxVal,Ramp" },
{Fail_LoVal|Fail_Ramp, "LoVal,Ramp" },
{Fail_HiVal|Fail_Ramp, "HiVal,Ramp" },
{Fail_MinVal|Fail_Noise, "MinVal,Noise" },
{Fail_MaxVal|Fail_Noise, "MaxVal,Noise" },
{Fail_LoVal|Fail_Noise, "LoVal,Noise" },
{Fail_HiVal|Fail_Noise, "HiVal,Noise" },
{Fail_MinVal|Fail_Ramp|Fail_Noise, "MinVal,Ramp,Noise"},
{Fail_MaxVal|Fail_Ramp|Fail_Noise, "MaxVal,Ramp,Noise"},
{Fail_LoVal|Fail_Ramp|Fail_Noise, "LoVal,Ramp,Noise" },
{Fail_HiVal|Fail_Ramp|Fail_Noise, "HiVal,Ramp,Noise" },
{0}};
static DDBValueLst DDBXForms[]={
{XF_None, "None" },
{XF_Linear, "Linear" },
//{XF_Sqr, "Sqr" },
//{XF_Sqrt, "Sqrt" },
{0}};
static DDBValueLst DDBFilters[]={
{Flt_None, "None" },
{Flt_FirstOrder, "FirstOrder" },
{0}};
static DDBValueLst DDBRawXLates[]={
{XL_None, "None" },
{XL_AtoD, "AtoD" },
{XL_Linear, "Linear" },
//{XL_PulseEncode "PulseWidth" },
{0}};
char Buff[128];
Strng Tag;
if (DDB.BeginArray(this, "Cfg", "Ac_Cfg", m_DataBlk.GetSize()))
{
for (int i=0; i<m_DataBlk.GetSize(); i++)
{
if (1)// i>0 && (i % 2)==1)
{
sprintf(Buff, "%d", i);
DDB.Page(Buff, DDB_OptPage);
}
DDB.BeginElement(this, i);
CActuatorBlk * T = m_DataBlk[i];
Strng CnvTxt;
if (bWithCnvComment && XRefsValid() && T->m_bValid)
GetValidCnvTxt(T->m_OutputVar, CnvTxt);
DDB.String("ID", "", DC_, "", idmCfgTags+(i*NoOfCfgTags)+1, this, isParmStopped|isTag);
DDB.String("OutputTag", "", DC_, "", idmCfgTags+(i*NoOfCfgTags)+2, this, isParmStopped|isTag);
//DDB.Double("RequiredValue", "ReqdVal", DC_, "", &T->m_dReqdValue, this, isResult|noFileAtAll);
DDB.Double("RequiredValue", "Rqd", DC_, "", &T->m_dReqdValue, this, isResult|noFileAtAll);
if (CnvTxt.Len())
DDB.TagComment(CnvTxt());
// DDB.Byte ("Transform", "", DC_, "", &T->m_Xform.m_iType, this, isParm|SetOnChange, DDBXForms);
// DDB.Visibility(NSHM_All, T->m_Xform.m_iType);
// DDB.Float ("Xf.Factor", "", DC_, "", &T->m_Xform.m_dFactor, this, isParm);
// DDB.Float ("Xf.Bias", "", DC_, "", &T->m_Xform.m_dBias, this, isParm);
//
// DDB.Visibility();
//
// DDB.Byte ("Filter", "", DC_, "", &T->m_Flt.m_iType, this, isParm|SetOnChange, DDBFilters);
// DDB.Visibility(NSHM_All, T->m_Flt.m_iType == Flt_FirstOrder);
// DDB.Float ("Flt.TimeConst", "Flt.Tau", DC_Time, "s", &T->m_Flt.m_dTau, this, isParm);
// DDB.Double("Flt.PrevValue", "", DC_, "", &T->m_Flt.m_dPrevValue, this, InitHidden);
// DDB.Visibility();
//
// DDB.Byte ("Fail.Mode", "", DC_, "", &T->m_Fail.m_iType, this, isParm|SetOnChange, DDBFail);
// DDB.Float ("Fail.LoValue", "", DC_, "", &T->m_Fail.m_dLoValue, this, isParm);
// DDB.Float ("Fail.HiValue", "", DC_, "", &T->m_Fail.m_dHiValue, this, isParm);
// DDB.Float ("Fail.NoiseStdDev", "", DC_, "%", &T->m_Fail.m_dNoiseStdDevFrac, this, isParm);
// DDB.Float ("Fail.SlewTime", "", DC_Time, "s", &T->m_Fail.m_dSlewTime, this, isParm);
//
//
// DDB.Float ("MinValue", "MinV", DC_, "", &T->m_dMinValue, this, isParm);
// DDB.Float ("MaxValue", "MaxV", DC_, "", &T->m_dMaxValue, this, isParm);
// DDB.Double("Value", "", DC_, "", &T->m_dValue, this, isResult);
//
// DDB.Float ("LoLimit", "LL", DC_, "", &T->m_dLoLimit, this, isParm);
// DDB.Float ("HiLimit", "HL", DC_, "", &T->m_dHiLimit, this, isParm);
//
flag ff=0;
DDB.CheckBox ("LoInvert", "", DC_, "", &T->m_bLoInvert, this, isParm|SetOnChange);
DDB.CheckBox ("HiInvert", "", DC_, "", &T->m_bHiInvert, this, isParm|SetOnChange);
DDB.Bool ("", "Lo", DC_, "", &T->m_bLo, this, isResult);
DDB.Bool ("", "Hi", DC_, "", &T->m_bHi, this, isResult);
// DDB.Byte ("RawTransform", "", DC_, "", &T->m_RawXform.m_iType, this, isParm|SetOnChange, DDBRawXLates);
// DDB.Visibility(NSHM_All, T->m_RawXform.m_iType>=XL_AtoD);
// DDB.Float ("Raw.MinValue", "", DC_, "", &T->m_RawXform.m_dMinValue, this, isParm);
// DDB.Float ("Raw.MaxValue", "", DC_, "", &T->m_RawXform.m_dMaxValue, this, isParm);
// DDB.Visibility();
//
//DDB.Double ("OutputValue", "Output", DC_, "", &T->m_dOutputValue, this, isResult);
DDB.Double ("OutputValue", "Out", DC_, "", &T->m_dOutputValue, this, isResult);
DDB.String ("PLCAddess", "", DC_, "", &T->m_sPLCAddress, this, isParmStopped|InitHidden);
DDB.Long ("Priority", "", DC_, "", idmCfgTags+(i*NoOfCfgTags)+4, this, isParmStopped|InitHidden);
DDB.Text("----------------------------------------");
}
}
DDB.EndArray();
DDB.EndStruct();
}
//--------------------------------------------------------------------------
flag CActuator::DataXchg(DataChangeBlk & DCB)
{
if (FlwNode::DataXchg(DCB))
return 1;
switch (DCB.lHandle)
{
case idmCount:
if (DCB.rL)
{
if (*DCB.rL!=m_DataBlk.GetSize())
StructureChanged(this);
SetCount(Range(0L, *DCB.rL, 50L));
}
DCB.L = m_DataBlk.GetSize();
return True;
case idmCheckBtn:
if (DCB.rB && (*DCB.rB!=0))
{
//AccNodeWnd::RefreshData(TRUE); ???
//TODO: need to accept current data before processing button push!
if (PreStartCheck())
LogNote(Tag(), 0, "No bad external tag references or function errors");
bAboutToStart = 0;
}
DCB.B=0;
return True;
default:
if (DCB.lHandle>=idmCfgTags)
{
int Index = (DCB.lHandle - idmCfgTags) / NoOfCfgTags;
if (Index<m_DataBlk.GetSize())
{
CActuatorBlk * T = m_DataBlk[Index];
switch ((DCB.lHandle - idmCfgTags) - (Index * NoOfCfgTags))
{
case 1:
{
if (DCB.rpC)
{
bool OK=true;
for (int i=0; OK && i<m_DataBlk.GetSize(); i++)
if (i!=Index && m_DataBlk[i]->m_sID.XStrICmp(DCB.rpC)==0)
OK=false;
if (OK)
{
T->m_sID=DCB.rpC;
for (int j=0; j<T->m_sID.Length(); j++)
if (T->m_sID[j]==' ')
T->m_sID[j]=' ';
MyTagsHaveChanged();
}
}
DCB.pC = T->m_sID();
break;
}
case 2:
{
if (DCB.rpC)
{
if (T->m_OutputVar.SetVar(DCB.rpC, false, NULL, &T->m_sID)==1)
{
MyTagsHaveChanged();
}
}
DCB.pC = T->m_OutputVar.sVar();
break;
}
case 4:
if (DCB.rL)
{
T->m_iPriority = *DCB.rL;
if (SortRqd())
{
Sort();
}
}
DCB.L = T->m_iPriority;
break;
// case 5:
// //if (DCB.rD)
// // xxx = *DCB.rD;
// DCB.D = T->dTotalMass/GTZ(T->dTtlTime);
// break;
// case 6:
// //if (DCB.rD)
// // xxx = *DCB.rD;
// DCB.D = T->dTotalMass/GTZ(T->dTtlTime - T->dZeroTime);
// break;
// case 7:
// //if (DCB.rD)
// // xxx = *DCB.rD;
// DCB.D = T->dTotalVol/GTZ(T->dTtlTime);
// break;
// case 8:
// //if (DCB.rD)
// // xxx = *DCB.rD;
// DCB.D = T->dTotalMassS/GTZ(T->dTtlTime);
// break;
// case 9:
// //if (DCB.rD)
// // xxx = *DCB.rD;
// DCB.D = T->dTotalMassL/GTZ(T->dTtlTime);
// break;
}
}
return True;
}
}
return False;
}
//--------------------------------------------------------------------------
flag CActuator::ValidateData(ValidateDataBlk & VDB)
{
if (m_DataBlk.GetSize()<1)
SetCount(1);
if (SortRqd())
{
Sort();
FixIOTags();
}
return FlwNode::ValidateData(VDB);
}
//--------------------------------------------------------------------------
flag CActuator::PreStartCheck()
{
for (int i=0; i<3; i++)
m_StateLine[i] = "";
m_StateLine[0] = "OK";
if (bOn)
{
bAboutToStart = 1;
}
return FlwNode::PreStartCheck();
}
//--------------------------------------------------------------------------
bool CActuator::TestXRefListActive() { return SetXRefListActive(!GetActiveHold() && bOn!=0); }
//---------------------------------------------------------------------------
int CActuator::UpdateXRefLists(CXRefBuildResults & Results)
{
if (1)//bOn)
{
FnMngrClear();
int FunctNo = 0;
for (int i=0; i<m_DataBlk.GetSize(); i++)
{
CActuatorBlk * T = m_DataBlk[i];
int RetCode = T->m_OutputVar.UpdateXRef(T, 1, 0, FunctNo, this, -1, T->m_sTagOutput(), T->m_sIDOutput(),"Actuator:Output", Results);
T->m_bValid = (RetCode==BXR_OK);
int RetCode1 = T->m_InputVar.UpdateXRef(T, 0, 1, FunctNo, this, CtrlIOId(i), T->m_sTagInput(), T->m_sIDInput(), "Actuator:Input", Results);
}
FnMngrTryUpdateXRefLists(Results);
}
return Results.m_nMissing;
}
//--------------------------------------------------------------------------
void CActuator::UnlinkAllXRefs()
{
FnMngrClear();
FnMngrTryUnlinkAllXRefs();
for (int i=0; i<m_DataBlk.GetSize(); i++)
{
CActuatorBlk * p = m_DataBlk[i];
p->m_OutputVar.UnlinkXRefs();
p->m_InputVar.UnlinkXRefs();
}
CNodeXRefMngr::UnlinkAllXRefs();
};
//--------------------------------------------------------------------------
void CActuator::EvalCtrlStrategy(eScdCtrlTasks Tasks)
{
if (XRefListActive() && ICGetTimeInc() > 0.0)
{
//for (int i=0; i<NoCIOs(); i++)
// {
// int ac=IOId_Self(i);
// m_DataBlk[ac]->m_dReqdValue=CIO_Value(i);
// }
//solve pgm functions...
if (FnMngrPresent())
{
CGExecContext ECtx(this);
ECtx.dIC_Time = ICGetTime();
ECtx.dIC_dTime = ICGetTimeInc();
ECtx.OnStart = bAboutToStart;
ECtx.m_HoldNearXRefGet=true;
ECtx.m_HoldNearXRefSet=true;
FnMngr().Execute(ECtx);
bAboutToStart = 0;
if (ECtx.DoXStop)
{
LogError(Tag(), 0, "SysCAD stopped by function");
ExecObj()->XStop();
}
if (ECtx.DoXIdle)
{
LogError(Tag(), 0, "SysCAD paused by function");
ExecObj()->XIdle();
}
}
//solve FlowStats...
for (int i=0; i<m_DataBlk.GetSize(); i++)
{
CActuatorBlk * T = m_DataBlk[i];
if (T->m_bValid)
{
//if (T->m_OutputVar.bIsFunct)
// {
// T->m_dOutputValue = T->m_OutputVar.pFunctVar->getD();
// }
//else
// {
// CXRefItem& Meas = (T->m_OutputVar.bIsNear ? NearGCXRefs[T->m_OutputVar.iXRefIndex] : FarGCXRefs[T->m_OutputVar.iXRefIndex]);
// T->m_dOutputValue = Cnvs[Meas.iCnvIndex]->Human(Meas.dVal, Meas.sCnv());
// }
T->m_InputVar.GetValue(T->m_dReqdValue);
T->ExecIns(ICGetTimeInc());
//if (T->m_OutputVar.bIsFunct)
// {
// T->m_dOutputValue = T->m_OutputVar.pFunctVar->getD();
// }
//else
// {
T->m_OutputVar.PutValue(T->m_dOutputValue);
// }
int xxx=0;
}
}
SetNearXRefValues();
//for (i=0; i<m_NearXRefs.GetSize(); i++)
// m_NearXRefs[i]->SetNearXRefValue();
}
}
//--------------------------------------------------------------------------
void CActuator::SetState(eScdMdlStateActs RqdState)
{
int i;
FlwNode::SetState(RqdState);
switch (RqdState)
{
case MSA_PBInit :
case MSA_ZeroFlows:
case MSA_Empty :
for (i=0; i<m_DataBlk.GetSize(); i++)
{
CActuatorBlk * T = m_DataBlk[i];
T->m_Flt.m_dPrevValue=T->m_dValue;
}
break;
case MSA_PreSet :
break;
case MSA_DynStatsRunInit:
break;
default:
break;
}
}
//--------------------------------------------------------------------------
void CActuator::EvalDiscrete()
{
}
//--------------------------------------------------------------------------
int CActuator::ChangeTag(pchar pOldTag, pchar pNewTag)
{
BOOL DidChange = FALSE;
for (int i=0; i<m_DataBlk.GetSize(); i++)
{
if (m_DataBlk[i]->m_OutputVar.DoChangeTag(pOldTag, pNewTag))
DidChange = TRUE;
}
if (DidChange)
{
PreStartCheck();
bAboutToStart = 0;
}
return FlwNode::ChangeTag(pOldTag, pNewTag);
}
//--------------------------------------------------------------------------
int CActuator::DeleteTag(pchar pDelTag)
{
BOOL FoundOne = FALSE;
for (int i=0; i<m_DataBlk.GetSize(); i++)
{
if (m_DataBlk[i]->m_OutputVar.ContainsTag(pDelTag))
FoundOne = TRUE;
}
if (FoundOne)
{
LogNote(Tag(), 0, "Delete tag '%s' affects Actuater model '%s'.", pDelTag, Tag());
PreStartCheck();
bAboutToStart = 0;
}
return FlwNode::DeleteTag(pDelTag);
}
//--------------------------------------------------------------------------
dword CActuator::ModelStatus()
{
dword Status=FlwNode::ModelStatus();
Status|=bOn ? FNS_On : FNS_Off;
return Status;
}
//--------------------------------------------------------------------------
flag CActuator::CIStrng(int No, pchar & pS)
{
// NB check CBCount is large enough.
switch (No-CBContext())
{
case 1: pS="E\t?????????"; return 1;
default:
return FlwNode::CIStrng(No, pS);
}
}
//==========================================================================
#endif | [
"[email protected]",
"[email protected]",
"[email protected]"
]
| [
[
[
1,
300
],
[
303,
323
],
[
326,
337
],
[
340,
432
],
[
435,
458
],
[
460,
460
],
[
466,
577
],
[
579,
584
],
[
586,
610
],
[
612,
773
],
[
775,
814
],
[
816,
816
],
[
818,
832
],
[
835,
930
],
[
932,
949
],
[
951,
977
]
],
[
[
301,
302
]
],
[
[
324,
325
],
[
338,
339
],
[
433,
434
],
[
459,
459
],
[
461,
465
],
[
578,
578
],
[
585,
585
],
[
611,
611
],
[
774,
774
],
[
815,
815
],
[
817,
817
],
[
833,
834
],
[
931,
931
],
[
950,
950
]
]
]
|
68a71764aeaf7c682448000462c056a73f4834cc | 465f130736402a22233b0148c1bd0fe7ab638e92 | /电路资料/磁场传感器/KMZ52/电子指南针芯片kmz52专用上位机输出程序/Compass1Doc.h | 59e09d7984b9b864463e855dfe5c6236de63af9c | []
| no_license | gilamada/minigpslog | 3a59cf4ea0e67463e006a655901ccac46994c60c | 342e311053ee5a43002a3f2968a0f0bd5ae49c90 | refs/heads/master | 2021-01-10T11:21:59.487362 | 2010-12-05T16:20:41 | 2010-12-05T16:20:41 | 36,965,174 | 1 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,497 | h | // Compass1Doc.h : interface of the CCompass1Doc class
//
/////////////////////////////////////////////////////////////////////////////
#if !defined(AFX_COMPASS1DOC_H__7F290CE8_9BA4_42FD_A6E5_946867B0700D__INCLUDED_)
#define AFX_COMPASS1DOC_H__7F290CE8_9BA4_42FD_A6E5_946867B0700D__INCLUDED_
#if _MSC_VER > 1000
#pragma once
#endif // _MSC_VER > 1000
class CCompass1Doc : public CDocument
{
protected: // create from serialization only
CCompass1Doc();
DECLARE_DYNCREATE(CCompass1Doc)
// Attributes
public:
// Operations
public:
// Overrides
// ClassWizard generated virtual function overrides
//{{AFX_VIRTUAL(CCompass1Doc)
public:
virtual BOOL OnNewDocument();
virtual void Serialize(CArchive& ar);
//}}AFX_VIRTUAL
// Implementation
public:
virtual ~CCompass1Doc();
#ifdef _DEBUG
virtual void AssertValid() const;
virtual void Dump(CDumpContext& dc) const;
#endif
protected:
// Generated message map functions
protected:
//{{AFX_MSG(CCompass1Doc)
// NOTE - the ClassWizard will add and remove member functions here.
// DO NOT EDIT what you see in these blocks of generated code !
//}}AFX_MSG
DECLARE_MESSAGE_MAP()
};
/////////////////////////////////////////////////////////////////////////////
//{{AFX_INSERT_LOCATION}}
// Microsoft Visual C++ will insert additional declarations immediately before the previous line.
#endif // !defined(AFX_COMPASS1DOC_H__7F290CE8_9BA4_42FD_A6E5_946867B0700D__INCLUDED_)
| [
"[email protected]"
]
| [
[
[
1,
57
]
]
]
|
03f1a23d6d6c61dbd065ff2781daa22d2ea6880a | e1d76663bb020dc27abb53c8f8bb979b4738373f | /source/support/library/stdio.cc | e9c2478159afcdd1c9ec4acfd02212c9325357cc | []
| no_license | fanopi/autoFloderSync | 97e29f9aa24bc8bf78aa8325996e176572f46f8a | 5232e01f43c9cc31df349a8b474c5d35a1e92ac5 | refs/heads/master | 2020-06-03T15:28:13.583695 | 2011-09-19T13:52:25 | 2011-09-19T13:52:25 | 2,338,869 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 79 | cc | /*
* stdio.cc
*
* Created on: 2011-4-27
* Author: FanOpi
*/
| [
"[email protected]"
]
| [
[
[
1,
7
]
]
]
|
380091d8b52e2e22a120fcb285a902dc4193430a | 7b4c786d4258ce4421b1e7bcca9011d4eeb50083 | /_统计专用/C++Primer中文版(第4版)/第一次-代码集合-20090414/第十八章 特殊工具与技术/20090406-Vector-b.hpp | 40ba177cdd0482a2a27b8601124e4c83764f81db | []
| no_license | lzq123218/guoyishi-works | dbfa42a3e2d3bd4a984a5681e4335814657551ef | 4e78c8f2e902589c3f06387374024225f52e5a92 | refs/heads/master | 2021-12-04T11:11:32.639076 | 2011-05-30T14:12:43 | 2011-05-30T14:12:43 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 2,997 | hpp | #ifndef MYVECTOR_H
#define MYVECTOR_H
#include <memory>
#include <cstddef>
using namespace std;
template <class T>
class Vector {
public:
Vector(): elements(0), first_free(0), end(0) { }
void push_back(const T&);
void reserve(const size_t capa);
void resize(const size_t n);
void resize(const size_t n, const T& t);
T& operator[] (const size_t);
const T& operator[] (const size_t) const;
size_t size()
{ return first_free - elements; }
size_t capacity()
{ return end - elements; }
private:
static std::allocator<T> alloc;
void reallocate();
T* elements;
T* first_free;
T* end;
};
template <class T>
std::allocator<T> Vector<T>::alloc;
template <class T>
void Vector<T>::push_back(const T& t)
{
if (first_free == end)
reallocate();
new (first_free) T(t);
++first_free;
}
template <class T>
void Vector<T>::reallocate()
{
ptrdiff_t size = first_free - elements;
ptrdiff_t newcapacity = 2 * max(size, 1);
T* newelements = static_cast<T*>
(operator new[] (newcapacity * sizeof(T)));
uninitilized_copy(elements, first_free, newelements);
for (T *p = first_free; p != elements; /*empty*/)
(--p) -> ~T();
if (elements)
operator delete[] (elements);
elements = newelements;
first_free = elements + size;
end = elements + newcapacity;
}
template <class T>
void Vector<T>::reserve(const size_t capa)
{
size_t size = first_free - elements;
T* newelements = static_cast<T*>
(operator new[] (capa * sizeof (T)));
if (size <= capa)
uninitilized_copy(elements, first_free, newelements);
else
uninitilized_copy(elements, first_free, newelements);
for (T *p = first_free; p != elements; /*empty*/)
(--p) -> ~T();
if (elements)
operator delete[] (elements);
elements = newelements;
first_free = elements + min(size, capa);
end = elements + capa;
}
template <class T>
void Vector<T>::resize(const size_t n)
{
size_t size = first_free - elements;
size_t capacity = end - elements;
if (n > capacity) {
reallocate();
uninitilized_fill(elements + size, elements + n, T());
} else if (n > size)
uninitilized_fill(elements + size, elements + n, T());
else
for (T *p = first_free; p != elements + n; /*empty*/)
(--p) -> ~T();
first_free = elements + n;
}
template <class T>
void Vector<T>::resize(const size_t n, const T& t)
{
size_t size = first_free - elements;
size_t capacity = end - elements;
if (n > capacity) {
reallocate();
uninitilized_fill(elements + size, elements + n, t);
} else if (n > size)
uninitilized_fill(elements + size, elements + n, t);
else
for (T *p = first_free; p != elements + n; /*empty*/)
(--p) -> ~T();
first_free = elements + n;
}
template <class T>
T& Vector<T>::operator[] (const size_t index)
{
return elements[index];
}
template <class T>
const T& Vector<T>::operator[] (const size_t index) const
{
return elements[index];
}
#endif
| [
"baicaibang@70501136-4834-11de-8855-c187e5f49513"
]
| [
[
[
1,
138
]
]
]
|
242a0a9eb7fa7e2bc3c9f5274de19a3b13786a7d | b8ac0bb1d1731d074b7a3cbebccc283529b750d4 | /Code/controllers/RecollectionBenchmark/robotapi/webts/WebotsDeviceTag.h | bec46a1faaacd7e30be99604eedac4370502a21a | []
| no_license | dh-04/tpf-robotica | 5efbac38d59fda0271ac4639ea7b3b4129c28d82 | 10a7f4113d5a38dc0568996edebba91f672786e9 | refs/heads/master | 2022-12-10T18:19:22.428435 | 2010-11-05T02:42:29 | 2010-11-05T02:42:29 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 497 | h | #ifndef robotapi_webts_WebotsDeviceTag_h
#define robotapi_webts_WebotsDeviceTag_h
#include <robotapi/IWbDeviceTag.h>
#include <webots/Device.hpp>
namespace robotapi {
namespace webts {
class WebotsDeviceTag : virtual public robotapi::IWbDeviceTag {
public:
int dtag;
WebotsDeviceTag(int tag);
WebotsDeviceTag(WbDeviceTag tag);
};
} /* End of namespace robotapi::webts */
} /* End of namespace robotapi */
#endif // robotapi_webts_WebotsDeviceTag_h
| [
"guicamest@d69ea68a-f96b-11de-8cdf-e97ad7d0f28a"
]
| [
[
[
1,
24
]
]
]
|
f5d7d6e2b50a463d4c9ab9a835006b050a6ad88a | 7b379862f58f587d9327db829ae4c6493b745bb1 | /JuceLibraryCode/modules/juce_gui_basics/widgets/juce_ToolbarItemPalette.cpp | 7bed7a2c6fc909b83fd3f7295525142e1d1504e3 | []
| no_license | owenvallis/Nomestate | 75e844e8ab68933d481640c12019f0d734c62065 | 7fe7c06c2893421a3c77b5180e5f27ab61dd0ffd | refs/heads/master | 2021-01-19T07:35:14.301832 | 2011-12-28T07:42:50 | 2011-12-28T07:42:50 | 2,950,072 | 2 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 3,671 | cpp | /*
==============================================================================
This file is part of the JUCE library - "Jules' Utility Class Extensions"
Copyright 2004-11 by Raw Material Software Ltd.
------------------------------------------------------------------------------
JUCE can be redistributed and/or modified under the terms of the GNU General
Public License (Version 2), as published by the Free Software Foundation.
A copy of the license is included in the JUCE distribution, or can be found
online at www.gnu.org/licenses.
JUCE is distributed in the hope that it will be useful, but WITHOUT ANY
WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR
A PARTICULAR PURPOSE. See the GNU General Public License for more details.
------------------------------------------------------------------------------
To release a closed-source product which uses JUCE, commercial licenses are
available: visit www.rawmaterialsoftware.com/juce for more information.
==============================================================================
*/
BEGIN_JUCE_NAMESPACE
//==============================================================================
ToolbarItemPalette::ToolbarItemPalette (ToolbarItemFactory& factory_,
Toolbar* const toolbar_)
: factory (factory_),
toolbar (toolbar_)
{
Component* const itemHolder = new Component();
viewport.setViewedComponent (itemHolder);
Array <int> allIds;
factory.getAllToolbarItemIds (allIds);
for (int i = 0; i < allIds.size(); ++i)
addComponent (allIds.getUnchecked (i), -1);
addAndMakeVisible (&viewport);
}
ToolbarItemPalette::~ToolbarItemPalette()
{
}
//==============================================================================
void ToolbarItemPalette::addComponent (const int itemId, const int index)
{
ToolbarItemComponent* const tc = Toolbar::createItem (factory, itemId);
jassert (tc != nullptr);
if (tc != nullptr)
{
items.insert (index, tc);
viewport.getViewedComponent()->addAndMakeVisible (tc, index);
tc->setEditingMode (ToolbarItemComponent::editableOnPalette);
}
}
void ToolbarItemPalette::replaceComponent (ToolbarItemComponent* const comp)
{
const int index = items.indexOf (comp);
jassert (index >= 0);
items.removeObject (comp, false);
addComponent (comp->getItemId(), index);
resized();
}
void ToolbarItemPalette::resized()
{
viewport.setBoundsInset (BorderSize<int> (1));
Component* const itemHolder = viewport.getViewedComponent();
const int indent = 8;
const int preferredWidth = viewport.getWidth() - viewport.getScrollBarThickness() - indent;
const int height = toolbar->getThickness();
int x = indent;
int y = indent;
int maxX = 0;
for (int i = 0; i < items.size(); ++i)
{
ToolbarItemComponent* const tc = items.getUnchecked(i);
tc->setStyle (toolbar->getStyle());
int preferredSize = 1, minSize = 1, maxSize = 1;
if (tc->getToolbarItemSizes (height, false, preferredSize, minSize, maxSize))
{
if (x + preferredSize > preferredWidth && x > indent)
{
x = indent;
y += height;
}
tc->setBounds (x, y, preferredSize, height);
x += preferredSize + 8;
maxX = jmax (maxX, x);
}
}
itemHolder->setSize (maxX, y + height + 8);
}
END_JUCE_NAMESPACE
| [
"ow3nskip"
]
| [
[
[
1,
114
]
]
]
|
09933933c884e4fc2ed4583c6b208af0ef593055 | 29c5bc6757634a26ac5103f87ed068292e418d74 | /src/hook/out_buf_nop.cpp | dc1b207b07d7ca78a6afd2609592cee62680ceac | []
| no_license | drivehappy/tlapi | d10bb75f47773e381e3ba59206ff50889de7e66a | 56607a0243bd9d2f0d6fb853cddc4fce3e7e0eb9 | refs/heads/master | 2021-03-19T07:10:57.343889 | 2011-04-18T22:58:29 | 2011-04-18T22:58:29 | 32,191,364 | 5 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 459 | cpp | #include "out_buf_nop.h"
out_buf_nop::out_buf_nop()
: size(0), chksum(0)
{
}
void out_buf_nop::puc(uint8_t x)
{
chksum+=x;
size++;
}
void out_buf_nop::pus(uint16_t x)
{
chksum+=x;
size+=2;
}
void out_buf_nop::pui(uint32_t x)
{
chksum+=x;
size+=4;
}
uint32_t out_buf_nop::addr()
{
return 0x10000000 + size;
}
bool out_buf_nop::operator !=(const out_buf_nop &n)
{
return size!=n.size||chksum!=n.chksum;
}
| [
"drivehappy@53ea644a-42e2-1498-a4e7-6aa81ae25522"
]
| [
[
[
1,
34
]
]
]
|
9d22b917d47b74e8cc53e874ec5d7aa1f1538b0f | 7b379862f58f587d9327db829ae4c6493b745bb1 | /JuceLibraryCode/modules/juce_events/messages/juce_Message.h | e39c53a8e6aad3405819394e39cd0dd5e409134b | []
| no_license | owenvallis/Nomestate | 75e844e8ab68933d481640c12019f0d734c62065 | 7fe7c06c2893421a3c77b5180e5f27ab61dd0ffd | refs/heads/master | 2021-01-19T07:35:14.301832 | 2011-12-28T07:42:50 | 2011-12-28T07:42:50 | 2,950,072 | 2 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 2,701 | h | /*
==============================================================================
This file is part of the JUCE library - "Jules' Utility Class Extensions"
Copyright 2004-11 by Raw Material Software Ltd.
------------------------------------------------------------------------------
JUCE can be redistributed and/or modified under the terms of the GNU General
Public License (Version 2), as published by the Free Software Foundation.
A copy of the license is included in the JUCE distribution, or can be found
online at www.gnu.org/licenses.
JUCE is distributed in the hope that it will be useful, but WITHOUT ANY
WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR
A PARTICULAR PURPOSE. See the GNU General Public License for more details.
------------------------------------------------------------------------------
To release a closed-source product which uses JUCE, commercial licenses are
available: visit www.rawmaterialsoftware.com/juce for more information.
==============================================================================
*/
#ifndef __JUCE_MESSAGE_JUCEHEADER__
#define __JUCE_MESSAGE_JUCEHEADER__
class MessageListener;
class MessageManager;
//==============================================================================
/** The base class for objects that can be delivered to a MessageListener.
The simplest Message object contains a few integer and pointer parameters
that the user can set, and this is enough for a lot of purposes. For passing more
complex data, subclasses of Message can also be used.
@see MessageListener, MessageManager, ActionListener, ChangeListener
*/
class JUCE_API Message : public ReferenceCountedObject
{
public:
//==============================================================================
/** Creates an uninitialised message.
The class's variables will also be left uninitialised.
*/
Message() noexcept;
/** Destructor. */
virtual ~Message();
/** A typedef for pointers to messages. */
typedef ReferenceCountedObjectPtr <Message> Ptr;
//==============================================================================
private:
friend class MessageListener;
friend class MessageManager;
MessageListener* messageRecipient;
// Avoid the leak-detector because for plugins, the host can unload our DLL with undelivered
// messages still in the system event queue. These aren't harmful, but can cause annoying assertions.
JUCE_DECLARE_NON_COPYABLE (Message);
};
#endif // __JUCE_MESSAGE_JUCEHEADER__
| [
"ow3nskip"
]
| [
[
[
1,
70
]
]
]
|
9a218d2694d3d8a4d8098acfe1d474f58665f98d | 8aa65aef3daa1a52966b287ffa33a3155e48cc84 | /Source/3rdparty/Bullet/src/BulletCollision/CollisionShapes/btTriangleIndexVertexArray.cpp | 1e2b11e9776eddb89537950c6604473f00b436b8 | [
"Zlib",
"LicenseRef-scancode-unknown-license-reference"
]
| permissive | jitrc/p3d | da2e63ef4c52ccb70023d64316cbd473f3bd77d9 | b9943c5ee533ddc3a5afa6b92bad15a864e40e1e | refs/heads/master | 2020-04-15T09:09:16.192788 | 2009-06-29T04:45:02 | 2009-06-29T04:45:02 | 37,063,569 | 1 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 3,565 | cpp | /*
Bullet Continuous Collision Detection and Physics Library
Copyright (c) 2003-2006 Erwin Coumans http://continuousphysics.com/Bullet/
This software is provided 'as-is', without any express or implied warranty.
In no event will the authors be held liable for any damages arising from the use of this software.
Permission is granted to anyone to use this software for any purpose,
including commercial applications, and to alter it and redistribute it freely,
subject to the following restrictions:
1. The origin of this software must not be misrepresented; you must not claim that you wrote the original software. If you use this software in a product, an acknowledgment in the product documentation would be appreciated but is not required.
2. Altered source versions must be plainly marked as such, and must not be misrepresented as being the original software.
3. This notice may not be removed or altered from any source distribution.
*/
#include "btTriangleIndexVertexArray.h"
btTriangleIndexVertexArray::btTriangleIndexVertexArray(int numTriangles,int* triangleIndexBase,int triangleIndexStride,int numVertices,btScalar* vertexBase,int vertexStride)
: m_hasAabb(0)
{
btIndexedMesh mesh;
mesh.m_numTriangles = numTriangles;
mesh.m_triangleIndexBase = (const unsigned char *)triangleIndexBase;
mesh.m_triangleIndexStride = triangleIndexStride;
mesh.m_numVertices = numVertices;
mesh.m_vertexBase = (const unsigned char *)vertexBase;
mesh.m_vertexStride = vertexStride;
addIndexedMesh(mesh);
}
btTriangleIndexVertexArray::~btTriangleIndexVertexArray()
{
}
void btTriangleIndexVertexArray::getLockedVertexIndexBase(unsigned char **vertexbase, int& numverts,PHY_ScalarType& type, int& vertexStride,unsigned char **indexbase,int & indexstride,int& numfaces,PHY_ScalarType& indicestype,int subpart)
{
btAssert(subpart< getNumSubParts() );
btIndexedMesh& mesh = m_indexedMeshes[subpart];
numverts = mesh.m_numVertices;
(*vertexbase) = (unsigned char *) mesh.m_vertexBase;
#ifdef BT_USE_DOUBLE_PRECISION
type = PHY_DOUBLE;
#else
type = PHY_FLOAT;
#endif
vertexStride = mesh.m_vertexStride;
numfaces = mesh.m_numTriangles;
(*indexbase) = (unsigned char *)mesh.m_triangleIndexBase;
indexstride = mesh.m_triangleIndexStride;
indicestype = mesh.m_indexType;
}
void btTriangleIndexVertexArray::getLockedReadOnlyVertexIndexBase(const unsigned char **vertexbase, int& numverts,PHY_ScalarType& type, int& vertexStride,const unsigned char **indexbase,int & indexstride,int& numfaces,PHY_ScalarType& indicestype,int subpart) const
{
const btIndexedMesh& mesh = m_indexedMeshes[subpart];
numverts = mesh.m_numVertices;
(*vertexbase) = (const unsigned char *)mesh.m_vertexBase;
#ifdef BT_USE_DOUBLE_PRECISION
type = PHY_DOUBLE;
#else
type = PHY_FLOAT;
#endif
vertexStride = mesh.m_vertexStride;
numfaces = mesh.m_numTriangles;
(*indexbase) = (const unsigned char *)mesh.m_triangleIndexBase;
indexstride = mesh.m_triangleIndexStride;
indicestype = mesh.m_indexType;
}
bool btTriangleIndexVertexArray::hasPremadeAabb() const
{
return (m_hasAabb == 1);
}
void btTriangleIndexVertexArray::setPremadeAabb(const btVector3& aabbMin, const btVector3& aabbMax ) const
{
m_aabbMin = aabbMin;
m_aabbMax = aabbMax;
m_hasAabb = 1; // this is intentionally an int see notes in header
}
void btTriangleIndexVertexArray::getPremadeAabb(btVector3* aabbMin, btVector3* aabbMax ) const
{
*aabbMin = m_aabbMin;
*aabbMax = m_aabbMax;
}
| [
"vadun87@6320d0be-1f75-11de-b650-e715bd6d7cf1"
]
| [
[
[
1,
99
]
]
]
|
db86bed0e1db278d864d84e9d7fe9769a78fa19f | 6188f1aaaf5508e046cde6da16b56feb3d5914bc | /branches/CamFighter 1.0/Models/lib3dx/xElementCalc.cpp | f28699e3e08556bb50a4f6ef22e244e6a419c061 | []
| no_license | dogtwelve/fighter3d | 7bb099f0dc396e8224c573743ee28c54cdd3d5a2 | c073194989bc1589e4aa665714c5511f001e6400 | refs/heads/master | 2021-04-30T15:58:11.300681 | 2011-06-27T18:51:30 | 2011-06-27T18:51:30 | 33,675,635 | 1 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 22,825 | cpp | #include "xElement.h"
#include <vector>
////////////////////// Normals
struct smoothVert {
xDWORD smooth; // smoothing group
xVector3 normal; // normal for this sgroup
xWORD count; // count for normal calculation
xVector3 mnormal; // merged normal for this sgroup
xWORD mcount; // merged count for normal calculation
smoothVert *mergedWith;
xDWORD vertexId; // new vertex id
xFace *flatFace; // used when smooth == 0
};
void xElement :: CalculateSmoothVertices ()
{
size_t stride = this->GetVertexStride();
xBYTE *verticesIn = (xBYTE*) this->L_vertices;
this->renderData.L_face_normals = new xVector3[this->I_faces];
xVector3 *faceNormal = this->renderData.L_face_normals;
//// assign smoothing groups to vertices
std::vector<smoothVert>::iterator iterF, iterE, iterF2, iterE2;
std::vector<std::vector<smoothVert> > vertices; // vertex_id->(smooth, normal)[]
vertices.resize(this->I_vertices);
xDWORD *smooth = this->L_smooth;
xFace *faceIn = this->L_faces;
for (int fP=this->I_faces; fP; --fP, ++smooth, ++faceIn, ++faceNormal)
{
xVector3 *v0 = (xVector3*)(verticesIn + (*faceIn)[0]*stride);
xVector3 *v1 = (xVector3*)(verticesIn + (*faceIn)[1]*stride);
xVector3 *v2 = (xVector3*)(verticesIn + (*faceIn)[2]*stride);
*faceNormal = xVector3::CrossProduct(*v1-*v0, *v2-*v0).normalize();
for (int i=0; i<3; ++i)
{
int idx = (*faceIn)[i];
bool found = false;
xVector3 vnormal = *faceNormal;
xWORD vcount = 1;
if (*smooth)
{
iterE = vertices[idx].end();
for (iterF = vertices[idx].begin(); iterF != iterE; ++iterF)
if (iterF->smooth & *smooth)
{
if (iterF->smooth == *smooth)
{
iterF->normal += *faceNormal;
++(iterF->count);
found = true;
}
else
{
vnormal += iterF->normal;
vcount += iterF->count;
}
iterF->mnormal += *faceNormal;
++(iterF->mcount);
}
if (found) continue;
}
vertices[idx].resize(vertices[idx].size()+1);
iterF = vertices[idx].end()-1;
iterF->smooth = *smooth;
iterF->count = 1;
iterF->normal = *faceNormal;
iterF->mcount = vcount;
iterF->mnormal = vnormal;
iterF->flatFace = faceIn;
iterF->mergedWith = NULL;
}
}
//// smooth normals for original vertex duplicates
xDWORD verticesC = this->I_vertices;
std::vector<std::vector<smoothVert> >::iterator vertF = vertices.begin(), vertF2;
std::vector<std::vector<smoothVert> >::iterator vertE = vertices.end();
xBYTE *xvertI = verticesIn, *xvertI2;
for (int i=0; vertF != vertE; ++vertF, xvertI += stride, ++i)
{
if (!vertF->size()) continue;
xVector3 *v1 = (xVector3*)xvertI;
xvertI2 = xvertI+stride;
int j = i+1;
for (vertF2 = vertF+1; vertF2 != vertE; ++vertF2, xvertI2 += stride, ++j)
{
xVector3 *v2 = (xVector3*)xvertI2;
if (!v1->nearlyEqual(*v2)) continue;
iterE = vertF->end();
iterE2 = vertF2->end();
for (iterF = vertF->begin(); iterF != iterE; ++iterF)
for (iterF2 = vertF2->begin(); iterF2 != iterE2; ++iterF2)
if (iterF->smooth & iterF2->smooth)
{
iterF->mnormal += iterF2->normal;
iterF->mcount += iterF2->count;
iterF2->mnormal += iterF->normal;
iterF2->mcount += iterF->count;
}
}
}
//// merge smoothing groups, where possible
for (vertF = vertices.begin(); vertF != vertE; ++vertF)
{
if (!vertF->size()) continue;
iterE = vertF->end();
for (iterF = vertF->begin(); iterF != iterE; ++iterF)
if (!iterF->mergedWith)
{
xDWORD msmooth = iterF->smooth;
for (iterF2 = iterF+1; iterF2 != iterE; ++iterF2)
if (!iterF2->mergedWith && (msmooth & iterF2->smooth) && (iterF->count == iterF2->count))
{
msmooth |= iterF2->smooth;
iterF2->mergedWith = &*iterF;
}
}
}
//// normalize normals and assign ids for new vertex duplicates
for (vertF = vertices.begin(); vertF != vertE; ++vertF)
{
if (!vertF->size()) continue;
bool used = false;
iterE = vertF->end();
for (iterF = vertF->begin(); iterF != iterE; ++iterF)
if (!iterF->mergedWith)
{
iterF->mnormal /= (float)iterF->mcount;
iterF->mnormal.normalize();
if (!used)
{
iterF->vertexId = 0; // no change
used = true;
continue;
}
iterF->vertexId = verticesC++;
}
else
iterF->vertexId = iterF->mergedWith->vertexId;
}
this->renderData.I_vertices = verticesC;
if (verticesC == this->I_vertices)
{
this->renderData.L_vertices = this->L_vertices;
this->renderData.L_faces = this->L_faces;
}
else
{
this->renderData.L_vertices = (xVertex*) new xBYTE[stride*verticesC];
memcpy(this->renderData.L_vertices, this->L_vertices, stride*this->I_vertices);
this->renderData.L_faces = new xFace[this->I_faces];
//// fill and correct faces
smooth = this->L_smooth;
faceIn = this->L_faces;
xFace *faceOut = this->renderData.L_faces;
for (int fP=this->I_faces; fP; --fP, ++smooth, ++faceIn, ++faceOut)
for (int i=0; i<3; ++i)
{
int idx = (*faceOut)[i] = (*faceIn)[i];
iterE = vertices[idx].end();
for (iterF = vertices[idx].begin(); iterF != iterE; ++iterF)
if (iterF->smooth == *smooth && (*smooth || iterF->flatFace == faceIn))
{
if (iterF->vertexId) idx = iterF->vertexId;
(*faceOut)[i] = idx;
break;
}
}
}
this->renderData.L_normals = new xVector3[verticesC];
//// duplicate vertices and fill normals
xBYTE *verticesOut = ((xBYTE*) this->renderData.L_vertices) + stride*this->I_vertices;
xVector3 *L_normals = this->renderData.L_normals;
xVector3 *normalP2 = this->renderData.L_normals + this->I_vertices;
for (vertF = vertices.begin(); vertF != vertE; ++vertF, verticesIn += stride, ++L_normals)
{
if (!vertF->size()) continue;
iterE = vertF->end();
for (iterF = vertF->begin(); iterF != iterE; ++iterF)
if (!iterF->mergedWith)
if (iterF->vertexId)
{
memcpy(verticesOut, verticesIn, stride);
verticesOut += stride;
*(normalP2++) = iterF->mnormal;
}
else
*L_normals = iterF->mnormal;
}
}
////////////////////// Shadow Edges
xMaterial *xFaceGetMaterial(const xElement *elem, int faceIdx)
{
xFaceList *faceL = elem->L_faceLists;
for (int i=elem->I_faceLists; i; --i, ++faceL)
if (faceIdx - faceL->I_offset < faceL->I_count)
return faceL->Material;
return NULL;
}
bool xFaceTransparent(const xElement *elem, int faceIdx)
{
xMaterial *mat = xFaceGetMaterial(elem, faceIdx);
return mat && mat->transparency > 0.f;
}
void xFaceTransparentOr2Sided(const xElement *elem, int faceIdx, bool &outTransp, bool &outTwoSide)
{
xMaterial *mat = xFaceGetMaterial(elem, faceIdx);
outTransp = mat && mat->transparency > 0.f;
outTwoSide = mat && mat->two_sided;
}
void xElement :: FillShadowEdges ()
{
xWORD edgesC = 3 * (this->I_faces);
this->L_edges = new xEdge[edgesC << 1];
bool *flags = new bool[this->I_faces*3];
memset(flags, 0, this->I_faces*3);
xFace *iterF1 = this->L_faces, *iterF2;
bool *iterUsed1 = flags, *iterUsed2;
xEdge *iterE = this->L_edges;
size_t stride = this->FL_skeletized
? this->FL_textured
? sizeof (xVertexTexSkel)
: sizeof (xVertexSkel)
: this->FL_textured
? sizeof (xVertexTex)
: sizeof (xVertex);
xBYTE *verticesIn = (xBYTE*) this->L_vertices;
xDWORD cnt = 0;
for (int i = 0; i < this->I_faces; ++i, ++iterF1, iterUsed1 += 3)
{
bool transp1;
bool twoSide1;
xFaceTransparentOr2Sided(this, i, transp1, twoSide1);
if (transp1) continue;
for (int e1 = 0; e1 < 3; ++e1)
if (!iterUsed1[e1])
{
++cnt;
iterE->ID_vert_1 = (*iterF1)[e1];
iterE->ID_vert_2 = (*iterF1)[(e1+1)%3];
iterE->ID_face_1 = i;
iterE->ID_face_2 = xWORD_MAX;
iterUsed1[e1] = true;
xVector3 *vc1a = (xVector3 *)(verticesIn + stride* iterE->ID_vert_1);
xVector3 *vc1b = (xVector3 *)(verticesIn + stride* iterE->ID_vert_2);
iterF2 = iterF1 + 1;
iterUsed2 = iterUsed1 + 3;
bool found = false;
for (int j = i+1; j < this->I_faces && !found; ++j, ++iterF2, iterUsed2+=3)
{
bool transp2;
bool twoSide2;
xFaceTransparentOr2Sided(this, i, transp2, twoSide2);
if (transp2) continue;
for (int e2 = 0; e2 < 3 && !found; ++e2)
if (!iterUsed2[e2] && !(twoSide1 ^ twoSide2))
{
xWORD v1 = (*iterF2)[e2];
xWORD v2 = (*iterF2)[(e2+1)%3];
xVector3 *vc2a = (xVector3 *)(verticesIn + stride*v1);
xVector3 *vc2b = (xVector3 *)(verticesIn + stride*v2);
//if ((vc1a->nearlyEqual(*vc2a) && vc1b->nearlyEqual(*vc2b)) ||
// (vc1a->nearlyEqual(*vc2b) && vc1b->nearlyEqual(*vc2a)) )
if ((*vc1a == *vc2a && *vc1b == *vc2b) ||
(*vc1a == *vc2b && *vc1b == *vc2a) )
{
iterE->ID_face_2 = j;
iterUsed2[e2] = true;
found = true;
--edgesC;
}
}
}
if (iterE->ID_face_2 == xWORD_MAX)
{
iterE->ID_face_2 = xWORD_MAX;
}
++iterE;
}
}
xEdge *tmp = this->L_edges;
this->I_edges = cnt;
this->L_edges = new xEdge[cnt];
memcpy(this->L_edges, tmp, cnt*sizeof(xEdge));
delete[] tmp;
}
#include "../../Math/Figures/xSphere.h"
#include "../../Math/Figures/xBoxO.h"
#include "../../Math/Figures/xMesh.h"
using namespace Math::Figures;
xBoxA xElement :: ReFillBVHNode(xBVHierarchy &BVH_node,
xMeshData &MeshData,
const xMatrix &MX_LocalToWorld)
{
xBoxA boxA;
if (BVH_node.I_items)
{
boxA.P_min.init(xFLOAT_HUGE_POSITIVE, xFLOAT_HUGE_POSITIVE, xFLOAT_HUGE_POSITIVE);
boxA.P_max.init(xFLOAT_HUGE_NEGATIVE, xFLOAT_HUGE_NEGATIVE, xFLOAT_HUGE_NEGATIVE);
xBoxA boxAc;
xBVHierarchy *BVH_kid = BVH_node.L_items;
for (int i = BVH_node.I_items; i; --i, ++BVH_kid)
{
boxAc = ReFillBVHNode(*BVH_kid, MeshData, MX_LocalToWorld);
if (boxAc.P_min.x < boxA.P_min.x) boxA.P_min.x = boxAc.P_min.x;
if (boxAc.P_min.y < boxA.P_min.y) boxA.P_min.y = boxAc.P_min.y;
if (boxAc.P_min.z < boxA.P_min.z) boxA.P_min.z = boxAc.P_min.z;
if (boxAc.P_max.x > boxA.P_max.x) boxA.P_max.x = boxAc.P_max.x;
if (boxAc.P_max.y > boxA.P_max.y) boxA.P_max.y = boxAc.P_max.y;
if (boxAc.P_max.z > boxA.P_max.z) boxA.P_max.z = boxAc.P_max.z;
}
xVector3 NW_extends = (boxA.P_max - boxA.P_min) * 0.5f;
xBoxO &boxO = *(xBoxO*) BVH_node.GetTransformed(MX_LocalToWorld);
boxO.P_center = boxA.P_min + NW_extends;
boxO.S_side = NW_extends.x;
boxO.S_front = NW_extends.y;
boxO.S_top = NW_extends.z;
}
else
{
xMesh &mesh = *(xMesh*) BVH_node.GetTransformed(MX_LocalToWorld);
boxA.P_max = boxA.P_min = MeshData.GetVertexTransf(mesh.L_VertexIndices[0]);
xDWORD *MV_iter = mesh.L_VertexIndices + 1;
for (xDWORD i = mesh.I_VertexIndices-1; i; --i, ++MV_iter)
{
xPoint3 &P_tmp = MeshData.GetVertexTransf(*MV_iter);
if (P_tmp.x < boxA.P_min.x) boxA.P_min.x = P_tmp.x;
else
if (P_tmp.x > boxA.P_max.x) boxA.P_max.x = P_tmp.x;
if (P_tmp.y < boxA.P_min.y) boxA.P_min.y = P_tmp.y;
else
if (P_tmp.y > boxA.P_max.y) boxA.P_max.y = P_tmp.y;
if (P_tmp.z < boxA.P_min.z) boxA.P_min.z = P_tmp.z;
else
if (P_tmp.z > boxA.P_max.z) boxA.P_max.z = P_tmp.z;
}
}
return boxA;
}
xBoxA xElement :: ReFillBVH ( xBVHierarchy *L_BVH, xMeshData *MeshData,
const xMatrix &MX_LocalToWorld )
{
xBVHierarchy &BVH_node = L_BVH[ID];
xMeshData &Mesh_node = MeshData[ID];
xBoxA boxA, boxAc;
boxA.P_min.init(xFLOAT_HUGE_POSITIVE, xFLOAT_HUGE_POSITIVE, xFLOAT_HUGE_POSITIVE);
boxA.P_max.init(xFLOAT_HUGE_NEGATIVE, xFLOAT_HUGE_NEGATIVE, xFLOAT_HUGE_NEGATIVE);
if (BVH_node.I_items)
{
xBVHierarchy *BVH_kid = BVH_node.L_items;
for (int i = boundingData.I_kids; i; --i, ++BVH_kid)
{
boxAc = ReFillBVHNode(*BVH_kid, Mesh_node, MX_LocalToWorld);
if (boxAc.P_min.x < boxA.P_min.x) boxA.P_min.x = boxAc.P_min.x;
if (boxAc.P_min.y < boxA.P_min.y) boxA.P_min.y = boxAc.P_min.y;
if (boxAc.P_min.z < boxA.P_min.z) boxA.P_min.z = boxAc.P_min.z;
if (boxAc.P_max.x > boxA.P_max.x) boxA.P_max.x = boxAc.P_max.x;
if (boxAc.P_max.y > boxA.P_max.y) boxA.P_max.y = boxAc.P_max.y;
if (boxAc.P_max.z > boxA.P_max.z) boxA.P_max.z = boxAc.P_max.z;
}
xVector3 NW_extends = (boxA.P_max - boxA.P_min) * 0.5f;
xBoxO &boxO = *(xBoxO*) BVH_node.GetTransformed(MX_LocalToWorld);
boxO.P_center = boxA.P_min + NW_extends;
boxO.S_side = NW_extends.x;
boxO.S_front = NW_extends.y;
boxO.S_top = NW_extends.z;
boxO.N_side.init(1.f, 0.f, 0.f);
boxO.N_front.init(0.f, 1.f, 0.f);
boxO.N_top.init(0.f, 0.f, 1.f);
}
xElement *elem = L_kids;
for (; elem; elem = elem->Next)
{
boxAc = elem->ReFillBVH( L_BVH, MeshData, MX_LocalToWorld );
if (boxAc.P_min.x < boxA.P_min.x) boxA.P_min.x = boxAc.P_min.x;
if (boxAc.P_min.y < boxA.P_min.y) boxA.P_min.y = boxAc.P_min.y;
if (boxAc.P_min.z < boxA.P_min.z) boxA.P_min.z = boxAc.P_min.z;
if (boxAc.P_max.x > boxA.P_max.x) boxA.P_max.x = boxAc.P_max.x;
if (boxAc.P_max.y > boxA.P_max.y) boxA.P_max.y = boxAc.P_max.y;
if (boxAc.P_max.z > boxA.P_max.z) boxA.P_max.z = boxAc.P_max.z;
}
return boxA;
}
xBoxA xElement :: FillBVHNode(xBoundingHierarchy &BH_node,
xBVHierarchy &BVH_node,
xMeshData &MeshData)
{
xBoxA boxA;
BVH_node.init(*new xBoxO());
if (BH_node.I_kids)
{
boxA.P_min.init(xFLOAT_HUGE_POSITIVE, xFLOAT_HUGE_POSITIVE, xFLOAT_HUGE_POSITIVE);
boxA.P_max.init(xFLOAT_HUGE_NEGATIVE, xFLOAT_HUGE_NEGATIVE, xFLOAT_HUGE_NEGATIVE);
BVH_node.I_items = BH_node.I_kids;
BVH_node.L_items = new xBVHierarchy[BVH_node.I_items];
xBoxA boxAc;
xBoundingHierarchy *BH_kid = BH_node.L_kids;
xBVHierarchy *BVH_kid = BVH_node.L_items;
for (int i = BH_node.I_kids; i; --i, ++BH_kid, ++BVH_kid)
{
boxAc = FillBVHNode(*BH_kid, *BVH_kid, MeshData);
if (boxAc.P_min.x < boxA.P_min.x) boxA.P_min.x = boxAc.P_min.x;
if (boxAc.P_min.y < boxA.P_min.y) boxA.P_min.y = boxAc.P_min.y;
if (boxAc.P_min.z < boxA.P_min.z) boxA.P_min.z = boxAc.P_min.z;
if (boxAc.P_max.x > boxA.P_max.x) boxA.P_max.x = boxAc.P_max.x;
if (boxAc.P_max.y > boxA.P_max.y) boxA.P_max.y = boxAc.P_max.y;
if (boxAc.P_max.z > boxA.P_max.z) boxA.P_max.z = boxAc.P_max.z;
}
}
else
{
BVH_node.I_items = 1;
BVH_node.L_items = new xBVHierarchy[1];
BVH_node.L_items[0].init(*new xMesh());
xMesh &mesh = *(xMesh*) BVH_node.L_items[0].Figure;
mesh.MeshData = &MeshData;
mesh.I_FaceIndices = BH_node.I_faces;
mesh.L_FaceIndices = new xDWORD[mesh.I_FaceIndices];
xDWORD *MF_iter = mesh.L_FaceIndices;
xFace **CF_iter = BH_node.L_faces;
for (xDWORD i = mesh.I_FaceIndices; i; --i, ++MF_iter, ++CF_iter)
*MF_iter = (*CF_iter - L_faces);// % MeshData->I_FaceStride;
boxA.P_max = boxA.P_min = MeshData.GetVertex(BH_node.L_vertices[0]);
mesh.I_VertexIndices = BH_node.I_vertices;
mesh.L_VertexIndices = new xDWORD[mesh.I_VertexIndices];
xDWORD *MV_iter = mesh.L_VertexIndices;
xWORD *CV_iter = BH_node.L_vertices;
for (xDWORD i = mesh.I_VertexIndices; i; --i, ++MV_iter, ++CV_iter)
{
xPoint3 &P_tmp = MeshData.GetVertex(*MV_iter = *CV_iter);
if (P_tmp.x < boxA.P_min.x) boxA.P_min.x = P_tmp.x;
else
if (P_tmp.x > boxA.P_max.x) boxA.P_max.x = P_tmp.x;
if (P_tmp.y < boxA.P_min.y) boxA.P_min.y = P_tmp.y;
else
if (P_tmp.y > boxA.P_max.y) boxA.P_max.y = P_tmp.y;
if (P_tmp.z < boxA.P_min.z) boxA.P_min.z = P_tmp.z;
else
if (P_tmp.z > boxA.P_max.z) boxA.P_max.z = P_tmp.z;
}
}
xVector3 NW_extends = (boxA.P_max - boxA.P_min) * 0.5f;
xBoxO &boxO = *(xBoxO*) BVH_node.Figure;
boxO.P_center = boxA.P_min + NW_extends;
boxO.S_side = NW_extends.x;
boxO.S_front = NW_extends.y;
boxO.S_top = NW_extends.z;
boxO.N_side.init(1.f, 0.f, 0.f);
boxO.N_front.init(0.f, 1.f, 0.f);
boxO.N_top.init(0.f, 0.f, 1.f);
return boxA;
}
xBoxA xElement :: FillBVH ( xBVHierarchy *L_BVH, xMeshData *MeshData )
{
xBVHierarchy &BVH_node = L_BVH[ID];
xMeshData &Mesh_node = MeshData[ID];
xBoxA boxA, boxAc;
boxA.P_min.init(xFLOAT_HUGE_POSITIVE, xFLOAT_HUGE_POSITIVE, xFLOAT_HUGE_POSITIVE);
boxA.P_max.init(xFLOAT_HUGE_NEGATIVE, xFLOAT_HUGE_NEGATIVE, xFLOAT_HUGE_NEGATIVE);
if (boundingData.I_kids)
{
BVH_node.init(*new xBoxO());
BVH_node.I_items = boundingData.I_kids;
BVH_node.L_items = new xBVHierarchy[BVH_node.I_items];
//xMeshData *MeshData = new xMeshData();
Mesh_node.ID = ID;
Mesh_node.I_FaceCount = I_faces;
Mesh_node.I_FaceStride = sizeof(xFace);
Mesh_node.L_FaceData = (xBYTE*) L_faces;
Mesh_node.I_VertexCount = I_vertices;
Mesh_node.I_VertexStride = GetVertexStride();
Mesh_node.L_VertexData = (xBYTE*) L_vertices;
Mesh_node.MX_MeshToLocal = MX_MeshToLocal;
if (FL_skeletized)
{
Mesh_node.L_BoneData = (xBYTE*) L_verticesS->bone;
Mesh_node.I_BoneStride = Mesh_node.I_VertexStride;
}
xBoundingHierarchy *CH_kid = boundingData.L_kids;
xBVHierarchy *BVH_kid = BVH_node.L_items;
for (int i = boundingData.I_kids; i; --i, ++CH_kid, ++BVH_kid)
{
boxAc = FillBVHNode(*CH_kid, *BVH_kid, Mesh_node);
if (boxAc.P_min.x < boxA.P_min.x) boxA.P_min.x = boxAc.P_min.x;
if (boxAc.P_min.y < boxA.P_min.y) boxA.P_min.y = boxAc.P_min.y;
if (boxAc.P_min.z < boxA.P_min.z) boxA.P_min.z = boxAc.P_min.z;
if (boxAc.P_max.x > boxA.P_max.x) boxA.P_max.x = boxAc.P_max.x;
if (boxAc.P_max.y > boxA.P_max.y) boxA.P_max.y = boxAc.P_max.y;
if (boxAc.P_max.z > boxA.P_max.z) boxA.P_max.z = boxAc.P_max.z;
}
xVector3 NW_extends = (boxA.P_max - boxA.P_min) * 0.5f;
xBoxO &boxO = *(xBoxO*) BVH_node.Figure;
boxO.P_center = boxA.P_min + NW_extends;
boxO.S_side = NW_extends.x;
boxO.S_front = NW_extends.y;
boxO.S_top = NW_extends.z;
boxO.N_side.init(1.f, 0.f, 0.f);
boxO.N_front.init(0.f, 1.f, 0.f);
boxO.N_top.init(0.f, 0.f, 1.f);
}
else
{
BVH_node.init(*new xSphere());
xSphere &sphere = *(xSphere*) BVH_node.Figure;
sphere.P_center.zero();
sphere.S_radius = 0.f;
Mesh_node.I_FaceCount = 0;
Mesh_node.I_FaceStride = 0;
Mesh_node.L_FaceData = 0;
Mesh_node.I_VertexCount = 0;
Mesh_node.I_VertexStride = 0;
Mesh_node.L_VertexData = 0;
Mesh_node.MX_MeshToLocal = MX_MeshToLocal;
Mesh_node.L_BoneData = 0;
Mesh_node.I_BoneStride = 0;
}
xElement *elem = L_kids;
for (; elem; elem = elem->Next)
{
boxAc = elem->FillBVH( L_BVH, MeshData );
if (boxAc.P_min.x < boxA.P_min.x) boxA.P_min.x = boxAc.P_min.x;
if (boxAc.P_min.y < boxA.P_min.y) boxA.P_min.y = boxAc.P_min.y;
if (boxAc.P_min.z < boxA.P_min.z) boxA.P_min.z = boxAc.P_min.z;
if (boxAc.P_max.x > boxA.P_max.x) boxA.P_max.x = boxAc.P_max.x;
if (boxAc.P_max.y > boxA.P_max.y) boxA.P_max.y = boxAc.P_max.y;
if (boxAc.P_max.z > boxA.P_max.z) boxA.P_max.z = boxAc.P_max.z;
}
return boxA;
}
| [
"dmaciej1@f75eed02-8a0f-11dd-b20b-83d96e936561"
]
| [
[
[
1,
587
]
]
]
|
ebdc5acceb06fd6a8593d4bdf32a90e0a4b91f90 | 2ca3ad74c1b5416b2748353d23710eed63539bb0 | /Src/Lokapala/Operator/CBFMediator.cpp | b13e2f1e369eb68e481775e137462c4fc44388cd | []
| no_license | sjp38/lokapala | 5ced19e534bd7067aeace0b38ee80b87dfc7faed | dfa51d28845815cfccd39941c802faaec9233a6e | refs/heads/master | 2021-01-15T16:10:23.884841 | 2009-06-03T14:56:50 | 2009-06-03T14:56:50 | 32,124,140 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 17,045 | cpp | /**@file CBFMediator.cpp
* @brief Common Buisiness Framework Mediator.
* @author siva
*/
#include "stdafx.h"
#include "CBFMediator.h"
#include "Resource.h"
#include "DisplayDTO.h"
#include "StatusReportsDTO.h"
///////////////////////////////////////////////////////////////////////////////////////////////////////////////
// DCM
/**@brief 호스트가 접속했음.
*/
void CCBFMediator::HostConnected(void *a_hostData)
{
CDecisionBI *_interface = CDecisionFacade::Instance();
_interface->HostConnected(a_hostData);
}
/**@brief 호스트가 접속을 끊었음. 로그아웃 했을 경우와 동일하다.
*/
void CCBFMediator::HostDisconnected(void *a_hostData)
{
CDecisionBI *_interface = CDecisionFacade::Instance();
_interface->HostDisconnected(a_hostData);
}
/**@brief 사용자 로그인 처리. 올바른 사용자인지 확인한다.
* @param a_loginRequestData 사용자 로그인 정보의 포인터. 해당 DTO의 포인터이지만 void 포인터로 캐스팅 해 사용한다.
*/
void CCBFMediator::JudgeLoginRequest(void *a_loginRequestData)
{
CDecisionBI *_interface = CDecisionFacade::Instance();
_interface->JudgeLoginRequest(a_loginRequestData);
}
/**@brief 사용자가 실행한 프로세스에 대해 올바른 프로세스인지 어떤지 확인/처리한다.
*/
void CCBFMediator::JudgeUserExecutedProcess(void *a_executedProcessData)
{
CDecisionBI *_interface = CDecisionFacade::Instance();
_interface->JudgeUserExecutedProcess(a_executedProcessData);
}
/**@brief 새로운 고장 상태 보고를 받는다.
*/
void CCBFMediator::PresentStatusReport(void *a_statusReportData)
{
CDecisionBI *_interface = CDecisionFacade::Instance();
_interface->PresentStatusReport(a_statusReportData);
}
/**@brief 특정 호스트의 컴퓨터를 종료시킨다.
*/
void CCBFMediator::ShutdownHost(void *a_argument)
{
CDecisionBI *_interface = CDecisionFacade::Instance();
_interface->ShutdownHost(a_argument);
}
/**@brief 특정 호스트의 컴퓨터를 리부팅 시킨다.
*/
void CCBFMediator::RebootHost(void *a_argument)
{
CDecisionBI *_interface = CDecisionFacade::Instance();
_interface->RebootHost(a_argument);
}
/**@brief 특정 유저를 강제로 로그아웃시킨다.
*/
void CCBFMediator::BanUser(void *a_argument)
{
CDecisionBI *_interface = CDecisionFacade::Instance();
_interface->BanUser(a_argument);
}
/**@brief 특정 호스트의 특정 프로세스를 실행시킨다.
*/
void CCBFMediator::ExecuteHostProcess(void *a_argument)
{
CDecisionBI *_interface = CDecisionFacade::Instance();
_interface->ExecuteHostProcess(a_argument);
}
/**@brief 특정 호스트의 특정 프로세스를 종료시킨다.
*/
void CCBFMediator::KillHostProcess(void *a_argument)
{
CDecisionBI *_interface = CDecisionFacade::Instance();
_interface->KillHostProcess(a_argument);
}
/**@brief 특정 호스트의 모든 프로세스를 종료시킨다.
*/
void CCBFMediator::GenocideHostProcess(void *a_argument)
{
CDecisionBI *_interface = CDecisionFacade::Instance();
_interface->GenocideHostProcess(a_argument);
}
/**@brief 특정 호스트에게 경고를 한다.
*/
void CCBFMediator::WarnHost(void *a_argument)
{
CDecisionBI *_interface = CDecisionFacade::Instance();
_interface->WarnHost(a_argument);
}
/**@brief 특정 호스트에게 상태 보고를 날린다.
*/
void CCBFMediator::SubmitStatusReportToHost(void *a_statusReport)
{
CDecisionBI *_interface = CDecisionFacade::Instance();
_interface->SubmitStatusReportToHost(a_statusReport);
}
/**@brief 특정 호스트의 랩터 동작을 멈춘다.
*/
void CCBFMediator::TerminateRaptorOnHost(void *a_argument)
{
CDecisionBI *_interface = CDecisionFacade::Instance();
_interface->TerminateRaptorOnHost(a_argument);
}
////////////////////////////////////////////////////////////////////////////////////////////////////////////////
//CCM
/**@brief CCM의 통신 초기화. 서버 구조를 구현하기 위해 리슨 소켓을 생성하고 랩터로부터의 연결 요청을 수락한다.
* @remarks 다라니 컴포넌트 테스트 용.
*/
void CCBFMediator::BeginCommunication()
{
CCommunicationBI *_interface = CCommunicationFacade::Instance();
_interface->InitiallizeAsServer();
}
/**@brief CCM을 이용해 문자를 방송한다. 연결되어 있는 모든 raptor에게 문자를 전송한다.
* @param a_message 방송할 문자.
*/
void CCBFMediator::BroadcastTextMessage(CString a_message)
{
CCommunicationBI *_interface = CCommunicationFacade::Instance();
_interface->BroadcastTextMessage(a_message);
}
/**@brief CCM을 이용해서 문자를 전송한다.
* @param a_targetAddress 문자를 전송할 위치의 ip 주소.
* @param a_message 전송할 문자.
*/
void CCBFMediator::SendTextMessageTo(CString a_targetAddress, CString a_message)
{
CCommunicationBI *_interface = CCommunicationFacade::Instance();
_interface->SendTextMessageTo(a_targetAddress, a_message);
}
/**@brief 특정 주소로 로그인 허용 메세지를 전송한다.
* @param a_acceptedData 로그인 허용 메세지를 전송하는데 필요한 데이터의 포인터.
*/
void CCBFMediator::SendLoginAcceptedNotifyMessage(void *a_acceptedData)
{
CCommunicationBI *_interface = CCommunicationFacade::Instance();
_interface->SendLoginAcceptedNotifyMessage(a_acceptedData);
}
/**@brief 특정 유저 컴퓨터를 꺼버린다.
*/
void CCBFMediator::SendShutdownInstruction(void *a_argument)
{
CCommunicationBI *_interface = CCommunicationFacade::Instance();
_interface->SendShutdownInstruction(a_argument);
}
/**@brief 특정 유저의 컴퓨터를 재부팅시킨다.
*/
void CCBFMediator::SendRebootInstruction(void *a_argument)
{
CCommunicationBI *_interface = CCommunicationFacade::Instance();
_interface->SendRebootInstruction(a_argument);
}
/**@brief 특정 유저를 강제 로그아웃 시킨다.
*/
void CCBFMediator::SendBanUserInstruction(void *a_argument)
{
CCommunicationBI *_interface = CCommunicationFacade::Instance();
_interface->SendBanUserInstruction(a_argument);
}
/**@brief 특정 유저에게 특정 프로세스를 실행시킨다.
*/
void CCBFMediator::SendExecuteProcessInstruction(void *a_argument)
{
CCommunicationBI *_interface = CCommunicationFacade::Instance();
_interface->SendExecuteProcessInstruction(a_argument);
}
void CCBFMediator::SendKillProcessInstruction(void *a_argument)
{
CCommunicationBI *_interface = CCommunicationFacade::Instance();
_interface->SendKillProcessInstruction(a_argument);
}
/**@brief 특정 유저의 실행중인 프로세스 전부를 죽여버린다.
*/
void CCBFMediator::SendGenocideProcessInstruction(void *a_argument)
{
CCommunicationBI *_interface = CCommunicationFacade::Instance();
_interface->SendGenocideProcessInstruction(a_argument);
}
/**@brief 특정 유저에게 경고 메세지를 띄운다.
*/
void CCBFMediator::SendWarningMessage(void *a_argument)
{
CCommunicationBI *_interface = CCommunicationFacade::Instance();
_interface->SendWarningMessage(a_argument);
}
/**@brief 특정 호스트로 고장 상태 보고를 날린다.
*/
void CCBFMediator::SendStatusReport(void *a_statusReport)
{
CCommunicationBI *_interface = CCommunicationFacade::Instance();
_interface->SendStatusReport(a_statusReport);
}
/**@brief 특정 호스트로 랩터 동작 중지 명령을 날린다.
*/
void CCBFMediator::SendRaptorTerminationInstruction(void *a_argument)
{
CCommunicationBI *_interface = CCommunicationFacade::Instance();
_interface->SendRaptorTerminationInstruction(a_argument);
}
/**@brief 특정 호스트로 메세지를 날린다(로카파라의 xml 포맷 패킷으로 만들어서 날린다).
* @remarks 단순히 해당 문자열만을 날리는 SendTextMessageTo 와 구별하도록.
*/
void CCBFMediator::SendTextMessageToRaptor(void *a_message)
{
CCommunicationBI *_interface = CCommunicationFacade::Instance();
_interface->SendTextMessageToRaptor(a_message);
}
///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
//DAM
/**@brief 현재 DAM의 모든 데이터를 파일로 저장한다.
*/
void CCBFMediator::SaveDataAs(CString *a_filePath)
{
CDataAdminBI *_interface = CDataAdminFacade::Instance();
_interface->SaveDataAs(a_filePath);
}
/**@brief 외부 파일로부터 데이터를 읽어들인다.
*/
void CCBFMediator::LoadDataFrom(CString *a_filePath)
{
CDataAdminBI *_interface = CDataAdminFacade::Instance();
_interface->LoadDataFrom(a_filePath);
}
/**@brief DAM에 유저를 추가한다.
*/
void CCBFMediator::AddUser(void *a_user)
{
CDataAdminBI *_interface = CDataAdminFacade::Instance();
_interface->AddUser(a_user);
}
/**@brief DAM에서 유저를 삭제한다.
*/
void CCBFMediator::DeleteUser(CString *a_id)
{
CDataAdminBI *_interface = CDataAdminFacade::Instance();
_interface->DeleteUser(a_id);
}
/**@brief 유저 정보 전체를 알려준다.\n
* 실제 유저 정보체의 구조를 모든 곳에서 알게 될 필요는 없으므로 포인터는 void 포인터로 캐스팅 되어 전달된다.\n
* 최종 클라이언트 코드에서만 실제 유저 정보체의 구조를 알면(유저 정보체 헤더를 인클루드) 된다.
* @return void 포인터로 캐스팅 된 유저 정보 구조체의 포인터
*/
void *CCBFMediator::GetUsers()
{
CDataAdminBI *_interface = CDataAdminFacade::Instance();
return _interface->GetUsers();
}
/**@brief 좌석의 전체 크기를 설정한다. */
void CCBFMediator::SetSeats(int a_x, int a_y)
{
CDataAdminBI *_interface = CDataAdminFacade::Instance();
_interface->SetSeats(a_x, a_y);
}
/**@brief 좌석 정보를 추가한다. */
void CCBFMediator::AddSeat(void *a_seat)
{
CDataAdminBI *_interface = CDataAdminFacade::Instance();
_interface->AddSeat(a_seat);
}
/**@brief 좌석 정보를 삭제한다. */
void CCBFMediator::DeleteSeat(void *a_seat)
{
CDataAdminBI *_interface = CDataAdminFacade::Instance();
_interface->DeleteSeat(a_seat);
}
/**@brief 전체 좌석 정보를 얻는다.
* void 포인터로 캐스팅 되어 전달되므로 최종 클라이언트 코드에서만 실제 좌석 정보체 구조를 알면 된다.
*/
void *CCBFMediator::GetSeats()
{
CDataAdminBI *_interface = CDataAdminFacade::Instance();
return _interface->GetSeats();
}
/**@brief 금지 프로세스 관련 규칙을 하나 추가한다.
*/
void CCBFMediator::AddRule(void *a_rule)
{
CDataAdminBI *_interface = CDataAdminFacade::Instance();
_interface->AddRule(a_rule);
}
/**@brief 금지 프로세스 관련 규칙을 하나 삭제한다.
*/
void CCBFMediator::DeleteRule(void *a_rule)
{
CDataAdminBI *_interface = CDataAdminFacade::Instance();
_interface->DeleteRule(a_rule);
}
/**@brief 금지 프로세스 관련 규칙 전체를 얻어온다.
*/
void *CCBFMediator::GetRules()
{
CDataAdminBI *_interface = CDataAdminFacade::Instance();
return _interface->GetRules();
}
/**@brief 고장 상태 정보 전체를 얻어온다.
*/
void *CCBFMediator::GetStatusReports()
{
CDataAdminBI *_interface = CDataAdminFacade::Instance();
return _interface->GetStatusReports();
}
/**@brief 접속된 사용자 전체 정보를 얻어온다.
*/
void *CCBFMediator::GetConnectedHosts()
{
CDataAdminBI *_interface = CDataAdminFacade::Instance();
return _interface->GetConnectedHosts();
}
///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
//MSM
/**@brief 랩터에게 텍스트 메세지를 보낸다.
*/
void CCBFMediator::PostTextMessgeTo(void *a_messageData)
{
CMessengerBI *_interface = CMessengerFacade::Instance();
_interface->PostTextMessageTo(a_messageData);
}
/**@brief 랩터로부터 텍스트 메세지를 받았음을 알린다.
*/
void CCBFMediator::PresentMessage(void *a_messageData)
{
CMessengerBI *_interface = CMessengerFacade::Instance();
_interface->ReceiveTextMessageFrom(a_messageData);
}
/////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
/**@brief 메인 다이얼로그의 포인터를 저장한다.
*/
void CCBFMediator::SetMainDlg(CDialog *a_pDlg)
{
m_mainDlg = a_pDlg;
}
/**@brief 공지 리스트박스에 공지사항을 표시한다.
*/
void CCBFMediator::Notify(CString *a_notifyMessage)
{
void *notifyMessage = (void *)a_notifyMessage;
SendMessage(m_mainDlg->m_hWnd, LKPLM_NOTIFYMESSAGE, (WPARAM)notifyMessage, NULL);
}
/**@brief 새로운 랩터의 로그인을 알린다.
*/
void CCBFMediator::NotifyRaptorLogin(CString *a_address)
{
CDisplayDTO displayData(*a_address, LOGIN);
SendMessage(m_mainDlg->m_hWnd, LKPLM_SHOWCHANGED, (WPARAM)&displayData, NULL);
}
/**@brief 특정 랩터의 로그아웃을 알린다.
*/
void CCBFMediator::NotifyRaptorLogout(CString *a_address)
{
CDisplayDTO displayData(*a_address, LOGOUT);
SendMessage(m_mainDlg->m_hWnd, LKPLM_SHOWCHANGED, (WPARAM)&displayData, NULL);
}
/**@brief 특정 금지 프로세스를 실행했음을 알린다.
*/
void CCBFMediator::NotifyRaptorExecutedProcess(CString *a_hostAddress, CString *a_executedProcess)
{
CDisplayDTO displayData(*a_hostAddress, CRIMINAL, *a_executedProcess);
SendMessage(m_mainDlg->m_hWnd, LKPLM_SHOWCHANGED, (WPARAM)&displayData, NULL);
}
/**@brief 상황 보고를 알린다.
*/
void CCBFMediator::NotifyRaptorStatusChange(void *a_statusReports)
{
CStatusReportDTOArray *statusReports = (CStatusReportDTOArray *)a_statusReports;
if( (*statusReports)[0].m_state == VERIFIED )
{
CDisplayDTO displayData( (*statusReports)[0].m_hostAddress, FINE, _T(""));
SendMessage(m_mainDlg->m_hWnd, LKPLM_SHOWCHANGED, (WPARAM)&displayData, NULL);
return;
}
BOOL sw = FALSE;
BOOL hw = FALSE;
for(int i=0;i<statusReports->GetCount(); i++)
{
if( (*statusReports)[i].m_state == SW_DEFECT )
{
sw = TRUE;
}
else if( (*statusReports)[i].m_state == HW_DEFECT )
{
hw = TRUE;
}
}
enum DisplayState state;
if(sw)
{
state = SW;
}
if(hw)
{
state = HW;
}
if(sw && hw)
{
state = HWSW;
}
if(!sw && !hw)
{
state = FINE;
}
CDisplayDTO displayData( (*statusReports)[0].m_hostAddress, state);
SendMessage(m_mainDlg->m_hWnd, LKPLM_SHOWCHANGED, (WPARAM)&displayData, NULL);
}
/**@brief 특정 랩터로부터의 소켓 연결이 들어왔음을 알린다.
* 이는 곧 로그인 시도임을 의미한다.
*/
void CCBFMediator::NotifyRaptorAccepted(CString *a_address)
{
CDisplayDTO display(*a_address, DISPLAY_CONNECTED);
SendMessage(m_mainDlg->m_hWnd, LKPLM_SHOWCHANGED, (WPARAM)&display, NULL);
}
/**@brief 특정 랩터로부터의 소켓 연결이 끊어졌음을 알린다.
* 이는 오퍼레이터의 강제 로그아웃에 의해서일 수도, 해당 랩터의 연결 해제에 의해서일 수도 있다.
* 하지만 어쨌건 해당 랩터는 로그아웃 상태에 빠진다.
*/
void CCBFMediator::NotifyRaptorLeaved(CString *a_address)
{
CDisplayDTO display(*a_address, DISPLAY_DISCONNECTED);
SendMessage(m_mainDlg->m_hWnd, LKPLM_SHOWCHANGED, (WPARAM)&display, NULL);
}
/**@brief 좌석의 크기 변경을 알린다.
*/
void CCBFMediator::NotifySeatResized(int a_maxX, int a_maxY)
{
CDisplayDTO display(_T(""), SEATRESIZE, _T(""), a_maxX, a_maxY);
SendMessage(m_mainDlg->m_hWnd, LKPLM_SHOWCHANGED, (WPARAM)&display, NULL);
}
/**@brief 새로운 좌석의 추가를 알린다.
*/
void CCBFMediator::NotifySeatAdded(CString *a_seatId)
{
CDisplayDTO display(*a_seatId, SEATADD);
SendMessage(m_mainDlg->m_hWnd, LKPLM_SHOWCHANGED, (WPARAM)&display, NULL);
}
/**@brief 좌석의 삭제를 알린다.
*/
void CCBFMediator::NotifySeatDeleted(CString *a_seatId)
{
CDisplayDTO display(*a_seatId, SEATDELETE);
SendMessage(m_mainDlg->m_hWnd, LKPLM_SHOWCHANGED, (WPARAM)&display, NULL);
}
/**@brief 랩터로부터의 텍스트 메세지 도착을 유저에게 알린다.
*/
void CCBFMediator::NotifyRaptorMessageReceived(CString a_hostAddress, CString a_message)
{
CDisplayDTO display(a_hostAddress, MESSAGE_FROM_RAPTOR_RECEIVED, a_message);
SendMessage(m_mainDlg->m_hWnd, LKPLM_SHOWCHANGED, (WPARAM)&display, NULL);
}
/**@brief 랩터에게 텍스트 메세지를 날렸음을 유저에게 알린다.
*/
void CCBFMediator::NotifyTextMessageToRaptorSended(CString a_hostAddress, CString a_message)
{
CDisplayDTO display(a_hostAddress, MESSAGE_TO_RAPTOR_SENDED, a_message);
SendMessage(m_mainDlg->m_hWnd, LKPLM_SHOWCHANGED, (WPARAM)&display, NULL);
}
| [
"nilakantha38@b9e76448-5c52-0410-ae0e-a5aea8c5d16c"
]
| [
[
[
1,
549
]
]
]
|
b0f962eac2a8c93af88be9731ea50f0182c7ec2f | 222bc22cb0330b694d2c3b0f4b866d726fd29c72 | /src/brookbox/wm2/WmlBisect3.h | e58f3843a5d4070d2df031eea4d1bc33e78ea4b5 | [
"LicenseRef-scancode-other-permissive",
"LicenseRef-scancode-unknown-license-reference"
]
| permissive | darwin/inferno | 02acd3d05ca4c092aa4006b028a843ac04b551b1 | e87017763abae0cfe09d47987f5f6ac37c4f073d | refs/heads/master | 2021-03-12T22:15:47.889580 | 2009-04-17T13:29:39 | 2009-04-17T13:29:39 | 178,477 | 2 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 2,484 | h | // Magic Software, Inc.
// http://www.magic-software.com
// http://www.wild-magic.com
// Copyright (c) 2003. All Rights Reserved
//
// The Wild Magic Library (WML) source code is supplied under the terms of
// the license agreement http://www.magic-software.com/License/WildMagic.pdf
// and may not be copied or disclosed except in accordance with the terms of
// that agreement.
#ifndef WMLBISECT3_H
#define WMLBISECT3_H
#include "WmlSystem.h"
namespace Wml
{
template <class Real>
class WML_ITEM Bisect3
{
public:
typedef Real (*Function)(Real,Real,Real);
Bisect3 (Function oF, Function oG, Function oH, int iMaxLevel,
Real fTolerance);
bool Bisect (Real fX0, Real fY0, Real fZ0, Real fX1,
Real fY1, Real fZ1, Real& rfXRoot, Real& rfYRoot,
Real& rfZRoot);
private:
class WML_ITEM BisectNode
{
public:
Real m_fX, m_fY, m_fZ, m_fF, m_fG, m_fH;
BisectNode* m_pkXNext;
BisectNode* m_pkYNext;
BisectNode* m_pkZNext;
};
// input data and functions
Function m_oF, m_oG, m_oH;
int m_iLevel, m_iMaxLevel;
Real m_fTolerance;
Real m_fXRoot, m_fYRoot, m_fZRoot;
// vertex and midpoint locations
Real m_fX0, m_fXm, m_fX1, m_fY0, m_fYm, m_fY1, m_fZ0, m_fZm, m_fZ1;
// vertices
Real m_fF000, m_fF100, m_fF010, m_fF110;
Real m_fF001, m_fF101, m_fF011, m_fF111;
Real m_fG000, m_fG100, m_fG010, m_fG110;
Real m_fG001, m_fG101, m_fG011, m_fG111;
Real m_fH000, m_fH100, m_fH010, m_fH110;
Real m_fH001, m_fH101, m_fH011, m_fH111;
// edges
Real m_fF00m, m_fF10m, m_fF01m, m_fF11m, m_fF0m0, m_fF1m0, m_fF0m1;
Real m_fF1m1, m_fFm00, m_fFm10, m_fFm01, m_fFm11;
Real m_fG00m, m_fG10m, m_fG01m, m_fG11m, m_fG0m0, m_fG1m0, m_fG0m1;
Real m_fG1m1, m_fGm00, m_fGm10, m_fGm01, m_fGm11;
Real m_fH00m, m_fH10m, m_fH01m, m_fH11m, m_fH0m0, m_fH1m0, m_fH0m1;
Real m_fH1m1, m_fHm00, m_fHm10, m_fHm01, m_fHm11;
// faces
Real m_fF0mm, m_fFm0m, m_fFmm0, m_fF1mm, m_fFm1m, m_fFmm1;
Real m_fG0mm, m_fGm0m, m_fGmm0, m_fG1mm, m_fGm1m, m_fGmm1;
Real m_fH0mm, m_fHm0m, m_fHmm0, m_fH1mm, m_fHm1m, m_fHmm1;
// center
Real m_fFmmm, m_fGmmm, m_fHmmm;
int m_iNetSign;
BisectNode* m_pkTemp;
// the graph and recursion routine for building it
BisectNode* m_pkGraph;
bool BisectRecurse (BisectNode* m_pkN000);
};
}
#endif
| [
"[email protected]"
]
| [
[
[
1,
85
]
]
]
|
899d7321b280d3071703398e28dcb1eec552a407 | 6c8c4728e608a4badd88de181910a294be56953a | /Core/Quaternion.cpp | d263ec2ee37f5b609ed4cd0cedb85dcc86f3d358 | [
"Apache-2.0",
"LicenseRef-scancode-unknown-license-reference"
]
| permissive | caocao/naali | 29c544e121703221fe9c90b5c20b3480442875ef | 67c5aa85fa357f7aae9869215f840af4b0e58897 | refs/heads/master | 2021-01-21T00:25:27.447991 | 2010-03-22T15:04:19 | 2010-03-22T15:04:19 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 241 | cpp | // For conditions of distribution and use, see copyright notice in license.txt
#include "CoreStableHeaders.h"
#include "Quaternion.h"
const Quaternion Quaternion::ZERO(0, 0, 0, 0);
const Quaternion Quaternion::IDENTITY(0, 0, 0, 1);
| [
"cmayhem@5b2332b8-efa3-11de-8684-7d64432d61a3",
"cadaver@5b2332b8-efa3-11de-8684-7d64432d61a3"
]
| [
[
[
1,
5
]
],
[
[
6,
7
]
]
]
|
c06a754262fac6e25eceda74f66c5fd2c1779269 | 6c8c4728e608a4badd88de181910a294be56953a | /CommunicationModule/OpensimIM/Contact.h | 694d5646f7b00264771fdea56683cf8d2185bf6e | [
"Apache-2.0",
"LicenseRef-scancode-unknown-license-reference"
]
| permissive | caocao/naali | 29c544e121703221fe9c90b5c20b3480442875ef | 67c5aa85fa357f7aae9869215f840af4b0e58897 | refs/heads/master | 2021-01-21T00:25:27.447991 | 2010-03-22T15:04:19 | 2010-03-22T15:04:19 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,630 | h | // For conditions of distribution and use, see copyright notice in license.txt
#ifndef incl_Communication_OpensimIM_Contact_h
#define incl_Communication_OpensimIM_Contact_h
//#include "Foundation.h"
//#include "NetworkEvents.h"
//#include "interface.h"
#include "ContactInterface.h"
namespace OpensimIM
{
/**
* @todo Initial state of online status is not checked currently.
*
*/
class Contact : public Communication::ContactInterface
{
public:
Contact(const QString &id, const QString &name);
//! UUID of this contact
virtual QString GetID() const;
//! Provides name of this contact item
virtual QString GetName() const;
//! Not supported by Opensim
virtual void SetName(const QString& name);
//! Values "online", "offline"
virtual QString GetPresenceStatus() const;
//! Not supported by Opensim
virtual QString GetPresenceMessage() const;
//! Connection object calls this according messages from server
virtual void SetOnlineStatus(bool online);
private:
//! UUID of this contact
QString id_;
QString name_;
bool online_;
bool is_typing_; // probably will be used on ChatSessionParticipant class
//bool rights_to_see_users_online_status;
//bool rights_to_locate_user_;
//bool right_to_use_users_objects_;
};
typedef std::vector<Contact*> ContactVector;
} // end of namespace: OpensimIM
#endif // incl_Communication_OpensimIM_Contact_h
| [
"Stinkfist0@5b2332b8-efa3-11de-8684-7d64432d61a3",
"mattiku@5b2332b8-efa3-11de-8684-7d64432d61a3",
"jujjyl@5b2332b8-efa3-11de-8684-7d64432d61a3"
]
| [
[
[
1,
2
],
[
13,
20
],
[
22,
23
],
[
25,
26
],
[
28,
29
],
[
31,
32
],
[
34,
35
],
[
37,
39
],
[
41,
42
],
[
44,
44
],
[
46,
47
],
[
49,
53
]
],
[
[
3,
5
],
[
10,
12
],
[
21,
21
],
[
24,
24
],
[
27,
27
],
[
30,
30
],
[
33,
33
],
[
36,
36
],
[
40,
40
],
[
43,
43
],
[
45,
45
],
[
48,
48
],
[
54,
57
]
],
[
[
6,
9
]
]
]
|
e3f29333a6da71bf47ff09999acd31ed4b7804b2 | 9c62af23e0a1faea5aaa8dd328ba1d82688823a5 | /rl/branches/newton20/engine/core/include/SaveGameFile.h | 870c459abb19a62537fc35319199817e5c74ca9b | [
"ClArtistic",
"LicenseRef-scancode-unknown-license-reference",
"LicenseRef-scancode-public-domain"
]
| permissive | jacmoe/dsa-hl-svn | 55b05b6f28b0b8b216eac7b0f9eedf650d116f85 | 97798e1f54df9d5785fb206c7165cd011c611560 | refs/heads/master | 2021-04-22T12:07:43.389214 | 2009-11-27T22:01:03 | 2009-11-27T22:01:03 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 2,497 | h | /* This source file is part of Rastullahs Lockenpracht.
* Copyright (C) 2003-2008 Team Pantheon. http://www.team-pantheon.de
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the Clarified Artistic License.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* Clarified Artistic License for more details.
*
* You should have received a copy of the Clarified Artistic License
* along with this program; if not you can get it here
* http://www.jpaulmorrison.com/fbp/artistic2.htm.
*/
#ifndef __SaveGameFile_H__
#define __SaveGameFile_H__
#include "CorePrerequisites.h"
#include <xercesc/framework/XMLFormatter.hpp>
#include <ctime>
#include "Property.h"
#include "Properties.h"
namespace rl
{
class _RlCoreExport SaveGameFile : public PropertyHolder, public Ogre::ScriptLoader
{
public:
static const Ogre::String PROPERTY_MODULEID;
static const Ogre::String PROPERTY_TIME;
static const Ogre::String PROPERTY_NAME;
static const Ogre::String PROPERTY_MODULENAME;
SaveGameFile(const CeGuiString &name, int id = 0);
~SaveGameFile();
CeGuiString buildFilename();
CeGuiString getName();
int getId();
bool saveGameExists();
//access to file
Ogre::DataStreamPtr &getDataStream();
void closeDataStream();
XERCES_CPP_NAMESPACE::XMLFormatTarget* getFormatTarget();
void deleteFileFromStorage();
//data to be saved
virtual const Ogre::StringVector& getScriptPatterns(void) const;
virtual void parseScript(Ogre::DataStreamPtr &stream, const Ogre::String &groupName);
virtual Ogre::Real getLoadingOrder(void) const;
//propertyholder
virtual const Property getProperty(const CeGuiString& key) const;
virtual void setProperty(const CeGuiString& key, const Property& value);
virtual PropertyKeys getAllPropertyKeys() const;
protected:
//properties
CeGuiString mName;
CeGuiString mModuleID;
CeGuiString mModuleName;
CeGuiString mLocalTime;
//file access
Ogre::StringVector mScriptPatterns;
Ogre::DataStreamPtr mStream;
int mSaveGameId;
};
}
#endif
| [
"melven@4c79e8ff-cfd4-0310-af45-a38c79f83013"
]
| [
[
[
1,
76
]
]
]
|
5f0a6cb7714d295114fdc9a7059112627160cd58 | 02c2e62bcb9a54738bfbd95693978b8709e88fdb | /opencv/cvmoments.cpp | 4ffc22e2510ea4f33db8ac41cdde632c83908e75 | []
| no_license | ThadeuFerreira/sift-coprojeto | 7ab823926e135f0ac388ae267c40e7069e39553a | bba43ef6fa37561621eb5f2126e5aa7d1c3f7024 | refs/heads/master | 2021-01-10T15:15:21.698124 | 2009-05-08T17:38:51 | 2009-05-08T17:38:51 | 45,042,655 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 28,123 | cpp | /*M///////////////////////////////////////////////////////////////////////////////////////
//
// IMPORTANT: READ BEFORE DOWNLOADING, COPYING, INSTALLING OR USING.
//
// By downloading, copying, installing or using the software you agree to this license.
// If you do not agree to this license, do not download, install,
// copy or use the software.
//
//
// Intel License Agreement
// For Open Source Computer Vision Library
//
// Copyright (C) 2000, Intel Corporation, all rights reserved.
// Third party copyrights are property of their respective owners.
//
// Redistribution and use in source and binary forms, with or without modification,
// are permitted provided that the following conditions are met:
//
// * Redistribution's of source code must retain the above copyright notice,
// this list of conditions and the following disclaimer.
//
// * Redistribution's in binary form must reproduce the above copyright notice,
// this list of conditions and the following disclaimer in the documentation
// and/or other materials provided with the distribution.
//
// * The name of Intel Corporation may not be used to endorse or promote products
// derived from this software without specific prior written permission.
//
// This software is provided by the copyright holders and contributors "as is" and
// any express or implied warranties, including, but not limited to, the implied
// warranties of merchantability and fitness for a particular purpose are disclaimed.
// In no event shall the Intel Corporation or contributors be liable for any direct,
// indirect, incidental, special, exemplary, or consequential damages
// (including, but not limited to, procurement of substitute goods or services;
// loss of use, data, or profits; or business interruption) however caused
// and on any theory of liability, whether in contract, strict liability,
// or tort (including negligence or otherwise) arising in any way out of
// the use of this software, even if advised of the possibility of such damage.
//
//M*/
#include "_cv.h"
/* The function calculates center of gravity and central second order moments */
static void
icvCompleteMomentState( CvMoments* moments )
{
double cx = 0, cy = 0;
double mu20, mu11, mu02;
assert( moments != 0 );
moments->inv_sqrt_m00 = 0;
if( fabs(moments->m00) > DBL_EPSILON )
{
double inv_m00 = 1. / moments->m00;
cx = moments->m10 * inv_m00;
cy = moments->m01 * inv_m00;
moments->inv_sqrt_m00 = sqrt( fabs(inv_m00) );
}
/* mu20 = m20 - m10*cx */
mu20 = moments->m20 - moments->m10 * cx;
/* mu11 = m11 - m10*cy */
mu11 = moments->m11 - moments->m10 * cy;
/* mu02 = m02 - m01*cy */
mu02 = moments->m02 - moments->m01 * cy;
moments->mu20 = mu20;
moments->mu11 = mu11;
moments->mu02 = mu02;
/* mu30 = m30 - cx*(3*mu20 + cx*m10) */
moments->mu30 = moments->m30 - cx * (3 * mu20 + cx * moments->m10);
mu11 += mu11;
/* mu21 = m21 - cx*(2*mu11 + cx*m01) - cy*mu20 */
moments->mu21 = moments->m21 - cx * (mu11 + cx * moments->m01) - cy * mu20;
/* mu12 = m12 - cy*(2*mu11 + cy*m10) - cx*mu02 */
moments->mu12 = moments->m12 - cy * (mu11 + cy * moments->m10) - cx * mu02;
/* mu03 = m03 - cy*(3*mu02 + cy*m01) */
moments->mu03 = moments->m03 - cy * (3 * mu02 + cy * moments->m01);
}
static void
icvContourMoments( CvSeq* contour, CvMoments* moments )
{
int is_float = CV_SEQ_ELTYPE(contour) == CV_32FC2;
if( contour->total )
{
CvSeqReader reader;
double a00, a10, a01, a20, a11, a02, a30, a21, a12, a03;
double xi, yi, xi2, yi2, xi_1, yi_1, xi_12, yi_12, dxy, xii_1, yii_1;
int lpt = contour->total;
a00 = a10 = a01 = a20 = a11 = a02 = a30 = a21 = a12 = a03 = 0;
cvStartReadSeq( contour, &reader, 0 );
if( !is_float )
{
xi_1 = ((CvPoint*)(reader.ptr))->x;
yi_1 = ((CvPoint*)(reader.ptr))->y;
}
else
{
xi_1 = ((CvPoint2D32f*)(reader.ptr))->x;
yi_1 = ((CvPoint2D32f*)(reader.ptr))->y;
}
CV_NEXT_SEQ_ELEM( contour->elem_size, reader );
xi_12 = xi_1 * xi_1;
yi_12 = yi_1 * yi_1;
while( lpt-- > 0 )
{
if( !is_float )
{
xi = ((CvPoint*)(reader.ptr))->x;
yi = ((CvPoint*)(reader.ptr))->y;
}
else
{
xi = ((CvPoint2D32f*)(reader.ptr))->x;
yi = ((CvPoint2D32f*)(reader.ptr))->y;
}
CV_NEXT_SEQ_ELEM( contour->elem_size, reader );
xi2 = xi * xi;
yi2 = yi * yi;
dxy = xi_1 * yi - xi * yi_1;
xii_1 = xi_1 + xi;
yii_1 = yi_1 + yi;
a00 += dxy;
a10 += dxy * xii_1;
a01 += dxy * yii_1;
a20 += dxy * (xi_1 * xii_1 + xi2);
a11 += dxy * (xi_1 * (yii_1 + yi_1) + xi * (yii_1 + yi));
a02 += dxy * (yi_1 * yii_1 + yi2);
a30 += dxy * xii_1 * (xi_12 + xi2);
a03 += dxy * yii_1 * (yi_12 + yi2);
a21 +=
dxy * (xi_12 * (3 * yi_1 + yi) + 2 * xi * xi_1 * yii_1 +
xi2 * (yi_1 + 3 * yi));
a12 +=
dxy * (yi_12 * (3 * xi_1 + xi) + 2 * yi * yi_1 * xii_1 +
yi2 * (xi_1 + 3 * xi));
xi_1 = xi;
yi_1 = yi;
xi_12 = xi2;
yi_12 = yi2;
}
double db1_2, db1_6, db1_12, db1_24, db1_20, db1_60;
if( fabs(a00) > FLT_EPSILON )
{
if( a00 > 0 )
{
db1_2 = 0.5;
db1_6 = 0.16666666666666666666666666666667;
db1_12 = 0.083333333333333333333333333333333;
db1_24 = 0.041666666666666666666666666666667;
db1_20 = 0.05;
db1_60 = 0.016666666666666666666666666666667;
}
else
{
db1_2 = -0.5;
db1_6 = -0.16666666666666666666666666666667;
db1_12 = -0.083333333333333333333333333333333;
db1_24 = -0.041666666666666666666666666666667;
db1_20 = -0.05;
db1_60 = -0.016666666666666666666666666666667;
}
/* spatial moments */
moments->m00 = a00 * db1_2;
moments->m10 = a10 * db1_6;
moments->m01 = a01 * db1_6;
moments->m20 = a20 * db1_12;
moments->m11 = a11 * db1_24;
moments->m02 = a02 * db1_12;
moments->m30 = a30 * db1_20;
moments->m21 = a21 * db1_60;
moments->m12 = a12 * db1_60;
moments->m03 = a03 * db1_20;
icvCompleteMomentState( moments );
}
}
}
/* summarizes moment values for all tiles */
static void
icvAccumulateMoments( double *tiles, CvSize size, CvSize tile_size, CvMoments * moments )
{
int x, y;
for( y = 0; y < size.height; y += tile_size.height )
{
for( x = 0; x < size.width; x += tile_size.width, tiles += 10 )
{
double dx = x, dy = y;
double dxm = dx * tiles[0], dym = dy * tiles[0];
/* + m00 ( = m00' ) */
moments->m00 += tiles[0];
/* + m10 ( = m10' + dx*m00' ) */
moments->m10 += tiles[1] + dxm;
/* + m01 ( = m01' + dy*m00' ) */
moments->m01 += tiles[2] + dym;
/* + m20 ( = m20' + 2*dx*m10' + dx*dx*m00' ) */
moments->m20 += tiles[3] + dx * (tiles[1] * 2 + dxm);
/* + m11 ( = m11' + dx*m01' + dy*m10' + dx*dy*m00' ) */
moments->m11 += tiles[4] + dx * (tiles[2] + dym) + dy * tiles[1];
/* + m02 ( = m02' + 2*dy*m01' + dy*dy*m00' ) */
moments->m02 += tiles[5] + dy * (tiles[2] * 2 + dym);
/* + m30 ( = m30' + 3*dx*m20' + 3*dx*dx*m10' + dx*dx*dx*m00' ) */
moments->m30 += tiles[6] + dx * (3. * tiles[3] + dx * (3. * tiles[1] + dxm));
/* + m21 (= m21' + dx*(2*m11' + 2*dy*m10' + dx*m01' + dx*dy*m00') + dy*m20') */
moments->m21 += tiles[7] + dx * (2 * (tiles[4] + dy * tiles[1]) +
dx * (tiles[2] + dym)) + dy * tiles[3];
/* + m12 (= m12' + dy*(2*m11' + 2*dx*m01' + dy*m10' + dx*dy*m00') + dx*m02') */
moments->m12 += tiles[8] + dy * (2 * (tiles[4] + dx * tiles[2]) +
dy * (tiles[1] + dxm)) + dx * tiles[5];
/* + m03 ( = m03' + 3*dy*m02' + 3*dy*dy*m01' + dy*dy*dy*m00' ) */
moments->m03 += tiles[9] + dy * (3. * tiles[5] + dy * (3. * tiles[2] + dym));
}
}
icvCompleteMomentState( moments );
}
/****************************************************************************************\
* Spatial Moments *
\****************************************************************************************/
#define ICV_DEF_CALC_MOMENTS_IN_TILE( __op__, name, flavor, srctype, temptype, momtype ) \
static CvStatus CV_STDCALL icv##name##_##flavor##_CnCR \
( const srctype* img, int step, CvSize size, int cn, int coi, double *moments ) \
{ \
int x, y, sx_init = (size.width & -4) * (size.width & -4), sy = 0; \
momtype mom[10]; \
\
assert( img && size.width && (size.width | size.height) >= 0 ); \
memset( mom, 0, 10 * sizeof( mom[0] )); \
\
if( coi ) \
img += coi - 1; \
\
for( y = 0; y < size.height; sy += 2 * y + 1, y++, (char*&)img += step ) \
{ \
temptype x0 = 0; \
temptype x1 = 0; \
temptype x2 = 0; \
momtype x3 = 0; \
int sx = sx_init; \
const srctype* ptr = img; \
\
for( x = 0; x < size.width - 3; x += 4, ptr += cn*4 ) \
{ \
temptype p0 = __op__(ptr[0]), p1 = __op__(ptr[cn]), \
p2 = __op__(ptr[2*cn]), p3 = __op__(ptr[3*cn]); \
temptype t = p1; \
temptype a, b, c; \
\
p0 += p1 + p2 + p3; /* p0 + p1 + p2 + p3 */ \
p1 += 2 * p2 + 3 * p3; /* p1 + p2*2 + p3*3 */ \
p2 = p1 + 2 * p2 + 6 * p3; /* p1 + p2*4 + p3*9 */ \
p3 = 2 * p2 - t + 9 * p3; /* p1 + p2*8 + p3*27 */ \
\
a = x * p0 + p1; /* x*p0 + (x+1)*p1 + (x+2)*p2 + (x+3)*p3 */ \
b = x * p1 + p2; /* (x+1)*p1 + 2*(x+2)*p2 + 3*(x+3)*p3 */ \
c = x * p2 + p3; /* (x+1)*p1 + 4*(x+2)*p2 + 9*(x+3)*p3 */ \
\
x0 += p0; \
x1 += a; \
a = a * x + b; /*(x^2)*p0+((x+1)^2)*p1+((x+2)^2)*p2+((x+3)^2)*p3 */ \
x2 += a; \
x3 += ((momtype)(a + b)) * x + c; /*x3 += (x^3)*p0+((x+1)^3)*p1 + */ \
/* ((x+2)^3)*p2+((x+3)^3)*p3 */ \
} \
\
/* process the rest */ \
for( ; x < size.width; sx += 2 * x + 1, x++, ptr += cn ) \
{ \
temptype p = __op__(ptr[0]); \
temptype xp = x * p; \
\
x0 += p; \
x1 += xp; \
x2 += sx * p; \
x3 += ((momtype)sx) * xp; \
} \
\
{ \
temptype py = y * x0; \
\
mom[9] += ((momtype)py) * sy; /* m03 */ \
mom[8] += ((momtype)x1) * sy; /* m12 */ \
mom[7] += ((momtype)x2) * y; /* m21 */ \
mom[6] += x3; /* m30 */ \
mom[5] += x0 * sy; /* m02 */ \
mom[4] += x1 * y; /* m11 */ \
mom[3] += x2; /* m20 */ \
mom[2] += py; /* m01 */ \
mom[1] += x1; /* m10 */ \
mom[0] += x0; /* m00 */ \
} \
} \
\
for( x = 0; x < 10; x++ ) \
moments[x] = (double)mom[x]; \
\
return CV_OK; \
}
ICV_DEF_CALC_MOMENTS_IN_TILE( CV_NOP, MomentsInTile, 8u, uchar, int, int )
ICV_DEF_CALC_MOMENTS_IN_TILE( CV_NOP, MomentsInTile, 16u, ushort, int, int64 )
ICV_DEF_CALC_MOMENTS_IN_TILE( CV_NOP, MomentsInTile, 16s, short, int, int64 )
ICV_DEF_CALC_MOMENTS_IN_TILE( CV_NOP, MomentsInTile, 32f, float, double, double )
ICV_DEF_CALC_MOMENTS_IN_TILE( CV_NOP, MomentsInTile, 64f, double, double, double )
ICV_DEF_CALC_MOMENTS_IN_TILE( CV_NONZERO, MomentsInTileBin, 8u, uchar, int, int )
ICV_DEF_CALC_MOMENTS_IN_TILE( CV_NONZERO, MomentsInTileBin, 16s, ushort, int, int )
ICV_DEF_CALC_MOMENTS_IN_TILE( CV_NONZERO_FLT, MomentsInTileBin, 32f, int, int, int )
ICV_DEF_CALC_MOMENTS_IN_TILE( CV_NONZERO_FLT, MomentsInTileBin, 64f, int64, double, double )
#define icvMomentsInTile_8s_CnCR 0
#define icvMomentsInTile_32s_CnCR 0
#define icvMomentsInTileBin_8s_CnCR icvMomentsInTileBin_8u_CnCR
#define icvMomentsInTileBin_16u_CnCR icvMomentsInTileBin_16s_CnCR
#define icvMomentsInTileBin_32s_CnCR 0
CV_DEF_INIT_FUNC_TAB_2D( MomentsInTile, CnCR )
CV_DEF_INIT_FUNC_TAB_2D( MomentsInTileBin, CnCR )
////////////////////////////////// IPP moment functions //////////////////////////////////
icvMoments_8u_C1R_t icvMoments_8u_C1R_p = 0;
icvMoments_32f_C1R_t icvMoments_32f_C1R_p = 0;
icvMomentInitAlloc_64f_t icvMomentInitAlloc_64f_p = 0;
icvMomentFree_64f_t icvMomentFree_64f_p = 0;
icvGetSpatialMoment_64f_t icvGetSpatialMoment_64f_p = 0;
typedef CvStatus (CV_STDCALL * CvMomentIPPFunc)
( const void* img, int step, CvSize size, void* momentstate );
CV_IMPL void
cvMoments( const void* array, CvMoments* moments, int binary )
{
static CvFuncTable mom_tab;
static CvFuncTable mombin_tab;
static int inittab = 0;
double* tiles = 0;
void* ippmomentstate = 0;
CV_FUNCNAME("cvMoments");
__BEGIN__;
int type = 0, depth, cn, pix_size;
int coi = 0;
int x, y, k, tile_num = 1;
CvSize size, tile_size = { 32, 32 };
CvMat stub, *mat = (CvMat*)array;
CvFunc2DnC_1A1P func = 0;
CvMomentIPPFunc ipp_func = 0;
CvContour contour_header;
CvSeq* contour = 0;
CvSeqBlock block;
if( CV_IS_SEQ( array ))
{
contour = (CvSeq*)array;
if( !CV_IS_SEQ_POLYGON( contour ))
CV_ERROR( CV_StsBadArg, "The passed sequence is not a valid contour" );
}
if( !inittab )
{
icvInitMomentsInTileCnCRTable( &mom_tab );
icvInitMomentsInTileBinCnCRTable( &mombin_tab );
inittab = 1;
}
if( !moments )
CV_ERROR( CV_StsNullPtr, "" );
memset( moments, 0, sizeof(*moments));
if( !contour )
{
CV_CALL( mat = cvGetMat( mat, &stub, &coi ));
type = CV_MAT_TYPE( mat->type );
if( type == CV_32SC2 || type == CV_32FC2 )
{
CV_CALL( contour = cvPointSeqFromMat(
CV_SEQ_KIND_CURVE | CV_SEQ_FLAG_CLOSED,
mat, &contour_header, &block ));
}
}
if( contour )
{
icvContourMoments( contour, moments );
EXIT;
}
type = CV_MAT_TYPE( mat->type );
depth = CV_MAT_DEPTH( type );
cn = CV_MAT_CN( type );
pix_size = CV_ELEM_SIZE(type);
size = cvGetMatSize( mat );
if( cn > 1 && coi == 0 )
CV_ERROR( CV_StsBadArg, "Invalid image type" );
if( size.width <= 0 || size.height <= 0 )
{
EXIT;
}
if( type == CV_8UC1 )
ipp_func = (CvMomentIPPFunc)icvMoments_8u_C1R_p;
else if( type == CV_32FC1 )
ipp_func = (CvMomentIPPFunc)icvMoments_32f_C1R_p;
if( ipp_func && !binary )
{
int matstep = mat->step ? mat->step : CV_STUB_STEP;
IPPI_CALL( icvMomentInitAlloc_64f_p( &ippmomentstate, cvAlgHintAccurate ));
IPPI_CALL( ipp_func( mat->data.ptr, matstep, size, ippmomentstate ));
icvGetSpatialMoment_64f_p( ippmomentstate, 0, 0, 0, cvPoint(0,0), &moments->m00 );
icvGetSpatialMoment_64f_p( ippmomentstate, 1, 0, 0, cvPoint(0,0), &moments->m10 );
icvGetSpatialMoment_64f_p( ippmomentstate, 0, 1, 0, cvPoint(0,0), &moments->m01 );
icvGetSpatialMoment_64f_p( ippmomentstate, 2, 0, 0, cvPoint(0,0), &moments->m20 );
icvGetSpatialMoment_64f_p( ippmomentstate, 1, 1, 0, cvPoint(0,0), &moments->m11 );
icvGetSpatialMoment_64f_p( ippmomentstate, 0, 2, 0, cvPoint(0,0), &moments->m02 );
icvGetSpatialMoment_64f_p( ippmomentstate, 3, 0, 0, cvPoint(0,0), &moments->m30 );
icvGetSpatialMoment_64f_p( ippmomentstate, 2, 1, 0, cvPoint(0,0), &moments->m21 );
icvGetSpatialMoment_64f_p( ippmomentstate, 1, 2, 0, cvPoint(0,0), &moments->m12 );
icvGetSpatialMoment_64f_p( ippmomentstate, 0, 3, 0, cvPoint(0,0), &moments->m03 );
icvCompleteMomentState( moments );
EXIT;
}
func = (CvFunc2DnC_1A1P)(!binary ? mom_tab.fn_2d[depth] : mombin_tab.fn_2d[depth]);
if( !func )
CV_ERROR( CV_StsBadArg, cvUnsupportedFormat );
if( depth >= CV_32S && !binary )
tile_size = size;
else
tile_num = ((size.width + tile_size.width - 1)/tile_size.width)*
((size.height + tile_size.height - 1)/tile_size.height);
CV_CALL( tiles = (double*)cvAlloc( tile_num*10*sizeof(double)));
for( y = 0, k = 0; y < size.height; y += tile_size.height )
{
CvSize cur_tile_size = tile_size;
if( y + cur_tile_size.height > size.height )
cur_tile_size.height = size.height - y;
for( x = 0; x < size.width; x += tile_size.width, k++ )
{
if( x + cur_tile_size.width > size.width )
cur_tile_size.width = size.width - x;
assert( k < tile_num );
IPPI_CALL( func( mat->data.ptr + y*mat->step + x*pix_size,
mat->step, cur_tile_size, cn, coi, tiles + k*10 ));
}
}
icvAccumulateMoments( tiles, size, tile_size, moments );
__END__;
if( ippmomentstate )
icvMomentFree_64f_p( ippmomentstate );
cvFree( (void**)&tiles );
}
/*F///////////////////////////////////////////////////////////////////////////////////////
// Name: cvGetHuMoments
// Purpose: Returns Hu moments
// Context:
// Parameters:
// mState - moment structure filled by one of the icvMoments[Binary]*** function
// HuState - pointer to output structure containing seven Hu moments
// Returns:
// CV_NO_ERR if success or error code
// Notes:
//F*/
CV_IMPL void
cvGetHuMoments( CvMoments * mState, CvHuMoments * HuState )
{
CV_FUNCNAME( "cvGetHuMoments" );
__BEGIN__;
if( !mState || !HuState )
CV_ERROR_FROM_STATUS( CV_NULLPTR_ERR );
{
double m00s = mState->inv_sqrt_m00, m00 = m00s * m00s, s2 = m00 * m00, s3 = s2 * m00s;
double nu20 = mState->mu20 * s2,
nu11 = mState->mu11 * s2,
nu02 = mState->mu02 * s2,
nu30 = mState->mu30 * s3,
nu21 = mState->mu21 * s3, nu12 = mState->mu12 * s3, nu03 = mState->mu03 * s3;
double t0 = nu30 + nu12;
double t1 = nu21 + nu03;
double q0 = t0 * t0, q1 = t1 * t1;
double n4 = 4 * nu11;
double s = nu20 + nu02;
double d = nu20 - nu02;
HuState->hu1 = s;
HuState->hu2 = d * d + n4 * nu11;
HuState->hu4 = q0 + q1;
HuState->hu6 = d * (q0 - q1) + n4 * t0 * t1;
t0 *= q0 - 3 * q1;
t1 *= 3 * q0 - q1;
q0 = nu30 - 3 * nu12;
q1 = 3 * nu21 - nu03;
HuState->hu3 = q0 * q0 + q1 * q1;
HuState->hu5 = q0 * t0 + q1 * t1;
HuState->hu7 = q1 * t0 - q0 * t1;
}
__END__;
}
/*F///////////////////////////////////////////////////////////////////////////////////////
// Name: cvGetSpatialMoment
// Purpose: Returns spatial moment(x_order, y_order) which is determined as:
// m(x_o,y_o) = sum (x ^ x_o)*(y ^ y_o)*I(x,y)
// 0 <= x_o, y_o; x_o + y_o <= 3
// Context:
// Parameters:
// mom - moment structure filled by one of the icvMoments[Binary]*** function
// x_order - x order of the moment
// y_order - y order of the moment
// Returns:
// moment value or large negative number (-DBL_MAX) if error
// Notes:
//F*/
CV_IMPL double
cvGetSpatialMoment( CvMoments * moments, int x_order, int y_order )
{
int order = x_order + y_order;
double moment = -DBL_MAX;
CV_FUNCNAME( "cvGetSpatialMoment" );
__BEGIN__;
if( !moments )
CV_ERROR_FROM_STATUS( CV_NULLPTR_ERR );
if( (x_order | y_order) < 0 || order > 3 )
CV_ERROR_FROM_STATUS( CV_BADRANGE_ERR );
moment = (&(moments->m00))[order + (order >> 1) + (order > 2) * 2 + y_order];
__END__;
return moment;
}
/*F///////////////////////////////////////////////////////////////////////////////////////
// Name: cvGetCentralMoment
// Purpose: Returns central moment(x_order, y_order) which is determined as:
// mu(x_o,y_o) = sum ((x - xc)^ x_o)*((y - yc) ^ y_o)*I(x,y)
// 0 <= x_o, y_o; x_o + y_o <= 3,
// (xc, yc) = (m10/m00,m01/m00) - center of gravity
// Context:
// Parameters:
// mom - moment structure filled by one of the icvMoments[Binary]*** function
// x_order - x order of the moment
// y_order - y order of the moment
// Returns:
// moment value or large negative number (-DBL_MAX) if error
// Notes:
//F*/
CV_IMPL double
cvGetCentralMoment( CvMoments * moments, int x_order, int y_order )
{
int order = x_order + y_order;
double mu = 0;
CV_FUNCNAME( "cvGetCentralMoment" );
__BEGIN__;
if( !moments )
CV_ERROR_FROM_STATUS( CV_NULLPTR_ERR );
if( (x_order | y_order) < 0 || order > 3 )
CV_ERROR_FROM_STATUS( CV_BADRANGE_ERR );
if( order >= 2 )
{
mu = (&(moments->m00))[4 + order * 3 + y_order];
}
else if( order == 0 )
mu = moments->m00;
__END__;
return mu;
}
/*F///////////////////////////////////////////////////////////////////////////////////////
// Name: cvGetNormalizedCentralMoment
// Purpose: Returns normalized central moment(x_order,y_order) which is determined as:
// nu(x_o,y_o) = mu(x_o, y_o)/(m00 ^ (((x_o + y_o)/2) + 1))
// 0 <= x_o, y_o; x_o + y_o <= 3,
// (xc, yc) = (m10/m00,m01/m00) - center of gravity
// Context:
// Parameters:
// mom - moment structure filled by one of the icvMoments[Binary]*** function
// x_order - x order of the moment
// y_order - y order of the moment
// Returns:
// moment value or large negative number (-DBL_MAX) if error
// Notes:
//F*/
CV_IMPL double
cvGetNormalizedCentralMoment( CvMoments * moments, int x_order, int y_order )
{
int order = x_order + y_order;
double mu = 0;
double m00s, m00;
CV_FUNCNAME( "cvGetCentralNormalizedMoment" );
__BEGIN__;
mu = cvGetCentralMoment( moments, x_order, y_order );
CV_CHECK();
m00s = moments->inv_sqrt_m00;
m00 = m00s * m00s;
while( --order >= 0 )
m00 *= m00s;
mu *= m00;
__END__;
return mu;
}
/* End of file. */
| [
"[email protected]"
]
| [
[
[
1,
686
]
]
]
|
aa0c2eaa93c8db16bd994fbad373357276fe55cd | 184455acbcc5ee6b2ee0c77c66b436375e1171e9 | /src/Ship.cpp | 7fd5a9a98cbdd1b11360dac5f9f1fcfc1c6f5387 | []
| no_license | Karkasos/Core512 | d996d40e57be899e6c4c9aec106e371356152b36 | b83151ab284b7cf2e058fdd218dcc676946f43aa | refs/heads/master | 2020-04-07T14:19:51.907224 | 2011-11-01T06:46:20 | 2011-11-01T06:46:20 | 2,753,621 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,840 | cpp | #include "Core512.h"
#include "Ship.h"
Ship::Ship(HTEXTURE hTexture) : DynBody(Vertex(), hTexture), hTexture(hTexture)
{
EngineForce = 100.0f;
Alignment.x = 0;
Alignment.y = 1;
Body::Move(Rect.w, Rect.h);
lpParticle[0] = new ParticleSys();
lpParticle[1] = new ParticleSys();
lpExplosion = new Explosion();
}
Ship::~Ship()
{
DeleteNull(lpParticle[0]);
DeleteNull(lpParticle[1]);
DeleteNull(lpExplosion);
}
void Ship::Turn(int dRotate)
{
float RotateRad = CoreRad32 * 60;
float Delta = exHGE->Timer_GetDelta();
if(dRotate)
{
RotateRad *= dRotate * Delta;
Alignment.x = 0;
Alignment.y = 1;
Body::RotationOffset(RotateRad);
RotateRad = Body::RotationRadian;
Alignment.Rotate(RotateRad);
Alignment.StabilizeEpsilon();
}
}
//direction cound be -1, or 1
void Ship::Thrust(int ForceDirection)
{
Vertex Force;
if(ForceDirection)
{
Force.x = ForceDirection * EngineForce * Alignment.x;
Force.y = ForceDirection * EngineForce * Alignment.y;
ApplyForce(Force);
}
}
void Ship::Update()
{
DynBody::Update();
Vertex pp[2];
pp[0].x = Rect.x1 - Rect.cx + 16;
pp[0].y = Rect.y2 - Rect.cy - 8;
pp[1].x = Rect.x2 - Rect.cx - 16;
pp[1].y = Rect.y2 - Rect.cy - 8;
pp[0].Rotate(RotationRadian);
pp[1].Rotate(RotationRadian);
pp[0].x += Rect.cx;
pp[0].y += Rect.cy;
pp[1].x += Rect.cx;
pp[1].y += Rect.cy;
lpParticle[0]->Update(pp[0].x, pp[0].y, RotationRadian + CoreRad4 + CoreRad16);
lpParticle[1]->Update(pp[1].x, pp[1].y, RotationRadian + CoreRad4 - CoreRad16);
lpExplosion->Update();
}
void Ship::Explode()
{
lpExplosion->Play();
}
void Ship::Render()
{
Body::Render();
lpParticle[0]->Render();
lpParticle[1]->Render();
if(lpExplosion->IsPlaying())
lpExplosion->Render(Rect.cx, Rect.cy);
}
| [
"[email protected]"
]
| [
[
[
1,
91
]
]
]
|
5fbdfee87cb1112fa94e56ec2f0aff5a13158288 | 22d9640edca14b31280fae414f188739a82733e4 | /Code/VTK/include/vtk-5.2/vtkCompositeDataIterator.h | da0c14e20737e499a1bb4e742d5dfc8e6aeb8580 | []
| no_license | tack1/Casam | ad0a98febdb566c411adfe6983fcf63442b5eed5 | 3914de9d34c830d4a23a785768579bea80342f41 | refs/heads/master | 2020-04-06T03:45:40.734355 | 2009-06-10T14:54:07 | 2009-06-10T14:54:07 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 5,851 | h | /*=========================================================================
Program: Visualization Toolkit
Module: $RCSfile: vtkCompositeDataIterator.h,v $
Copyright (c) Ken Martin, Will Schroeder, Bill Lorensen
All rights reserved.
See Copyright.txt or http://www.kitware.com/Copyright.htm for details.
This software is distributed WITHOUT ANY WARRANTY; without even
the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR
PURPOSE. See the above copyright notice for more information.
=========================================================================*/
// .NAME vtkCompositeDataIterator - superclass for composite data iterators
// .SECTION Description
// vtkCompositeDataIterator provides an interface for accessing datasets
// in a collection (vtkCompositeDataIterator).
#ifndef __vtkCompositeDataIterator_h
#define __vtkCompositeDataIterator_h
#include "vtkObject.h"
class vtkCompositeDataSet;
class vtkCompositeDataSetInternals;
class vtkCompositeDataSetIndex;
class vtkDataObject;
class vtkInformation;
class VTK_FILTERING_EXPORT vtkCompositeDataIterator : public vtkObject
{
public:
static vtkCompositeDataIterator* New();
vtkTypeRevisionMacro(vtkCompositeDataIterator, vtkObject);
void PrintSelf(ostream& os, vtkIndent indent);
// Description:
// Set the composite dataset this iterator is iterating over.
// Must be set before traversal begins.
virtual void SetDataSet(vtkCompositeDataSet* ds);
vtkGetObjectMacro(DataSet, vtkCompositeDataSet);
// Description:
// Begin iterating over the composite dataset structure.
virtual void InitTraversal();
// Description:
// Begin iterating over the composite dataset structure in reverse order.
virtual void InitReverseTraversal();
// Description:
// Move the iterator to the beginning of the collection.
virtual void GoToFirstItem();
// Description:
// Move the iterator to the next item in the collection.
virtual void GoToNextItem();
// Description:
// Test whether the iterator is currently pointing to a valid item. Returns 1
// for yes, and 0 for no.
virtual int IsDoneWithTraversal();
// Description:
// Returns the current item. Valid only when IsDoneWithTraversal() returns 0.
virtual vtkDataObject* GetCurrentDataObject();
// Description:
// Returns the meta-data associated with the current item. This will allocate
// a new vtkInformation object is none is already present. Use
// HasCurrentMetaData to avoid unnecessary creation of vtkInformation objects.
virtual vtkInformation* GetCurrentMetaData();
// Description:
// Returns if the a meta-data information object is present for the current
// item. Return 1 on success, 0 otherwise.
virtual int HasCurrentMetaData();
// Description:
// If VisitOnlyLeaves is true, the iterator will only visit nodes
// (sub-datasets) that are not composite. If it encounters a composite
// data set, it will automatically traverse that composite dataset until
// it finds non-composite datasets. With this options, it is possible to
// visit all non-composite datasets in tree of composite datasets
// (composite of composite of composite for example :-) ) If
// VisitOnlyLeaves is false, GetCurrentDataObject() may return
// vtkCompositeDataSet. By default, VisitOnlyLeaves is 1.
vtkSetMacro(VisitOnlyLeaves, int);
vtkGetMacro(VisitOnlyLeaves, int);
vtkBooleanMacro(VisitOnlyLeaves, int);
// Description:
// If TraverseSubTree is set to true, the iterator will visit the entire tree
// structure, otherwise it only visits the first level children. Set to 1 by
// default.
vtkSetMacro(TraverseSubTree, int);
vtkGetMacro(TraverseSubTree, int);
vtkBooleanMacro(TraverseSubTree, int);
// Description:
// If SkipEmptyNodes is true, then NULL datasets will be skipped. Default is
// true.
vtkSetMacro(SkipEmptyNodes, int);
vtkGetMacro(SkipEmptyNodes, int);
vtkBooleanMacro(SkipEmptyNodes, int);
// Description:
// Flat index is an index obtained by traversing the tree in preorder.
// This can be used to uniquely identify nodes in the tree.
// Not valid if IsDoneWithTraversal() returns true.
unsigned int GetCurrentFlatIndex();
// Description:
// Returns if the iteration is in reverse order.
vtkGetMacro(Reverse, int);
//BTX
protected:
vtkCompositeDataIterator();
virtual ~vtkCompositeDataIterator();
// Takes the current location to the next dataset. This traverses the tree in
// preorder fashion.
// If the current location is a composite dataset, next is its 1st child dataset.
// If the current is not a composite dataset, then next is the next dataset.
// This method gives no guarantees whether the current dataset will be
// non-null or leaf.
void NextInternal();
// Description:
// Returns the index for the current data object.
vtkCompositeDataSetIndex GetCurrentIndex();
// Needs access to GetCurrentIndex().
friend class vtkCompositeDataSet;
unsigned int CurrentFlatIndex;
int SkipEmptyNodes;
int TraverseSubTree;
int Reverse;
int VisitOnlyLeaves;
vtkCompositeDataSet* DataSet;
private:
vtkCompositeDataIterator(const vtkCompositeDataIterator&); // Not implemented.
void operator=(const vtkCompositeDataIterator&); // Not implemented.
class vtkInternals;
vtkInternals* Internals;
friend class vtkInternals;
// Description:
// Helper method used by vtkInternals to get access to the internals of
// vtkCompositeDataSet.
vtkCompositeDataSetInternals* GetInternals(vtkCompositeDataSet*);
// Cannot be called when this->IsDoneWithTraversal() return 1.
void UpdateLocation();
//ETX
};
#endif
| [
"nnsmit@9b22acdf-97ab-464f-81e2-08fcc4a6931f"
]
| [
[
[
1,
165
]
]
]
|
ac71c1945592e5c09560154ef521f4b961becf00 | a92598d0a8a2e92b424915d2944212f2f13e7506 | /PtRPG/PhotonLib/Common-cpp/inc/UTF8String.h | a533745fa6248e5898c05b5f50a122c7593e33a8 | [
"MIT"
]
| permissive | peteo/RPG_Learn | 0cc4facd639bd01d837ac56cf37a07fe22c59211 | 325fd1802b14e055732278f3d2d33a9577608c39 | refs/heads/master | 2021-01-23T11:07:05.050645 | 2011-12-12T08:47:27 | 2011-12-12T08:47:27 | 2,299,148 | 2 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,263 | h | /* Exit Games Common - C++ Client Lib
* Copyright (C) 2004-2011 by Exit Games GmbH. All rights reserved.
* http://www.exitgames.com
* mailto:[email protected]
*/
#ifndef __UTF8_STRING_H
#define __UTF8_STRING_H
#include "BaseCharString.h"
#ifndef _EG_BREW_PLATFORM
namespace ExitGames
{
#endif
/* Summary
The UTF8String class is a container class for char* strings, encoded with UTF8.
Description
This is the UTF8 implementation of <link BaseCharString>.
Please look at the doc of the abstract base class for more information.*/
class UTF8String : protected BaseCharString
{
public:
UTF8String(void);
UTF8String(const UTF8String& wstr);
UTF8String(const JString& wstr);
UTF8String(const char* str);
UTF8String(const EG_CHAR* wstr);
~UTF8String(void);
UTF8String& operator=(const UTF8String& Rhs);
UTF8String& operator=(const JString& Rhs);
UTF8String& operator=(const char* Rhs);
UTF8String& operator=(const EG_CHAR* Rhs);
operator const char* (void) const;
operator const EG_CHAR* (void) const;
operator JString (void) const;
const char* cstr(void) const;
JString JStringRepresentation(void) const;
};
#ifndef _EG_BREW_PLATFORM
}
#endif
#endif
| [
"[email protected]"
]
| [
[
[
1,
49
]
]
]
|
e57cff0afb8cbc28a1a953dbcb44296cb55bbfe1 | cf579692f2e289563160b6a218fa5f1b6335d813 | /XBtool/XBtool.h | d283ce840e5172f5dc8b735939c70c98ad06d93d | []
| no_license | opcow/XBtool | a7451971de3296e1ce5632b0c9d95430f6d3b223 | 718a7fbf87e08c12c0c829dd2e2c0d6cee967cbe | refs/heads/master | 2021-01-16T21:02:17.759102 | 2011-03-09T23:36:54 | 2011-03-09T23:36:54 | 1,461,420 | 8 | 2 | null | null | null | null | UTF-8 | C++ | false | false | 1,485 | h | //////////////////////////////////////////////////////////////////////////////
// XBtool - Xbox BIOS pack/unpack/patch tool
// Copyright (C) 2003 Mitch Crane
//
// This program is free software; you can redistribute it and/or
// modify it under the terms of the GNU General Public License
// as published by the Free Software Foundation; either version 2
// of the License, or (at your option) any later version.
//
// This program is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU General Public License for more details.
//
// You should have received a copy of the GNU General Public License
// along with this program; if not, write to the Free Software
// Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.
//////////////////////////////////////////////////////////////////////////////
// XBtool.h : main header file for the PROJECT_NAME application
//
#pragma once
#ifndef __AFXWIN_H__
#error include 'stdafx.h' before including this file for PCH
#endif
#include "resource.h" // main symbols
// CXBtoolApp:
// See XBtool.cpp for the implementation of this class
//
class CXBtoolApp : public CWinApp
{
public:
CXBtoolApp();
// Overrides
public:
virtual BOOL InitInstance();
// Implementation
DECLARE_MESSAGE_MAP()
};
extern CXBtoolApp theApp;
| [
"[email protected]"
]
| [
[
[
1,
51
]
]
]
|
3b3e4fa2c3073626e245490ca797c910017efc73 | 709cd826da3ae55945fd7036ecf872ee7cdbd82a | /Term/Assignment/CG_2nd/FileView.cpp | 7577fec5fe0501501e333f3fd151f68c84cd63c6 | []
| no_license | argapratama/kucgbowling | 20dbaefe1596358156691e81ccceb9151b15efb0 | 65e40b6f33c5511bddf0fa350c1eefc647ace48a | refs/heads/master | 2018-01-08T15:27:44.784437 | 2011-06-19T15:23:39 | 2011-06-19T15:23:39 | 36,738,655 | 0 | 0 | null | null | null | null | UHC | C++ | false | false | 7,063 | cpp |
#include "stdafx.h"
#include "mainfrm.h"
#include "FileView.h"
#include "Resource.h"
#include "CG_2nd.h"
#ifdef _DEBUG
#undef THIS_FILE
static char THIS_FILE[]=__FILE__;
#define new DEBUG_NEW
#endif
/////////////////////////////////////////////////////////////////////////////
// CFileView
CFileView::CFileView()
{
}
CFileView::~CFileView()
{
}
BEGIN_MESSAGE_MAP(CFileView, CDockablePane)
ON_WM_CREATE()
ON_WM_SIZE()
ON_WM_CONTEXTMENU()
ON_COMMAND(ID_PROPERTIES, OnProperties)
ON_COMMAND(ID_OPEN, OnFileOpen)
ON_COMMAND(ID_OPEN_WITH, OnFileOpenWith)
ON_COMMAND(ID_DUMMY_COMPILE, OnDummyCompile)
ON_COMMAND(ID_EDIT_CUT, OnEditCut)
ON_COMMAND(ID_EDIT_COPY, OnEditCopy)
ON_COMMAND(ID_EDIT_CLEAR, OnEditClear)
ON_WM_PAINT()
ON_WM_SETFOCUS()
END_MESSAGE_MAP()
/////////////////////////////////////////////////////////////////////////////
// CWorkspaceBar 메시지 처리기
int CFileView::OnCreate(LPCREATESTRUCT lpCreateStruct)
{
if (CDockablePane::OnCreate(lpCreateStruct) == -1)
return -1;
CRect rectDummy;
rectDummy.SetRectEmpty();
// 뷰를 만듭니다.
const DWORD dwViewStyle = WS_CHILD | WS_VISIBLE | TVS_HASLINES | TVS_LINESATROOT | TVS_HASBUTTONS;
if (!m_wndFileView.Create(dwViewStyle, rectDummy, this, 4))
{
TRACE0("파일 뷰를 만들지 못했습니다.\n");
return -1; // 만들지 못했습니다.
}
// 뷰 이미지를 로드합니다.
m_FileViewImages.Create(IDB_FILE_VIEW, 16, 0, RGB(255, 0, 255));
m_wndFileView.SetImageList(&m_FileViewImages, TVSIL_NORMAL);
m_wndToolBar.Create(this, AFX_DEFAULT_TOOLBAR_STYLE, IDR_EXPLORER);
m_wndToolBar.LoadToolBar(IDR_EXPLORER, 0, 0, TRUE /* 잠금 */);
OnChangeVisualStyle();
m_wndToolBar.SetPaneStyle(m_wndToolBar.GetPaneStyle() | CBRS_TOOLTIPS | CBRS_FLYBY);
m_wndToolBar.SetPaneStyle(m_wndToolBar.GetPaneStyle() & ~(CBRS_GRIPPER | CBRS_SIZE_DYNAMIC | CBRS_BORDER_TOP | CBRS_BORDER_BOTTOM | CBRS_BORDER_LEFT | CBRS_BORDER_RIGHT));
m_wndToolBar.SetOwner(this);
// 모든 명령은 부모 프레임이 아닌 이 컨트롤을 통해 라우팅됩니다.
m_wndToolBar.SetRouteCommandsViaFrame(FALSE);
// 정적 트리 뷰 데이터를 더미 코드로 채웁니다.
FillFileView();
AdjustLayout();
return 0;
}
void CFileView::OnSize(UINT nType, int cx, int cy)
{
CDockablePane::OnSize(nType, cx, cy);
AdjustLayout();
}
void CFileView::FillFileView()
{
HTREEITEM hRoot = m_wndFileView.InsertItem(_T("FakeApp 파일"), 0, 0);
m_wndFileView.SetItemState(hRoot, TVIS_BOLD, TVIS_BOLD);
HTREEITEM hSrc = m_wndFileView.InsertItem(_T("FakeApp 소스 파일"), 0, 0, hRoot);
m_wndFileView.InsertItem(_T("FakeApp.cpp"), 1, 1, hSrc);
m_wndFileView.InsertItem(_T("FakeApp.rc"), 1, 1, hSrc);
m_wndFileView.InsertItem(_T("FakeAppDoc.cpp"), 1, 1, hSrc);
m_wndFileView.InsertItem(_T("FakeAppView.cpp"), 1, 1, hSrc);
m_wndFileView.InsertItem(_T("MainFrm.cpp"), 1, 1, hSrc);
m_wndFileView.InsertItem(_T("StdAfx.cpp"), 1, 1, hSrc);
HTREEITEM hInc = m_wndFileView.InsertItem(_T("FakeApp 헤더 파일"), 0, 0, hRoot);
m_wndFileView.InsertItem(_T("FakeApp.h"), 2, 2, hInc);
m_wndFileView.InsertItem(_T("FakeAppDoc.h"), 2, 2, hInc);
m_wndFileView.InsertItem(_T("FakeAppView.h"), 2, 2, hInc);
m_wndFileView.InsertItem(_T("Resource.h"), 2, 2, hInc);
m_wndFileView.InsertItem(_T("MainFrm.h"), 2, 2, hInc);
m_wndFileView.InsertItem(_T("StdAfx.h"), 2, 2, hInc);
HTREEITEM hRes = m_wndFileView.InsertItem(_T("FakeApp 리소스 파일"), 0, 0, hRoot);
m_wndFileView.InsertItem(_T("FakeApp.ico"), 2, 2, hRes);
m_wndFileView.InsertItem(_T("FakeApp.rc2"), 2, 2, hRes);
m_wndFileView.InsertItem(_T("FakeAppDoc.ico"), 2, 2, hRes);
m_wndFileView.InsertItem(_T("FakeToolbar.bmp"), 2, 2, hRes);
m_wndFileView.Expand(hRoot, TVE_EXPAND);
m_wndFileView.Expand(hSrc, TVE_EXPAND);
m_wndFileView.Expand(hInc, TVE_EXPAND);
}
void CFileView::OnContextMenu(CWnd* pWnd, CPoint point)
{
CTreeCtrl* pWndTree = (CTreeCtrl*) &m_wndFileView;
ASSERT_VALID(pWndTree);
if (pWnd != pWndTree)
{
CDockablePane::OnContextMenu(pWnd, point);
return;
}
if (point != CPoint(-1, -1))
{
// 클릭한 항목을 선택합니다.
CPoint ptTree = point;
pWndTree->ScreenToClient(&ptTree);
UINT flags = 0;
HTREEITEM hTreeItem = pWndTree->HitTest(ptTree, &flags);
if (hTreeItem != NULL)
{
pWndTree->SelectItem(hTreeItem);
}
}
pWndTree->SetFocus();
theApp.GetContextMenuManager()->ShowPopupMenu(IDR_POPUP_EXPLORER, point.x, point.y, this, TRUE);
}
void CFileView::AdjustLayout()
{
if (GetSafeHwnd() == NULL)
{
return;
}
CRect rectClient;
GetClientRect(rectClient);
int cyTlb = m_wndToolBar.CalcFixedLayout(FALSE, TRUE).cy;
m_wndToolBar.SetWindowPos(NULL, rectClient.left, rectClient.top, rectClient.Width(), cyTlb, SWP_NOACTIVATE | SWP_NOZORDER);
m_wndFileView.SetWindowPos(NULL, rectClient.left + 1, rectClient.top + cyTlb + 1, rectClient.Width() - 2, rectClient.Height() - cyTlb - 2, SWP_NOACTIVATE | SWP_NOZORDER);
}
void CFileView::OnProperties()
{
AfxMessageBox(_T("속성...."));
}
void CFileView::OnFileOpen()
{
// TODO: 여기에 명령 처리기 코드를 추가합니다.
}
void CFileView::OnFileOpenWith()
{
// TODO: 여기에 명령 처리기 코드를 추가합니다.
}
void CFileView::OnDummyCompile()
{
// TODO: 여기에 명령 처리기 코드를 추가합니다.
}
void CFileView::OnEditCut()
{
// TODO: 여기에 명령 처리기 코드를 추가합니다.
}
void CFileView::OnEditCopy()
{
// TODO: 여기에 명령 처리기 코드를 추가합니다.
}
void CFileView::OnEditClear()
{
// TODO: 여기에 명령 처리기 코드를 추가합니다.
}
void CFileView::OnPaint()
{
CPaintDC dc(this); // 그리기를 위한 디바이스 컨텍스트입니다.
CRect rectTree;
m_wndFileView.GetWindowRect(rectTree);
ScreenToClient(rectTree);
rectTree.InflateRect(1, 1);
dc.Draw3dRect(rectTree, ::GetSysColor(COLOR_3DSHADOW), ::GetSysColor(COLOR_3DSHADOW));
}
void CFileView::OnSetFocus(CWnd* pOldWnd)
{
CDockablePane::OnSetFocus(pOldWnd);
m_wndFileView.SetFocus();
}
void CFileView::OnChangeVisualStyle()
{
m_wndToolBar.CleanUpLockedImages();
m_wndToolBar.LoadBitmap(theApp.m_bHiColorIcons ? IDB_EXPLORER_24 : IDR_EXPLORER, 0, 0, TRUE /* 잠금 */);
m_FileViewImages.DeleteImageList();
UINT uiBmpId = theApp.m_bHiColorIcons ? IDB_FILE_VIEW_24 : IDB_FILE_VIEW;
CBitmap bmp;
if (!bmp.LoadBitmap(uiBmpId))
{
TRACE(_T("비트맵을 로드할 수 없습니다. %x\n"), uiBmpId);
ASSERT(FALSE);
return;
}
BITMAP bmpObj;
bmp.GetBitmap(&bmpObj);
UINT nFlags = ILC_MASK;
nFlags |= (theApp.m_bHiColorIcons) ? ILC_COLOR24 : ILC_COLOR4;
m_FileViewImages.Create(16, bmpObj.bmHeight, nFlags, 0, 0);
m_FileViewImages.Add(&bmp, RGB(255, 0, 255));
m_wndFileView.SetImageList(&m_FileViewImages, TVSIL_NORMAL);
}
| [
"[email protected]"
]
| [
[
[
1,
256
]
]
]
|
5829c46cc849a53ae927768efaaec23492725b9c | c95a83e1a741b8c0eb810dd018d91060e5872dd8 | /Game/ObjectDLL/ObjectShared/AIHumanStrategyShootStream.cpp | ccf0d2df56b08dbc25139dc7e3062d507ba66fbf | []
| no_license | rickyharis39/nolf2 | ba0b56e2abb076e60d97fc7a2a8ee7be4394266c | 0da0603dc961e73ac734ff365bfbfb8abb9b9b04 | refs/heads/master | 2021-01-01T17:21:00.678517 | 2011-07-23T12:11:19 | 2011-07-23T12:11:19 | 38,495,312 | 1 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 12,699 | cpp |
//----------------------------------------------------------------------------
//
// MODULE: AIHumanStrategyShootStream.cpp
//
// PURPOSE: - implementation
//
// CREATED: 04.04.2002
//
// (c) 2002 Monolith Productions, Inc. All Rights Reserved
//
//
// COMMENTS: Handles firing when it comes in a constant stream instead of
// in a burst. A stream has a Start, Hold and Finish animation
// IsFiring() is true as long as the beam is being emitted.
//
// TODO: Currently, the first anim and part of the second
// anim are garenteed. The third anim may be skipped due
// to a goal or state change.
//
// Hook streaming fire up to work with running characters.
//
//----------------------------------------------------------------------------
// Includes
#include "stdafx.h"
#include "AIHumanStrategyShootStream.h"
#include "AIHuman.h"
#include "WeaponFireInfo.h"
#include "Weapon.h"
#include "AIUtils.h"
#include "AIMovement.h"
// Forward declarations
// Globals
// Statics
DEFINE_AI_FACTORY_CLASS_SPECIFIC(Strategy, CAIHumanStrategyShootStream, kStrat_HumanShootStream);
const static LTFLOAT s_fPerturbScale = 4.0f;
//----------------------------------------------------------------------------
//
// ROUTINE: CAIHumanStrategyShootStream::CAIHumanStrategyShootStream()
//
// PURPOSE:
//
//----------------------------------------------------------------------------
CAIHumanStrategyShootStream::CAIHumanStrategyShootStream() :
m_bFiringStream( LTFALSE ),
m_flStreamTime( 0 )
{
}
//----------------------------------------------------------------------------
//
// ROUTINE: CAIHumanStrategyShootStream::Save()
//
// PURPOSE:
//
//----------------------------------------------------------------------------
/*virtual*/ void CAIHumanStrategyShootStream::Save(ILTMessage_Write *pMsg)
{
CAIHumanStrategyShoot::Save(pMsg);
SAVE_BOOL(m_bFiringStream);
SAVE_TIME(m_flStreamTime);
}
//----------------------------------------------------------------------------
//
// ROUTINE: CAIHumanStrategyShootStream::Load()
//
// PURPOSE:
//
//----------------------------------------------------------------------------
/*virtual*/ void CAIHumanStrategyShootStream::Load(ILTMessage_Read *pMsg)
{
CAIHumanStrategyShoot::Load(pMsg);
LOAD_BOOL(m_bFiringStream);
LOAD_TIME(m_flStreamTime);
}
//----------------------------------------------------------------------------
//
// ROUTINE: CAIHumanStrategyShootStream::Init()
//
// PURPOSE: Handle the initialization of the StreamTime code
//
//----------------------------------------------------------------------------
LTBOOL CAIHumanStrategyShootStream::Init(CAIHuman* pAIHuman)
{
AIASSERT( pAIHuman, NULL, "CAIHumanStrategyShootStream::Init: No human specified" );
if ( !CAIHumanStrategyShoot::Init(pAIHuman) )
{
return LTFALSE;
}
m_eFireState = eFireStateInvalid;
// All recalculations of the burst firing now handled
// by this function to reduce duplication
CalculateStreamTime();
return LTTRUE;
}
//----------------------------------------------------------------------------
//
// ROUTINE: CAIHumanStrategyShootStream::Fire()
//
// PURPOSE: Hook into the Fire() function so that we can start our special
// handling of the firing.
//
//----------------------------------------------------------------------------
/*virtual*/ void CAIHumanStrategyShootStream::Fire()
{
CAIHumanStrategyShoot::Fire();
if ( eFireStateInvalid == m_eFireState )
{
m_eFireState = eFireStateStart;
m_bFiringStream = LTTRUE;
}
}
//----------------------------------------------------------------------------
//
// ROUTINE: CAIHumanStrategyShootStream::UpdateFiring()
//
// PURPOSE: Updates the firing state, first allowing the base class to
// handle the basics, then extending it to check the animation
// lock state for handling progression from eFireStateStart to
// eFireStateFiring.
//
//----------------------------------------------------------------------------
/*virtual*/ void CAIHumanStrategyShootStream::UpdateFiring(HOBJECT hTarget,const LTVector& vTargetPos, CWeapon* pWeapon)
{
AIASSERT( LTTRUE == m_bFired, GetAI()->GetHOBJECT(), "Expected Fired to be true. Check logic.");
switch ( m_eFireState )
{
case eFireStateStart:
{
if ( !GetAI()->GetAnimationContext()->IsLocked() )
{
m_eFireState = eFireStateFiring;
}
}
break;
case eFireStateFiring:
{
// Get our fire position
AIASSERT( GetAI()->GetCurrentWeapon(), GetAI()->m_hObject, "UpdateFiring without a weapon" );
LTVector vFirePos = GetFirePosition(GetAI()->GetCurrentWeapon());
// Now fire the weapon
WeaponFireInfo weaponFireInfo;
weaponFireInfo.nDiscTrackingType = MPROJ_DISC_TRACKING_STEADY;
weaponFireInfo.hSocket = m_hFiringSocket!=INVALID_MODEL_SOCKET ? m_hFiringSocket : GetAI()->GetWeaponSocket(GetAI()->GetCurrentWeapon());
weaponFireInfo.hFiredFrom = GetAI()->GetObject();
weaponFireInfo.vPath = vTargetPos - vFirePos;
weaponFireInfo.vFirePos = vFirePos;
weaponFireInfo.vFlashPos = vFirePos;
weaponFireInfo.hTestObj = hTarget;
weaponFireInfo.fPerturbR = LOWER_BY_DIFFICULTY(s_fPerturbScale)*(1.0f - GetAI()->GetAccuracy());
weaponFireInfo.fPerturbU = LOWER_BY_DIFFICULTY(s_fPerturbScale)*(1.0f - GetAI()->GetAccuracy());
pWeapon->UpdateWeapon(weaponFireInfo, LTTRUE);
Fire();
// Check to see our fire timer expired
if ( m_flStreamTime < g_pLTServer->GetTime() || !GetAI()->GetAnimationContext()->IsLocked())
{
m_eFireState = eFireStateEnding;
}
}
break;
case eFireStateEnding:
{
if ( !GetAI()->GetAnimationContext()->IsLocked() )
{
m_eFireState = eFireStateInvalid;
m_bFiringStream = LTFALSE;
m_eState = eStateAiming;
return;
}
}
break;
default:
{
AIASSERT( 0, m_pAIHuman->GetHOBJECT(), "CAIHumanStrategyShootStream::UpdateAnimation: Unexpected m_eFireState");
}
break;
}
}
//----------------------------------------------------------------------------
//
// ROUTINE: CAIHumanStrategyShootStream::UpdateAiming()
//
// PURPOSE:
//
//----------------------------------------------------------------------------
/*virtual*/ void CAIHumanStrategyShootStream::UpdateAiming(HOBJECT hTarget)
{
if ( m_flStreamTime < g_pLTServer->GetTime() )
{
// Don't calculate new stream time until finished firing animation.
if( !GetAnimationContext()->IsLocked() )
{
CalculateStreamTime();
}
Aim();
}
else
{
// We're done waiting, fire if we're at a reasonable angle
if ( m_bIgnoreFOV )
{
Fire();
}
else
{
LTVector vTargetPos;
g_pLTServer->GetObjectPos(hTarget, &vTargetPos);
LTVector vDir = vTargetPos - GetAI()->GetPosition();
vDir.y = 0.0f;
vDir.Normalize();
if ( vDir.Dot(GetAI()->GetTorsoForward()) < 0.70f )
{
Aim();
}
else
{
Fire();
}
}
}
}
//----------------------------------------------------------------------------
//
// ROUTINE: CAIHumanStrategyShootStream::HandleFired()
//
// PURPOSE: Turn on the stream. Unlike standard firing, it does not go off
// until either we run out of ammo, or until we decide to cut it
// off based on time or some other such consideration.
//
//----------------------------------------------------------------------------
/*virtual*/ void CAIHumanStrategyShootStream::HandleFired(const char* const pszSocketName)
{
CAIHumanStrategyShoot::HandleFired(pszSocketName);
Fire();
}
//----------------------------------------------------------------------------
//
// ROUTINE: CAIHumanStrategyShootStream::HandleFired()
//
// PURPOSE: Allow the base class to handle the Fire string. Handle the
// stream nature of the firing through the overridden HandleFired
// function.
//
// Handle the 'StopFiring' command here.
//
//----------------------------------------------------------------------------
/*virtual*/ void CAIHumanStrategyShootStream::HandleModelString(ArgList* pArgList)
{
CAIHumanStrategyShoot::HandleModelString(pArgList);
if ( !pArgList || !pArgList->argv || pArgList->argc == 0 ) return;
char* szKey = pArgList->argv[0];
if ( !szKey ) return;
if ( !_stricmp(szKey, c_szKeyStopFireWeapon) )
{
m_eFireState = eFireStateEnding;
}
}
// ----------------------------------------------------------------------- //
//
// ROUTINE: CAIHumanStrategyShoot::UpdateAnimation
//
// PURPOSE: Handles any pending AnimationContext specializations.
// Extends the base class and makes the following assumptions:
// 1) Animations are being locked by the base class.
//
// ----------------------------------------------------------------------- //
LTBOOL CAIHumanStrategyShootStream::UpdateAnimation()
{
if( !CAIHumanStrategyShoot::UpdateAnimation() )
{
return LTFALSE;
}
switch ( m_eFireState )
{
case eFireStateStart:
{
// If we are in the fire state, and if our animation is not locked,
// then make sure it is cleared fully. Rely on the base class to
// handle the initial locking.
if( GetAI()->GetCurrentWeapon() == GetAI()->GetPrimaryWeapon() )
{
GetAnimationContext()->SetProp(kAPG_WeaponAction, kAP_FireStreamStart);
}
else
{
GetAnimationContext()->SetProp(kAPG_WeaponAction, kAP_FireSecondaryStreamStart);
}
GetAnimationContext()->Lock();
}
break;
case eFireStateFiring:
{
// Streaming attacks are NEVER garenteed to play all the way through -- we want
// tighter control over them than the animation will give us. BUT we want to also
// have the ability to kick out when the animation ends UNLESS the animation is
// looping.
if( GetAI()->GetCurrentWeapon() == GetAI()->GetPrimaryWeapon() )
{
GetAnimationContext()->SetProp(kAPG_WeaponAction, kAP_FireStream);
}
else
{
GetAnimationContext()->SetProp(kAPG_WeaponAction, kAP_FireSecondaryStream);
}
GetAnimationContext()->Lock();
}
break;
case eFireStateEnding:
{
if( GetAI()->GetCurrentWeapon() == GetAI()->GetPrimaryWeapon() )
{
GetAnimationContext()->SetProp(kAPG_WeaponAction, kAP_FireStreamEnd);
}
else
{
GetAnimationContext()->SetProp(kAPG_WeaponAction, kAP_FireSecondaryStreamEnd);
}
GetAnimationContext()->Lock();
}
break;
case eFireStateInvalid:
{
// we are not in one of the basic firing states, so don't do anything special
;
}
break;
default:
{
AIASSERT( 0, GetAI()->GetHOBJECT(), "CAIHumanStrategyShootStream::UpdateAnimation: Unexpected m_eFireState" );
}
break;
}
return LTTRUE;
}
//----------------------------------------------------------------------------
//
// ROUTINE: CAIHumanStrategyShootStream::CalculateStreamTime()
//
// PURPOSE: Calculate how long we should next fire a stream for.
//
//----------------------------------------------------------------------------
void CAIHumanStrategyShootStream::CalculateStreamTime()
{
CWeapon* pWeapon = GetAI()->GetCurrentWeapon();
AIASSERT( pWeapon && pWeapon->GetWeaponData(), m_pAIHuman->GetHOBJECT(), "" );
if ( !pWeapon || ( pWeapon && !pWeapon->GetWeaponData()) )
{
return;
}
m_flStreamTime = g_pLTServer->GetTime() + GetRandom(pWeapon->GetWeaponData()->fAIMinBurstInterval, pWeapon->GetWeaponData()->fAIMaxBurstInterval);
}
//----------------------------------------------------------------------------
//
// ROUTINE: CAIHumanStrategyFollowPath::DelayChangeState()
//
// PURPOSE: Delay a state change as long as
//
//----------------------------------------------------------------------------
/*virtual*/ LTBOOL CAIHumanStrategyShootStream::DelayChangeState()
{
if ( m_eFireState == eFireStateStart || m_eFireState == eFireStateFiring )
{
return LTTRUE;
}
return CAIHumanStrategyShoot::DelayChangeState();
}
| [
"[email protected]"
]
| [
[
[
1,
423
]
]
]
|
be6d3f499d622b9fe5db1bd37a6aac969e3a2eab | 8f1601062c4a5452f2bdd0f75f3d12a79b98ba62 | /examples/aegis/me519/sg/glui_v2_1_beta/example5.cpp | 5cf2a8775f1ec42f512caf8327d5863dbad93c42 | []
| no_license | chadaustin/isugamedev | 200a54f55a2581cd2c62c94eb96b9e238abcf3dd | d3008ada042d2dd98c6e05711773badf6f1fd85c | refs/heads/master | 2016-08-11T17:59:38.504631 | 2005-01-25T23:17:11 | 2005-01-25T23:17:11 | 36,483,500 | 1 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 14,372 | cpp | /****************************************************************************
example5.cpp
A GLUI program demonstrating subwindows, rotation controls,
translation controls, and listboxes
-----------------------------------------------------------------------
7/10/98 Paul Rademacher ([email protected])
****************************************************************************/
#include <string.h>
#include <GL/glut.h>
#include "glui.h"
float xy_aspect;
int last_x, last_y;
float rotationX = 0.0, rotationY = 0.0;
/** These are the live variables passed into GLUI ***/
int wireframe = 0;
int obj_type = 1;
int segments = 8;
int segments2 = 8;
int light0_enabled = 1;
int light1_enabled = 1;
float light0_intensity = 1.0;
float light1_intensity = .4;
int main_window;
float scale = 1.0;
int show_sphere=1;
int show_torus=1;
int show_axes = 1;
int show_text = 1;
float sphere_rotate[16] = { 1,0,0,0, 0,1,0,0, 0,0,1,0, 0,0,0,1 };
float torus_rotate[16] = { 1,0,0,0, 0,1,0,0, 0,0,1,0, 0,0,0,1 };
float view_rotate[16] = { 1,0,0,0, 0,1,0,0, 0,0,1,0, 0,0,0,1 };
float obj_pos[] = { 0.0, 0.0, 0.0 };
char *string_list[] = { "Hello World!", "Foo", "Testing...", "Bounding box: on" };
int curr_string = 0;
/** Pointers to the windows and some of the controls we'll create **/
GLUI *glui, *glui2;
GLUI_Checkbox *checkbox;
GLUI_Spinner *spinner, *light0_spinner, *light1_spinner;
GLUI_RadioGroup *radio;
GLUI_Panel *obj_panel;
/********** User IDs for callbacks ********/
#define LIGHT0_ENABLED_ID 200
#define LIGHT1_ENABLED_ID 201
#define LIGHT0_INTENSITY_ID 250
#define LIGHT1_INTENSITY_ID 251
#define ENABLE_ID 300
#define DISABLE_ID 301
#define SHOW_ID 302
#define HIDE_ID 303
/********** Miscellaneous global variables **********/
GLfloat light0_ambient[] = {0.1f, 0.1f, 0.3f, 1.0f};
GLfloat light0_diffuse[] = {.6f, .6f, 1.0f, 1.0f};
GLfloat light0_position[] = {.5f, .5f, 1.0f, 0.0f};
GLfloat light1_ambient[] = {0.1f, 0.1f, 0.3f, 1.0f};
GLfloat light1_diffuse[] = {.9f, .6f, 0.0f, 1.0f};
GLfloat light1_position[] = {-1.0f, -1.0f, 1.0f, 0.0f};
GLfloat lights_rotation[16] = {1,0,0,0, 0,1,0,0, 0,0,1,0, 0,0,0,1 };
/**************************************** control_cb() *******************/
/* GLUI control callback */
void control_cb( int control )
{
if ( control == LIGHT0_ENABLED_ID ) {
if ( light0_enabled ) {
glEnable( GL_LIGHT0 );
light0_spinner->enable();
}
else {
glDisable( GL_LIGHT0 );
light0_spinner->disable();
}
}
else if ( control == LIGHT1_ENABLED_ID ) {
if ( light1_enabled ) {
glEnable( GL_LIGHT1 );
light1_spinner->enable();
}
else {
glDisable( GL_LIGHT1 );
light1_spinner->disable();
}
}
else if ( control == LIGHT0_INTENSITY_ID ) {
float v[] = { light0_diffuse[0], light0_diffuse[1],
light0_diffuse[2], light0_diffuse[3] };
v[0] *= light0_intensity;
v[1] *= light0_intensity;
v[2] *= light0_intensity;
glLightfv(GL_LIGHT0, GL_DIFFUSE, v );
}
else if ( control == LIGHT1_INTENSITY_ID ) {
float v[] = { light1_diffuse[0], light1_diffuse[1],
light1_diffuse[2], light1_diffuse[3] };
v[0] *= light1_intensity;
v[1] *= light1_intensity;
v[2] *= light1_intensity;
glLightfv(GL_LIGHT1, GL_DIFFUSE, v );
}
else if ( control == ENABLE_ID )
{
glui2->enable();
}
else if ( control == DISABLE_ID )
{
glui2->disable();
}
else if ( control == SHOW_ID )
{
glui2->show();
}
else if ( control == HIDE_ID )
{
glui2->hide();
}
}
/**************************************** myGlutKeyboard() **********/
void myGlutKeyboard(unsigned char Key, int x, int y)
{
switch(Key)
{
case 27:
case 'q':
exit(0);
break;
};
glutPostRedisplay();
}
/***************************************** myGlutMenu() ***********/
void myGlutMenu( int value )
{
myGlutKeyboard( value, 0, 0 );
}
/***************************************** myGlutIdle() ***********/
void myGlutIdle( void )
{
/* According to the GLUT specification, the current window is
undefined during an idle callback. So we need to explicitly change
it if necessary */
if ( glutGetWindow() != main_window )
glutSetWindow(main_window);
/* GLUI_Master.sync_live_all(); -- not needed - nothing to sync in this
application */
glutPostRedisplay();
}
/***************************************** myGlutMouse() **********/
void myGlutMouse(int button, int button_state, int x, int y )
{
}
/***************************************** myGlutMotion() **********/
void myGlutMotion(int x, int y )
{
glutPostRedisplay();
}
/**************************************** myGlutReshape() *************/
void myGlutReshape( int x, int y )
{
int tx, ty, tw, th;
GLUI_Master.get_viewport_area( &tx, &ty, &tw, &th );
glViewport( tx, ty, tw, th );
xy_aspect = (float)tw / (float)th;
glutPostRedisplay();
}
/************************************************** draw_axes() **********/
/* Disables lighting, then draws RGB axes */
void draw_axes( float scale )
{
glDisable( GL_LIGHTING );
glPushMatrix();
glScalef( scale, scale, scale );
glBegin( GL_LINES );
glColor3f( 1.0, 0.0, 0.0 );
glVertex3f( .8f, 0.05f, 0.0 ); glVertex3f( 1.0, 0.25f, 0.0 ); /* Letter X */
glVertex3f( 0.8f, .25f, 0.0 ); glVertex3f( 1.0, 0.05f, 0.0 );
glVertex3f( 0.0, 0.0, 0.0 ); glVertex3f( 1.0, 0.0, 0.0 ); /* X axis */
glColor3f( 0.0, 1.0, 0.0 );
glVertex3f( 0.0, 0.0, 0.0 ); glVertex3f( 0.0, 1.0, 0.0 ); /* Y axis */
glColor3f( 0.0, 0.0, 1.0 );
glVertex3f( 0.0, 0.0, 0.0 ); glVertex3f( 0.0, 0.0, 1.0 ); /* Z axis */
glEnd();
glPopMatrix();
glEnable( GL_LIGHTING );
}
/***************************************** myGlutDisplay() *****************/
void myGlutDisplay( void )
{
glClearColor( .9f, .9f, .9f, 1.0f );
glClear( GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT );
glMatrixMode( GL_PROJECTION );
glLoadIdentity();
glFrustum( -xy_aspect*.04, xy_aspect*.04, -.04, .04, .1, 15.0 );
glMatrixMode( GL_MODELVIEW );
glLoadIdentity();
glMultMatrixf( lights_rotation );
glLightfv(GL_LIGHT0, GL_POSITION, light0_position);
glLoadIdentity();
glTranslatef( 0.0, 0.0, -2.6f );
glTranslatef( obj_pos[0], obj_pos[1], -obj_pos[2] );
glMultMatrixf( view_rotate );
glScalef( scale, scale, scale );
/*** Now we render object, using the variables 'obj_type', 'segments', and
'wireframe'. These are _live_ variables, which are transparently
updated by GLUI ***/
glPushMatrix();
glTranslatef( -.5, 0.0, 0.0 );
glMultMatrixf( sphere_rotate );
if ( wireframe && show_sphere)
glutWireSphere( .4, segments, segments );
else if ( show_sphere )
glutSolidSphere( .4, segments, segments );
if ( show_axes )
draw_axes(.52f);
glPopMatrix();
glPushMatrix();
glTranslatef( .5, 0.0, 0.0 );
glMultMatrixf( torus_rotate );
if ( wireframe && show_torus )
glutWireTorus( .15,.3,16,segments );
else if ( show_torus )
glutSolidTorus( .15,.3,16,segments );
if ( show_axes )
draw_axes(.52f);
glPopMatrix();
if ( show_text )
{
glDisable( GL_LIGHTING ); /* Disable lighting while we render text */
glMatrixMode( GL_PROJECTION );
glLoadIdentity();
gluOrtho2D( 0.0, 100.0, 0.0, 100.0 );
glMatrixMode( GL_MODELVIEW );
glLoadIdentity();
glColor3ub( 0, 0, 0 );
glRasterPos2i( 10, 10 );
/* printf( "text: %s\n", text ); */
/*** Render the live character array 'text' ***/
int i;
for( i=0; i<(int)strlen( string_list[curr_string] ); i++ )
glutBitmapCharacter( GLUT_BITMAP_HELVETICA_18, string_list[curr_string][i] );
}
glEnable( GL_LIGHTING );
glutSwapBuffers();
}
/**************************************** main() ********************/
void main(int argc, char* argv[])
{
/****************************************/
/* Initialize GLUT and create window */
/****************************************/
glutInitDisplayMode( GLUT_RGB | GLUT_DOUBLE | GLUT_DEPTH );
glutInitWindowPosition( 50, 50 );
glutInitWindowSize( 800, 600 );
main_window = glutCreateWindow( "GLUI Example 5" );
glutDisplayFunc( myGlutDisplay );
GLUI_Master.set_glutReshapeFunc( myGlutReshape );
GLUI_Master.set_glutKeyboardFunc( myGlutKeyboard );
GLUI_Master.set_glutSpecialFunc( NULL );
GLUI_Master.set_glutMouseFunc( myGlutMouse );
glutMotionFunc( myGlutMotion );
/****************************************/
/* Set up OpenGL lights */
/****************************************/
glEnable(GL_LIGHTING);
glEnable( GL_NORMALIZE );
glEnable(GL_LIGHT0);
glLightfv(GL_LIGHT0, GL_AMBIENT, light0_ambient);
glLightfv(GL_LIGHT0, GL_DIFFUSE, light0_diffuse);
glLightfv(GL_LIGHT0, GL_POSITION, light0_position);
glEnable(GL_LIGHT1);
glLightfv(GL_LIGHT1, GL_AMBIENT, light1_ambient);
glLightfv(GL_LIGHT1, GL_DIFFUSE, light1_diffuse);
glLightfv(GL_LIGHT1, GL_POSITION, light1_position);
/****************************************/
/* Enable z-buferring */
/****************************************/
glEnable(GL_DEPTH_TEST);
/****************************************/
/* Here's the GLUI code */
/****************************************/
printf( "GLUI version: %3.2f\n", GLUI_Master.get_version() );
/*** Create the side subwindow ***/
glui = GLUI_Master.create_glui_subwindow( main_window,
GLUI_SUBWINDOW_RIGHT );
obj_panel = glui->add_rollout( "Properties", false );
/***** Control for object params *****/
checkbox =
glui->add_checkbox_to_panel( obj_panel, "Wireframe", &wireframe, 1,
control_cb );
spinner = glui->add_spinner_to_panel( obj_panel, "Segments:",
GLUI_SPINNER_INT, &segments);
spinner->set_int_limits( 3, 60 );
spinner->set_alignment( GLUI_ALIGN_RIGHT );
GLUI_Spinner *scale_spinner =
glui->add_spinner_to_panel( obj_panel, "Scale:",
GLUI_SPINNER_FLOAT, &scale);
scale_spinner->set_float_limits( .2f, 4.0 );
scale_spinner->set_alignment( GLUI_ALIGN_RIGHT );
/******** Add some controls for lights ********/
GLUI_Rollout *roll_lights = glui->add_rollout( "Lights", false );
GLUI_Panel *light0 = glui->add_panel_to_panel( roll_lights, "Light 1" );
GLUI_Panel *light1 = glui->add_panel_to_panel( roll_lights, "Light 2" );
glui->add_checkbox_to_panel( light0, "Enabled", &light0_enabled,
LIGHT0_ENABLED_ID, control_cb );
light0_spinner =
glui->add_spinner_to_panel( light0, "Intensity:", GLUI_SPINNER_FLOAT,
&light0_intensity, LIGHT0_INTENSITY_ID,
control_cb );
light0_spinner->set_float_limits( 0.0, 1.0 );
glui->add_checkbox_to_panel( light1, "Enabled", &light1_enabled,
LIGHT1_ENABLED_ID, control_cb );
light1_spinner =
glui->add_spinner_to_panel( light1, "Intensity:", GLUI_SPINNER_FLOAT,
&light1_intensity, LIGHT1_INTENSITY_ID,
control_cb );
light1_spinner->set_float_limits( 0.0, 1.0 );
/*** Add another rollout ***/
GLUI_Rollout *options = glui->add_rollout( "Options", true );
glui->add_checkbox_to_panel( options, "Draw sphere", &show_sphere );
glui->add_checkbox_to_panel( options, "Draw torus", &show_torus );
glui->add_checkbox_to_panel( options, "Draw axes", &show_axes );
glui->add_checkbox_to_panel( options, "Draw text", &show_text );
/**** Add listbox ****/
glui->add_statictext( "" );
GLUI_Listbox *list = glui->add_listbox( "Text:", &curr_string );
int i;
for( i=0; i<4; i++ )
list->add_item( i, string_list[i] );
glui->add_statictext( "" );
/*** Disable/Enable buttons ***/
glui->add_button( "Disable movement", DISABLE_ID, control_cb );
glui->add_button( "Enable movement", ENABLE_ID, control_cb );
glui->add_button( "Hide", HIDE_ID, control_cb );
glui->add_button( "Show", SHOW_ID, control_cb );
glui->add_statictext( "" );
/****** A 'quit' button *****/
glui->add_button( "Quit", 0,(GLUI_Update_CB)exit );
/**** Link windows to GLUI, and register idle callback ******/
glui->set_main_gfx_window( main_window );
/*** Create the bottom subwindow ***/
glui2 = GLUI_Master.create_glui_subwindow( main_window,
GLUI_SUBWINDOW_BOTTOM );
glui2->set_main_gfx_window( main_window );
GLUI_Rotation *view_rot = glui2->add_rotation( "Objects", view_rotate );
view_rot->set_spin( 1.0 );
glui2->add_column( false );
GLUI_Rotation *sph_rot = glui2->add_rotation( "Sphere", sphere_rotate );
sph_rot->set_spin( .98 );
glui2->add_column( false );
GLUI_Rotation *tor_rot = glui2->add_rotation( "Torus", torus_rotate );
tor_rot->set_spin( .98 );
glui2->add_column( false );
GLUI_Rotation *lights_rot = glui2->add_rotation( "Blue Light", lights_rotation );
lights_rot->set_spin( .82 );
glui2->add_column( false );
GLUI_Translation *trans_xy =
glui2->add_translation( "Objects XY", GLUI_TRANSLATION_XY, obj_pos );
trans_xy->set_speed( .005 );
glui2->add_column( false );
GLUI_Translation *trans_x =
glui2->add_translation( "Objects X", GLUI_TRANSLATION_X, obj_pos );
trans_x->set_speed( .005 );
glui2->add_column( false );
GLUI_Translation *trans_y =
glui2->add_translation( "Objects Y", GLUI_TRANSLATION_Y, &obj_pos[1] );
trans_y->set_speed( .005 );
glui2->add_column( false );
GLUI_Translation *trans_z =
glui2->add_translation( "Objects Z", GLUI_TRANSLATION_Z, &obj_pos[2] );
trans_z->set_speed( .005 );
/**** We register the idle callback with GLUI, *not* with GLUT ****/
GLUI_Master.set_glutIdleFunc( myGlutIdle );
/**** Regular GLUT main loop ****/
glutMainLoop();
}
| [
"aegis@84b32ba4-53c3-423c-be69-77cca6335494"
]
| [
[
[
1,
482
]
]
]
|
b2b649a27705ce720bedc127108df3fc4e11b9a3 | 478570cde911b8e8e39046de62d3b5966b850384 | /apicompatanamdw/bcdrivers/mw/web/browser_control_api/src/BrCtlBCTestQueryDialog.cpp | 0e0256593e6e7f1a6c921989daf2fb6d544f7d66 | []
| no_license | SymbianSource/oss.FCL.sftools.ana.compatanamdw | a6a8abf9ef7ad71021d43b7f2b2076b504d4445e | 1169475bbf82ebb763de36686d144336fcf9d93b | refs/heads/master | 2020-12-24T12:29:44.646072 | 2010-11-11T14:03:20 | 2010-11-11T14:03:20 | 72,994,432 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 2,399 | cpp | /*
* Copyright (c) 2006-2009 Nokia Corporation and/or its subsidiary(-ies).
* All rights reserved.
* This component and the accompanying materials are made available
* under the terms of "Eclipse Public License v1.0"
* which accompanies this distribution, and is available
* at the URL "http://www.eclipse.org/legal/epl-v10.html".
*
* Initial Contributors:
* Nokia Corporation - initial contribution.
*
* Contributors:
*
* Description: ?Description
*
*/
// INCLUDE FILES
#include <avkon.hrh>
#include "BrCtlBCTestQueryDialog.h"
// ================= MEMBER FUNCTIONS =======================
// C++ default constructor can NOT contain any code, that
// might leave.
//
CBrCtlBCTestQueryDialog::CBrCtlBCTestQueryDialog( TDes& aDefInput, HBufC*& aRetBuf )
: CAknTextQueryDialog( aDefInput )
, iRetBuf( aRetBuf )
{
}
// ---------------------------------------------------------
// CBrCtlBCTestQueryDialog::PreLayoutDynInitL
// ---------------------------------------------------------
//
void CBrCtlBCTestQueryDialog::PreLayoutDynInitL()
{
CAknTextQueryDialog::PreLayoutDynInitL();
MakeLeftSoftkeyVisible( ETrue );
}
// ---------------------------------------------------------
// CBrCtlBCTestQueryDialog::OkToExitL
// ---------------------------------------------------------
//
TBool CBrCtlBCTestQueryDialog::OkToExitL( TInt aKeycode )
{
switch ( aKeycode )
{
case EAknSoftkeyOk:
{
CAknQueryControl* control = QueryControl();
__ASSERT_DEBUG( control, User::Panic( KNullDesC, KErrGeneral ) );
iRetBuf = HBufC::NewL( control->GetTextLength() + 1);
TPtr temp( iRetBuf->Des() );
control->GetText( temp );
temp.ZeroTerminate();
}
// no break !!! same return value
case EAknSoftkeyCancel:
return ETrue;
default:
return EFalse;
}
}
// ---------------------------------------------------------
// CBrCtlBCTestQueryDialog::HandleQueryEditorStateEventL
//
// This code is base on AknQueryDialog.cpp
// ---------------------------------------------------------
//
TBool CBrCtlBCTestQueryDialog::HandleQueryEditorStateEventL(CAknQueryControl* /*aQueryControl*/,
TQueryControlEvent /*aEventType*/, TQueryValidationStatus /*aStatus*/)
{
return EFalse;
}
// End of File | [
"none@none"
]
| [
[
[
1,
85
]
]
]
|
d43b6c7140ca8d9a81fe4b88d4ba13f384aa9e48 | 1ef66085a12fa4476f44b7faa6828a08170d9e51 | /meshdeformer/3rdparty/assimp/.svn/text-base/assimp.hpp.svn-base | 5ab9e2a2cb9f9a0e27782ef8b2f7e8f55d2010bc | []
| no_license | porpaew/dreamstuff | 73ad03e0308882e68c9c7b5c9f9eded6a4e90bed | f24d5aab1d4fbc87de012a7205b68d63255c0be3 | refs/heads/master | 2021-01-18T19:26:41.303411 | 2010-08-21T05:37:54 | 2010-08-21T05:37:54 | 40,980,385 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 23,797 | /*
---------------------------------------------------------------------------
Open Asset Import Library (ASSIMP)
---------------------------------------------------------------------------
Copyright (c) 2006-2008, ASSIMP Development Team
All rights reserved.
Redistribution and use of this software in source and binary forms,
with or without modification, are permitted provided that the following
conditions are met:
* Redistributions of source code must retain the above
copyright notice, this list of conditions and the
following disclaimer.
* Redistributions in binary form must reproduce the above
copyright notice, this list of conditions and the
following disclaimer in the documentation and/or other
materials provided with the distribution.
* Neither the name of the ASSIMP team, nor the names of its
contributors may be used to endorse or promote products
derived from this software without specific prior
written permission of the ASSIMP Development Team.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
"AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
---------------------------------------------------------------------------
*/
/** @file assimp.hpp
* @brief Defines the C++-API to the Open Asset Import Library.
*/
#ifndef INCLUDED_AI_ASSIMP_HPP
#define INCLUDED_AI_ASSIMP_HPP
#ifndef __cplusplus
# error This header requires C++ to be used. Use assimp.h for plain C.
#endif
// Public ASSIMP data structures
#include "aiTypes.h"
#include "aiConfig.h"
#include "aiAssert.h"
namespace Assimp {
// =======================================================================
// Public interface to Assimp
class Importer;
class IOStream;
class IOSystem;
// =======================================================================
// Plugin development
//
// Include the following headers for the declarations:
// BaseImporter.h
// BaseProcess.h
class BaseImporter;
class BaseProcess;
class SharedPostProcessInfo;
class BatchLoader;
// =======================================================================
// Holy stuff, only for members of the high council of the Jedi.
class ImporterPimpl;
} //! namespace Assimp
#define AI_PROPERTY_WAS_NOT_EXISTING 0xffffffff
struct aiScene;
struct aiFileIO;
extern "C" ASSIMP_API const aiScene* aiImportFileEx( const char*, unsigned int, aiFileIO*);
extern "C" ASSIMP_API const aiScene* aiImportFileFromMemory( const char*,
unsigned int,unsigned int,const char*);
/** @namespace Assimp Assimp's CPP-API and all internal APIs */
namespace Assimp {
// ----------------------------------------------------------------------------------
/** CPP-API: The Importer class forms an C++ interface to the functionality of the
* Open Asset Import Library.
*
* Create an object of this class and call ReadFile() to import a file.
* If the import succeeds, the function returns a pointer to the imported data.
* The data remains property of the object, it is intended to be accessed
* read-only. The imported data will be destroyed along with the Importer
* object. If the import fails, ReadFile() returns a NULL pointer. In this
* case you can retrieve a human-readable error description be calling
* GetErrorString(). You can call ReadFile() multiple times with a single Importer
* instance. Actually, constructing Importer objects involves quite many
* allocations and may take some time, so it's better to reuse them as often as
* possible.
*
* If you need the Importer to do custom file handling to access the files,
* implement IOSystem and IOStream and supply an instance of your custom
* IOSystem implementation by calling SetIOHandler() before calling ReadFile().
* If you do not assign a custion IO handler, a default handler using the
* standard C++ IO logic will be used.
*
* @note One Importer instance is not thread-safe. If you use multiple
* threads for loading, each thread should maintain its own Importer instance.
*/
class ASSIMP_API Importer {
// for internal use
friend class BaseProcess;
friend class BatchLoader;
friend const aiScene* ::aiImportFileEx( const char*, unsigned int, aiFileIO*);
friend const aiScene* ::aiImportFileFromMemory( const char*,
unsigned int,unsigned int,const char*);
public:
// -------------------------------------------------------------------
/** Constructor. Creates an empty importer object.
*
* Call ReadFile() to start the import process. The configuration
* property table is initially empty.
*/
Importer();
// -------------------------------------------------------------------
/** Copy constructor.
*
* This copies the configuration properties of another Importer.
* If this Importer owns a scene it won't be copied.
* Call ReadFile() to start the import process.
*/
Importer(const Importer& other);
// -------------------------------------------------------------------
/** Destructor. The object kept ownership of the imported data,
* which now will be destroyed along with the object.
*/
~Importer();
// -------------------------------------------------------------------
/** Registers a new loader.
*
* @param pImp Importer to be added. The Importer instance takes
* ownership of the pointer, so it will be automatically deleted
* with the Importer instance.
* @return AI_SUCCESS if the loader has been added. The registration
* fails if there is already a loader for a specific file extension.
*/
aiReturn RegisterLoader(BaseImporter* pImp);
// -------------------------------------------------------------------
/** Unregisters a loader.
*
* @param pImp Importer to be unregistered.
* @return AI_SUCCESS if the loader has been removed. The function
* fails if the loader is currently in use (this could happen
* if the #Importer instance is used by more than one thread) or
* if it has not yet been registered.
*/
aiReturn UnregisterLoader(BaseImporter* pImp);
// -------------------------------------------------------------------
/** Registers a new post-process step.
*
* At the moment, there's a small limitation: new post processing
* steps are added to end of the list, or in other words, executed
* last, after all built-in steps.
* @param pImp Post-process step to be added. The Importer instance
* takes ownership of the pointer, so it will be automatically
* deleted with the Importer instance.
* @return AI_SUCCESS if the step has been added correctly.
*/
aiReturn RegisterPPStep(BaseProcess* pImp);
// -------------------------------------------------------------------
/** Unregisters a post-process step.
*
* @param pImp Step to be unregistered.
* @return AI_SUCCESS if the step has been removed. The function
* fails if the step is currently in use (this could happen
* if the #Importer instance is used by more than one thread) or
* if it has not yet been registered.
*/
aiReturn UnregisterPPStep(BaseProcess* pImp);
// -------------------------------------------------------------------
/** Set an integer configuration property.
* @param szName Name of the property. All supported properties
* are defined in the aiConfig.g header (all constants share the
* prefix AI_CONFIG_XXX).
* @param iValue New value of the property
* @param bWasExisting Optional pointer to receive true if the
* property was set before. The new value replaced the old value
* in this case.
* @note Property of different types (float, int, string ..) are kept
* on different stacks, so calling SetPropertyInteger() for a
* floating-point property has no effect - the loader will call
* GetPropertyFloat() to read the property, but it won't be there.
*/
void SetPropertyInteger(const char* szName, int iValue,
bool* bWasExisting = NULL);
// -------------------------------------------------------------------
/** Set a floating-point configuration property.
* @see SetPropertyInteger()
*/
void SetPropertyFloat(const char* szName, float fValue,
bool* bWasExisting = NULL);
// -------------------------------------------------------------------
/** Set a string configuration property.
* @see SetPropertyInteger()
*/
void SetPropertyString(const char* szName, const std::string& sValue,
bool* bWasExisting = NULL);
// -------------------------------------------------------------------
/** Get a configuration property.
* @param szName Name of the property. All supported properties
* are defined in the aiConfig.g header (all constants share the
* prefix AI_CONFIG_XXX).
* @param iErrorReturn Value that is returned if the property
* is not found.
* @return Current value of the property
* @note Property of different types (float, int, string ..) are kept
* on different lists, so calling SetPropertyInteger() for a
* floating-point property has no effect - the loader will call
* GetPropertyFloat() to read the property, but it won't be there.
*/
int GetPropertyInteger(const char* szName,
int iErrorReturn = 0xffffffff) const;
// -------------------------------------------------------------------
/** Get a floating-point configuration property
* @see GetPropertyInteger()
*/
float GetPropertyFloat(const char* szName,
float fErrorReturn = 10e10f) const;
// -------------------------------------------------------------------
/** Get a string configuration property
*
* The return value remains valid until the property is modified.
* @see GetPropertyInteger()
*/
const std::string& GetPropertyString(const char* szName,
const std::string& sErrorReturn = "") const;
// -------------------------------------------------------------------
/** Supplies a custom IO handler to the importer to use to open and
* access files. If you need the importer to use custion IO logic to
* access the files, you need to provide a custom implementation of
* IOSystem and IOFile to the importer. Then create an instance of
* your custion IOSystem implementation and supply it by this function.
*
* The Importer takes ownership of the object and will destroy it
* afterwards. The previously assigned handler will be deleted.
* Pass NULL to take again ownership of your IOSystem and reset Assimp
* to use its default implementation.
*
* @param pIOHandler The IO handler to be used in all file accesses
* of the Importer.
*/
void SetIOHandler( IOSystem* pIOHandler);
// -------------------------------------------------------------------
/** Retrieves the IO handler that is currently set.
* You can use IsDefaultIOHandler() to check whether the returned
* interface is the default IO handler provided by ASSIMP. The default
* handler is active as long the application doesn't supply its own
* custom IO handler via SetIOHandler().
* @return A valid IOSystem interface
*/
IOSystem* GetIOHandler();
// -------------------------------------------------------------------
/** Checks whether a default IO handler is active
* A default handler is active as long the application doesn't
* supply its own custom IO handler via SetIOHandler().
* @return true by default
*/
bool IsDefaultIOHandler();
// -------------------------------------------------------------------
/** @brief Check whether a given set of postprocessing flags
* is supported.
*
* Some flags are mutually exclusive, others are probably
* not available because your excluded them from your
* Assimp builds. Calling this function is recommended if
* you're unsure.
*
* @param pFlags Bitwise combination of the aiPostProcess flags.
* @return true if this flag combination is not supported.
*/
bool ValidateFlags(unsigned int pFlags);
// -------------------------------------------------------------------
/** Reads the given file and returns its contents if successful.
*
* If the call succeeds, the contents of the file are returned as a
* pointer to an aiScene object. The returned data is intended to be
* read-only, the importer object keeps ownership of the data and will
* destroy it upon destruction. If the import fails, NULL is returned.
* A human-readable error description can be retrieved by calling
* GetErrorString(). The previous scene will be deleted during this call.
* @param pFile Path and filename to the file to be imported.
* @param pFlags Optional post processing steps to be executed after
* a successful import. Provide a bitwise combination of the
* #aiPostProcessSteps flags. If you wish to inspect the imported
* scene first in order to fine-tune your post-processing setup,
* consider to use #ApplyPostProcessing().
* @return A pointer to the imported data, NULL if the import failed.
* The pointer to the scene remains in possession of the Importer
* instance. Use GetOrphanedScene() to take ownership of it.
*
* @note Assimp is able to determine the file format of a file
* automatically. However, to enable automatic detection of the file
* format, the input path *must* not have an extension at all.
*/
const aiScene* ReadFile( const char* pFile, unsigned int pFlags);
// -------------------------------------------------------------------
/** Reads the given file from a memory buffer and returns its
* contents if successful.
*
* If the call succeeds, the contents of the file are returned as a
* pointer to an aiScene object. The returned data is intended to be
* read-only, the importer object keeps ownership of the data and will
* destroy it upon destruction. If the import fails, NULL is returned.
* A human-readable error description can be retrieved by calling
* GetErrorString(). The previous scene will be deleted during this call.
* Calling this method doesn't affect the active IOSystem.
* @param pBuffer Pointer to the file data
* @param pLength Length of pBuffer, in bytes
* @param pFlags Optional post processing steps to be executed after
* a successful import. Provide a bitwise combination of the
* #aiPostProcessSteps flags. If you wish to inspect the imported
* scene first in order to fine-tune your post-processing setup,
* consider to use #ApplyPostProcessing().
* @param pHint An additional hint to the library. If this is a non
* empty string, the library looks for a loader to support
* the file extension specified by pHint and passes the file to
* the first matching loader. If this loader is unable to completely
* the request, the library continues and tries to determine the
* file format on its own, a task that may or may not be successful.
* Check the return value, and you'll know ...
* @return A pointer to the imported data, NULL if the import failed.
* The pointer to the scene remains in possession of the Importer
* instance. Use GetOrphanedScene() to take ownership of it.
*
* @note This is a straightforward way to decode models from memory
* buffers, but it doesn't handle model formats spreading their
* data across multiple files or even directories. Examples include
* OBJ or MD3, which outsource parts of their material stuff into
* external scripts. f you need the full functionality, provide
* a custom IOSystem to make Assimp find these files.
*/
const aiScene* ReadFileFromMemory( const void* pBuffer,
size_t pLength,
unsigned int pFlags,
const char* pHint = "");
// -------------------------------------------------------------------
/** Apply post-processing to an already-imported scene.
*
* This is strictly equivalent to calling #ReadFile() with the same
* flags. However, you can use this separate function to inspect
* the imported scene first to fine-tune your post-processing setup.
* @param pFlags Provide a bitwise combination of the
* #aiPostProcessSteps flags.
* @return A pointer to the post-processed data. This is still the
* same as the pointer returned by #ReadFile(). However, if
* post-processing fails, the scene could now be NULL.
* That's quite a rare case, post processing steps are not really
* designed to 'fail'. To be exact, the #aiProcess_ValidateDS
* flag is currently the only post processing step which can actually
* cause the scene to be reset to NULL.
*
* @note The method does nothing if no scene is currently bound
* to the #Importer instance.
*/
const aiScene* ApplyPostProcessing(unsigned int pFlags);
// -------------------------------------------------------------------
/** @brief Reads the given file and returns its contents if successful.
*
* This function is provided for backward compatibility.
* See the const char* version for detailled docs.
* @see ReadFile(const char*, pFlags)
*/
const aiScene* ReadFile( const std::string& pFile, unsigned int pFlags);
// -------------------------------------------------------------------
/** Frees the current scene.
*
* The function does nothing if no scene has previously been
* read via ReadFile(). FreeScene() is called automatically by the
* destructor and ReadFile() itself.
*/
void FreeScene( );
// -------------------------------------------------------------------
/** Returns an error description of an error that occurred in ReadFile().
*
* Returns an empty string if no error occurred.
* @return A description of the last error, an empty string if no
* error occurred. The string is never NULL.
*
* @note The returned function remains valid until one of the
* following methods is called: #ReadFile(), #FreeScene().
*/
const char* GetErrorString() const;
// -------------------------------------------------------------------
/** Returns whether a given file extension is supported by ASSIMP.
*
* @param szExtension Extension to be checked.
* Must include a trailing dot '.'. Example: ".3ds", ".md3".
* Cases-insensitive.
* @return true if the extension is supported, false otherwise
*/
bool IsExtensionSupported(const char* szExtension);
// -------------------------------------------------------------------
/** @brief Returns whether a given file extension is supported by ASSIMP.
*
* This function is provided for backward compatibility.
* See the const char* version for detailled docs.
* @see IsExtensionSupported(const char*)
*/
inline bool IsExtensionSupported(const std::string& szExtension);
// -------------------------------------------------------------------
/** Get a full list of all file extensions supported by ASSIMP.
*
* If a file extension is contained in the list this does of course not
* mean that ASSIMP is able to load all files with this extension.
* @param szOut String to receive the extension list. It just means there
* is a loader which handles such files.
* Format of the list: "*.3ds;*.obj;*.dae".
*/
void GetExtensionList(aiString& szOut);
// -------------------------------------------------------------------
/** @brief Get a full list of all file extensions supported by ASSIMP.
*
* This function is provided for backward compatibility.
* See the aiString version for detailled docs.
* @see GetExtensionList(aiString&)
*/
inline void GetExtensionList(std::string& szOut);
// -------------------------------------------------------------------
/** Find the loader corresponding to a specific file extension.
*
* This is quite similar to IsExtensionSupported() except a
* BaseImporter instance is returned.
* @param szExtension Extension to be checked, cases insensitive,
* must include a trailing dot.
* @return NULL if there is no loader for the extension.
*/
BaseImporter* FindLoader (const char* szExtension);
// -------------------------------------------------------------------
/** Returns the scene loaded by the last successful call to ReadFile()
*
* @return Current scene or NULL if there is currently no scene loaded
*/
const aiScene* GetScene() const;
// -------------------------------------------------------------------
/** Returns the scene loaded by the last successful call to ReadFile()
* and releases the scene from the ownership of the Importer
* instance. The application is now responsible for deleting the
* scene. Any further calls to GetScene() or GetOrphanedScene()
* will return NULL - until a new scene has been loaded via ReadFile().
*
* @return Current scene or NULL if there is currently no scene loaded
* @note Under windows, deleting the returned scene manually will
* probably not work properly in applications using static runtime linkage.
*/
aiScene* GetOrphanedScene();
// -------------------------------------------------------------------
/** Returns the storage allocated by ASSIMP to hold the scene data
* in memory.
*
* This refers to the currently loaded file, see #ReadFile().
* @param in Data structure to be filled.
*/
void GetMemoryRequirements(aiMemoryInfo& in) const;
// -------------------------------------------------------------------
/** Enables "extra verbose" mode.
*
* In this mode the data structure is validated after every single
* post processing step to make sure everyone modifies the data
* structure in the defined manner. This is a debug feature and not
* intended for public use.
*/
void SetExtraVerbose(bool bDo);
protected:
// Just because we don't want you to know how we're hacking around.
ImporterPimpl* pimpl;
}; //! class Importer
// ----------------------------------------------------------------------------
// For compatibility, the interface of some functions taking a std::string was
// changed to const char* to avoid crashes between binary incompatible STL
// versions. This code her is inlined, so it shouldn't cause any problems.
// ----------------------------------------------------------------------------
// ----------------------------------------------------------------------------
AI_FORCE_INLINE const aiScene* Importer::ReadFile( const std::string& pFile,
unsigned int pFlags)
{
return ReadFile(pFile.c_str(),pFlags);
}
// ----------------------------------------------------------------------------
AI_FORCE_INLINE void Importer::GetExtensionList(std::string& szOut)
{
aiString s;
GetExtensionList(s);
szOut = s.data;
}
// ----------------------------------------------------------------------------
AI_FORCE_INLINE bool Importer::IsExtensionSupported(
const std::string& szExtension)
{
return IsExtensionSupported(szExtension.c_str());
}
} // !namespace Assimp
#endif // INCLUDED_AI_ASSIMP_HPP
| [
"lai.jingwen2008@21fd095a-c762-11de-9e96-3193d784f102"
]
| [
[
[
1,
549
]
]
]
|
|
9ea322fbf3059fda336855c1cd95ec0ac42941f8 | 26b6f15c144c2f7a26ab415c3997597fa98ba30a | /sdp/src/PortRange.cpp | 647ff7e42ef7fa509e4809a07b1b71198d864882 | []
| no_license | wangscript007/rtspsdk | fb0b52e63ad1671e8b2ded1d8f10ef6c3c63fddf | f5b095f0491e5823f50a83352945acb88f0b8aa0 | refs/heads/master | 2022-03-09T09:25:23.988183 | 2008-12-27T17:23:31 | 2008-12-27T17:23:31 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 4,531 | cpp | /*****************************************************************************
// SDP Parser Classes
//
// Port Range Class
//
// revision of last commit:
// $Rev$
// author of last commit:
// $Author$
// date of last commit:
// $Date$
//
// created by Argenet {[email protected]}
//
// Permission is hereby granted, free of charge, to any person or organization
// obtaining a copy of the software and accompanying documentation covered by
// this license (the "Software") to use, reproduce, display, distribute,
// execute, and transmit the Software, and to prepare derivative works of the
// Software, and to permit third-parties to whom the Software is furnished to
// do so, all subject to the following:
//
// The copyright notices in the Software and this entire statement, including
// the above license grant, this restriction and the following disclaimer,
// must be included in all copies of the Software, in whole or in part, and
// all derivative works of the Software, unless such copies or derivative
// works are solely in the form of machine-executable object code generated by
// a source language processor.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE, TITLE AND NON-INFRINGEMENT. IN NO EVENT
// SHALL THE COPYRIGHT HOLDERS OR ANYONE DISTRIBUTING THE SOFTWARE BE LIABLE
// FOR ANY DAMAGES OR OTHER LIABILITY, WHETHER IN CONTRACT, TORT OR OTHERWISE,
// ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
// DEALINGS IN THE SOFTWARE.
//
******************************************************************************/
//~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
// Includes
//~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
// PoCo headers
#include "Poco/NumberFormatter.h"
#include "PortRange.h"
using std::string;
using Poco::NumberFormatter;
namespace SDP {
//~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
// PortRange class implementation
//~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
//~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
// Public methods
//~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
PortRange :: PortRange()
: _firstPort(0)
, _numberOfPorts(1)
{
}
//~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
PortRange :: PortRange(unsigned short firstPort)
: _firstPort(firstPort)
, _numberOfPorts(1)
{
}
//~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
PortRange :: PortRange(unsigned short firstPort, unsigned short numberOfPorts)
: _firstPort(firstPort)
, _numberOfPorts(numberOfPorts)
{
}
//~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
PortRange :: PortRange(const PortRange & portRange)
: _firstPort(portRange._firstPort)
, _numberOfPorts(portRange._numberOfPorts)
{
}
//~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
PortRange & PortRange :: operator=(const PortRange & portRange)
{
if(&portRange != this)
{
_firstPort = portRange._firstPort;
_numberOfPorts = portRange._numberOfPorts;
}
return *this;
}
//~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
inline unsigned short PortRange :: getFirstPort() const
{
return _firstPort;
}
//~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
void PortRange :: setFirstPort(unsigned short firstPort)
{
_firstPort = firstPort;
}
//~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
inline unsigned short PortRange :: getNumberOfPorts() const
{
return _numberOfPorts;
}
//~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
void PortRange :: setNumberOfPorts(unsigned short numberOfPorts)
{
poco_assert((0 < numberOfPorts) && (_firstPort + numberOfPorts < 65536));
_numberOfPorts = numberOfPorts;
}
//~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
string PortRange :: toString() const
{
string result = NumberFormatter::format(_firstPort);
if(1 != _numberOfPorts)
{
result += "\\";
result += NumberFormatter::format(_numberOfPorts);
}
return result;
}
} // namespace SDP
| [
"[email protected]",
"[email protected]"
]
| [
[
[
1,
148
]
],
[
[
149,
149
]
]
]
|
94342e366254ff9ac1cf4b894e0d115df2d107e9 | b4d726a0321649f907923cc57323942a1e45915b | /CODE/ImpED/Sexp_tree.cpp | b2c33e15474607b117967cf92d8ae99c59d1c0a0 | []
| no_license | chief1983/Imperial-Alliance | f1aa664d91f32c9e244867aaac43fffdf42199dc | 6db0102a8897deac845a8bd2a7aa2e1b25086448 | refs/heads/master | 2016-09-06T02:40:39.069630 | 2010-10-06T22:06:24 | 2010-10-06T22:06:24 | 967,775 | 2 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 222,510 | cpp | /*
* Copyright (C) Volition, Inc. 1999. All rights reserved.
*
* All source code herein is the property of Volition, Inc. You may not sell
* or otherwise commercially exploit the source or things you created based on the
* source.
*
*/
/*
* $Logfile: /Freespace2/code/Fred2/Sexp_tree.cpp $
* $Revision: 1.72 $
* $Date: 2004/06/15 20:50:28 $
* $Author: wmcoolmon $
*
* Sexp tree handler class. Almost everything is handled by this class.
*
* $Log: Sexp_tree.cpp,v $
* Revision 1.72 2004/06/15 20:50:28 wmcoolmon
* hud-set-color, current-speed, and FRED fixes (Wouldn't compile).
*
* Revision 1.71 2004/06/09 00:19:48 wmcoolmon
* hud-set-color SEXP description
*
* Revision 1.70 2004/06/01 07:38:39 wmcoolmon
* New HUD SEXP stuff.
*
* Revision 1.69 2004/05/11 02:16:35 Goober5000
* accidentally committed this in fs2_open, so I should do it here too
* --Goober5000
*
* Revision 1.68 2004/03/15 12:14:46 randomtiger
* Fixed a whole heap of problems with Fred introduced by changes to global vars.
*
* Revision 1.67 2004/01/14 06:28:39 Goober5000
* made set-support-ship number align with general FS convention
* --Goober5000
*
* Revision 1.66 2003/11/11 21:29:58 Goober5000
* forgot the FRED one :-P
* --Goober5000
*
* Revision 1.65 2003/10/20 11:49:17 Goober5000
* added min, max, and avg sexps
* --Goober5000
*
* Revision 1.64 2003/09/30 04:06:43 Goober5000
* removed orphaned sexp help left over from _argv[-1]'s stuff
* --Goober5000
*
* Revision 1.63 2003/09/11 23:21:53 Goober5000
* Rolled back _argv[-1]'s changes to the sexp infrastructure, which would
* have broken a huge amount of stuff and created some nasty bugs.
* Also commented most of _argv[-1]'s new sexps pending consolidation,
* and added a placeholder help entry for the one good sexp.
* --Goober5000
*
* Revision 1.62 2003/09/05 10:04:33 Goober5000
* persistent variable checkboxes in FRED
* --Goober5000
*
* Revision 1.61 2003/09/05 07:43:56 Goober5000
* fix some compile errors
* --Goober5000
*
* Revision 1.60 2003/09/05 05:06:32 Goober5000
* merged num-ships-in-battle and num-ships-in-battle-team, making the
* team argument optional
* --Goober5000
*
* Revision 1.59 2003/09/05 04:53:50 Goober5000
* merge of Phreak's and my Sexp_tree.cpp
* --Goober5000
*
* Revision 1.58 2003/09/05 02:16:18 phreak
* added an option to loop sounds played by play-sound-from-file, so i updated the sexp help
*
* Revision 1.57 2003/08/30 22:00:49 phreak
* added sexp help for num-ships-in-battle and num-ships-in-battle-team
*
* Revision 1.56 2003/08/28 06:29:17 Goober5000
* ah, 'tworks :)
* now fixing up the FRED part
* basically the last few commits were bugfixes
* --Goober5000
*
* Revision 1.55 2003/08/27 02:04:54 Goober5000
* added percent-ships-disarmed and percent-ships-disabled
* --Goober5000
*
* Revision 1.54 2003/08/27 01:38:00 Goober5000
* added is-ship-type, is-ship-class, lock-rotating-subsystem, and free-rotating-subsystem;
* also fixed the argument and return values for various sexps so that they work
* properly for negative numbers
* --Goober5000
*
* Revision 1.53 2003/08/21 09:00:20 Goober5000
* fixed set-support-ship sexp
* --Goober5000
*
* Revision 1.52 2003/06/19 18:13:27 phreak
* added help for turret-tagged-specific and turret-tagged-clear-specific
*
* Revision 1.51 2003/05/24 16:48:49 phreak
* added help info for Sesquipedalian's kamikaze and not-kamikaze sexps
*
* Revision 1.50 2003/04/12 19:09:16 Goober5000
* fixed an omission that caused a subcategory not to show up
* --Goober5000
*
* Revision 1.49 2003/04/05 20:47:58 Goober5000
* gotta love those compiler errors ;)
* fixed those and cleaned up conflicts with the missile-locked sexp
* --Goober5000
*
* Revision 1.48 2003/03/30 21:01:19 Goober5000
* Ugh. Fixed a dumb bug where FRED wouldn't check the right subsystem for
* some sexps.
* --Goober5000
*
* Revision 1.47 2003/03/29 11:24:25 sesquipedalian
* Aaaand nevermind...
*
* Revision 1.46 2003/03/29 08:51:54 sesquipedalian
* Added is-missile-locked sexp
*
* Revision 1.45 2003/03/22 07:24:53 Goober5000
* bleah
* --Goober5000
*
* Revision 1.44 2003/03/21 08:43:23 Goober5000
* d'oh
* --Goober5000
*
* Revision 1.43 2003/03/21 08:33:34 Goober5000
* yuck - fixed a nasty error when FRED provides a default value for warp-effect
* and explosion-effect
* --Goober5000
*
* Revision 1.42 2003/03/21 04:51:33 Goober5000
* added get-relative-object-*, where * = x, y, and z; these sexps return the
* world coordinates of a set of relative coordinates to an object; also, fixed many
* places in sexp.cpp so that now sexps can accept other sexps as parameters,
* wherease before they weren't able to
* --Goober5000
*
* Revision 1.41 2003/03/20 09:17:16 Goober5000
* implemented EMP as part of weapon-effect sexp
* --Goober5000
*
* Revision 1.40 2003/03/20 04:27:10 Goober5000
* extended sexps
* --Goober5000
*
* Revision 1.39 2003/03/20 00:28:37 Goober5000
* he doesn't make sexps, he makes them better
* --Goober5000
* even though I do make sexps :)
*
* Revision 1.38 2003/03/20 00:08:09 Goober5000
* making sexps better
* --Goober5000
*
* Revision 1.37 2003/03/19 06:27:26 Goober5000
* sexp help
* --Goober5000
*
* Revision 1.36 2003/03/18 08:45:33 Goober5000
* added explosion-effect sexp and did some other minor housekeeping
* --Goober5000
*
* Revision 1.35 2003/03/03 04:15:24 Goober5000
* FRED portion of tech room fix, plus some neatening up of the dialogs
* --Goober5000
*
* Revision 1.34 2003/01/26 20:02:06 Goober5000
* clarified help for damaged-escort-list and damaged-escort-list-all
* --Goober5000
*
* Revision 1.33 2003/01/26 18:37:19 Goober5000
* changed change-music to change-soundtrack
* --Goober5000
*
* Revision 1.32 2003/01/25 04:17:39 Goober5000
* added change-music sexp and bumped MAX_SOUNDTRACKS from 10 to 25
* --Ian Warfield
*
* Revision 1.31 2003/01/21 17:24:16 Goober5000
* fixed a few bugs in Bobboau's implementation of the glow sexps; also added
* help for the sexps in sexp_tree
* --Goober5000
*
* Revision 1.30 2003/01/19 22:20:22 Goober5000
* fixed a bunch of bugs -- the support ship sexp, the "no-subspace-drive" flag,
* and departure into hangars should now all work properly
* --Goober5000
*
* Revision 1.29 2003/01/19 07:45:38 Goober5000
* actually added the set-support-ship sexp; much of the other commit was
* groundwork (data types and stuff)
* --Goober5000
*
* Revision 1.28 2003/01/19 07:02:15 Goober5000
* fixed a bunch of bugs - "no-subspace-drive" should now work properly for
* all ships, and all ships who have their departure anchor set to a capital ship
* should exit to that ship when told to depart
* --Goober5000
*
* Revision 1.27 2003/01/10 04:14:18 Goober5000
* I found these two beautiful functions in ship.cpp - ship_change_model
* and change_ship_type - so I made them into sexps :)
* --Goober5000
*
* Revision 1.26 2003/01/07 20:06:44 Goober5000
* added ai-chase-any-except sexp
* --Goober5000
*
* Revision 1.25 2003/01/05 01:26:35 Goober5000
* added capability of is-iff and change-iff to have wings as well as ships
* as their arguments; also allowed a bunch of sexps to accept the player
* as an argument where they would previously display a parse error
* --Goober5000
*
* Revision 1.24 2003/01/04 23:15:39 Goober5000
* fixed the order sexp
* --Goober5000
*
* Revision 1.23 2003/01/03 21:58:07 Goober5000
* Fixed some minor bugs, and added a primitive-sensors flag, where if a ship
* has primitive sensors it can't target anything and objects don't appear
* on radar if they're outside a certain range. This range can be modified
* via the sexp primitive-sensors-set-range.
* --Goober5000
*
* Revision 1.22 2003/01/02 00:35:20 Goober5000
* added don't-collide-invisible and collide-invisible sexps
* --Goober5000
*
* Revision 1.21 2003/01/01 23:33:33 Goober5000
* added ship-vaporize and ship-no-vaporize sexps
* --Goober5000
*
* Revision 1.20 2002/12/31 08:20:31 Goober5000
* simplified end-user implementation of ballistic primaries
* --Goober5000
*
* Revision 1.19 2002/12/27 20:00:11 phreak
* added damage-escort-list to sexp tree help
*
* Revision 1.18 2002/12/27 03:14:47 Goober5000
* removed the existing stealth sexps and replaced them with the following:
* ship-stealthy
* ship-unstealthy
* is-ship-stealthy
* friendly-stealth-invisible
* friendly-stealth-visible
* is-friendly-stealth-visible
* --Goober5000
*
* Revision 1.17 2002/12/25 01:22:23 Goober5000
* meh - changed is-cargo-x to is-cargo
* --Goober5000
*
* Revision 1.16 2002/12/24 07:42:29 Goober5000
* added change-ai-class and is-ai-class, and I think I may also have nailed the
* is-iff bug; did some other bug hunting as well
* --Goober5000
*
* Revision 1.15 2002/12/23 23:01:27 Goober5000
* added set-cargo and is-cargo-x sexps
* --Goober5000
*
* Revision 1.14 2002/12/23 05:18:52 Goober5000
* Squashed some Volition bugs! :O Some of the sexps for dealing with more than
* one ship would return after only dealing with the first ship.
*
* Also added the following sexps:
* is-ship-stealthed
* ship-force-stealth
* ship-force-nostealth
* ship-remove-stealth-forcing
*
* They toggle the stealth flag on and off. If a ship is forced stealthy, it won't even
* show up for friendly ships.
* --Goober5000
*
* Revision 1.13 2002/12/22 21:15:27 Goober5000
* added primaries-depleted and primary-ammo-pct sexps -- useful for ships with
* ballistic primaries
* --Goober5000
*
* Revision 1.12 2002/12/22 17:23:38 Goober5000
* Subcategories implemented. :) So far all that's been done is the Change menu, but other
* subcategorizations are possible. Here are the instructions from sexp.h...
* "Adding more subcategories is possible with the new code. All that needs to be done is
* to add a #define here (a number from 0x0000 to 0x00ff ORred with the category that it
* goes under), some appropriate case statements in get_subcategory() (in sexp.cpp) that
* will return the subcategory for each sexp that uses it, and the submenu name in the
* op_submenu[] array in sexp_tree.cpp."
*
* Please note that I rearranged a whole bunch of sexps in the Operators[] array in sexp.cpp
* in order to make the subcategories work better, so if you get a whole bunch of differences
* or even conflicts, just ignore them. :)
* --Goober5000
*
* Revision 1.11 2002/12/21 17:59:32 Goober5000
* rearranged the sexp list and got the preliminary subcategories working - still need to work on the actual submenu
* --Goober5000
*
* Revision 1.10 2002/12/17 03:19:22 Goober5000
* help for set-scanned and set-unscanned
* --Goober5000
*
* Revision 1.9 2002/12/13 21:10:01 Goober5000
* --fixed an annoying minor bug with distance-ship-subsystem where the sexp tree displayed subsystems for the wrong ship
* --allowed the "hidden sexps" grant-medal, grant-promotion, was-medal-granted, was-promotion-granted, tech-add-ships, and tech-add-weapons to be selectable
* --cleaned up grammar in the help structure a bit
* ~Goober5000~
*
* Revision 1.8 2002/12/12 19:16:51 Goober5000
* corrected /t to be \t
*
* Revision 1.7 2002/12/12 07:57:58 Goober5000
* added help for distance-ship-subsystem sexp; fixed up some grammar and spelling
* ~Goober5000~
*
* Revision 1.6 2002/12/10 04:49:00 righteous1
* Update: Port CATAGORY spelling update to FRED2_OPEN.
* Committer: R1
*
* Revision 1.5 2002/11/28 00:25:57 sesquipedalian
* fixed end-mission help text error
*
* Revision 1.4 2002/11/28 00:01:40 sesquipedalian
* end-mission sexp added
*
* Revision 1.3 2002/10/29 22:42:11 sesquipedalian
* no message
*
* Revision 1.2 2002/08/15 01:06:34 penguin
* Include filename reorg (to coordinate w/ fs2_open)
*
* Revision 1.1.1.1 2002/07/15 03:11:02 inquisitor
* Initial FRED2 Checking
*
*
* 43 9/07/99 9:22p Jefff
* added 2 more assignable medals
*
* 42 9/07/99 1:05a Andsager
* Added team-score sexp for multi team vs team missions
*
* 41 8/27/99 4:07p Andsager
* Add is-ship-visible sexp. Make ship-vanish sexp SINGLE player only
*
* 40 8/24/99 4:25p Andsager
* Add ship-vanish sexp
*
* 39 8/16/99 10:04p Andsager
* Add special-warp-dist and special-warpout-name sexp for Knossos device
* warpout.
*
* 38 8/09/99 2:00p Dave
* 2 new sexpressions.
*
* 37 8/02/99 4:26p Dave
* Added 2 new sexpressions.
*
* 36 8/02/99 1:43p Andsager
* format fix
*
* 35 7/28/99 1:36p Andsager
* Modify cargo1 to include flag CARGO_NO_DEPLETE. Add sexp
* cargo-no-deplete (only for BIG / HUGE). Modify ship struct to pack
* better.
*
* 34 7/24/99 4:56p Dave
* Added 3 new sexpressions.
*
* 33 7/21/99 8:10p Dave
* First run of supernova effect.
*
* 32 7/20/99 9:19p Andsager
* Added facing waypoint sexp
*
* 31 7/20/99 9:54a Andsager
* Add subsys-set-random sexp
*
* 30 7/19/99 12:02p Andsager
* Allow AWACS on any ship subsystem. Fix sexp_set_subsystem_strength to
* only blow up subsystem if its strength is > 0
*
* 29 7/13/99 3:37p Andsager
* Add secondaries-depleted sexp
*
* 28 7/12/99 12:01p Andsager
* Make message by default come from command.
*
* 27 7/08/99 12:06p Andsager
* Add turret-tagged-only and turret-tagged-clear sexp.
*
* 26 6/29/99 10:08a Andsager
* Add guardian sexp
*
* 25 6/23/99 5:51p Andsager
* Add waypoint-cap-speed. Checkin stealth ai - inactive.
*
* 24 6/16/99 10:21a Dave
* Added send-message-list sexpression.
*
* 23 6/01/99 8:35p Dave
* Finished lockarm weapons. Added proper supercap weapons/damage. Added
* awacs-set-radius sexpression.
*
* 22 5/24/99 11:28a Dave
* Sexpression for adding/removing ships from the hud escort list.
*
* 21 5/20/99 1:40p Andsager
* Fix find_text() to only look at nodes that are used.
*
* 20 5/04/99 5:21p Andsager
*
* 19 4/28/99 9:33a Andsager
* Add turret-free and turret-lock (and -all) sexp. Stargger start time
* of beam weapons beam-free and beam-free-all.
*
* 18 4/26/99 2:14p Andsager
* Add beam-protect-ship and beam-unprotect-ship sexp.
*
* 17 4/23/99 12:01p Johnson
* Added SIF_HUGE_SHIP
*
* 16 4/02/99 9:54a Dave
* Added a few more options in the weapons.tbl for beam weapons. Attempt
* at putting "pain" packets into multiplayer.
*
* 15 3/20/99 3:46p Dave
* Added support for model-based background nebulae. Added 3 new
* sexpressions.
*
* 14 3/04/99 6:09p Dave
* Added in sexpressions for firing beams and checking for if a ship is
* tagged.
*
* 13 3/01/99 10:00a Dave
* Fxied several dogfight related stats bugs.
*
* 12 2/26/99 6:01p Andsager
* Add sexp has-been-tagged-delay and cap-subsys-cargo-known-delay
*
* 11 1/26/99 10:09a Andsager
* Better checking for modifying/deleting variables
*
* 10 1/25/99 5:16p Andsager
* Handle change of variable type on modify-variable
*
* 9 1/25/99 8:10a Andsager
* Add sexp_modify_variable(). Changed syntax checking to allow, adding
* operator return type ambiguous
*
* 8 1/24/99 11:37p Dave
* First full rev of beam weapons. Very customizable. Removed some bogus
* Int3()'s in low level net code.
*
* 7 1/20/99 9:02a Andsager
* Fix bug in verify_and_fix_arguments, where list of strings can have
* NULL strings.
*
* 6 1/19/99 3:57p Andsager
* Round 2 of variables
*
* 5 12/17/98 2:39p Andsager
* Added bitmaps for campaign editor. Changed input into insert() to
* include bitmaps
*
* 4 12/17/98 2:34p Andsager
* new bitmap and dialog for campaign editor
*
* 3 10/13/98 9:27a Dave
* Started neatening up freespace.h
*
* 2 10/07/98 6:28p Dave
* Initial checkin. Renamed all relevant stuff to be Fred2 instead of
* Fred. Globalized mission and campaign file extensions. Removed Silent
* Threat specific code.
*
* 1 10/07/98 3:02p Dave
*
* 1 10/07/98 3:00p Dave
*
* 179 9/25/98 1:33p Andsager
* Add color to event editor (root and chain) indicating mission directive
*
* 178 9/15/98 4:26p Allender
* added sexpression help for some sexpressions
*
* 177 6/09/98 5:15p Lawrance
* French/German localization
*
* 176 5/21/98 12:58a Hoffoss
* Fixed warnings optimized build turned up.
*
* 175 5/15/98 6:45p Hoffoss
* Made some things not appear in the release version of Fred.
*
* 174 5/14/98 10:15a Allender
* add optional argument to prevous-goal/event operators to specify what
* sexpression should return when being played as a single mission
*
* 173 5/04/98 10:57a Johnson
* Fixed bug with labeled roots allowing insert.
*
* 172 4/25/98 7:39p Allender
* fixd some small hotkey stuff. Worked on turret orientation being
* correct for multiplayer. new sexpression called end-campaign will will
* end the main campaign
*
* 171 4/23/98 5:49p Hoffoss
* Added tracking of techroom database list info in pilot files, added
* sexp to add more to list, made mouse usable on ship listing in tech
* room.
*
* 170 4/15/98 3:46p Hoffoss
* Fixed bug with getting a default argument value from an opf listing was
* utilizing temporary memory that was being destroyed before we were
* finished with it.
*
* 169 4/14/98 5:46p Hoffoss
* Added special-check operator.
*
* 168 4/14/98 5:24p Hoffoss
* Added a custom operator for training handling for Mike K.
*
* 167 4/14/98 4:19p Jim
* Fixed bug with deleting an argument to an operator that you shouldn't
* be allowed to.
*
* 166 4/07/98 10:51a Allender
* remove any allied from message senders. Make heads for mission
* specific messages play appropriately
*
* 165 4/03/98 12:17a Allender
* new sexpression to detect departed or destroyed. optionally disallow
* support ships. Allow docking with escape pods
*
* 164 3/30/98 2:57p Hoffoss
* Fixed event listing in campaign editor mode.
*
* 163 3/26/98 3:13p Duncan
* Fixed bug in goal name listing generation function. Allender forgot
* about an assumption being made with them when he used it for
* invalidate-goal.
*
* 162 3/23/98 2:46p Hoffoss
* Fixed bug with default argument available for OPF_MESSAGE even when
* there were no messages, and added "#Command" as a message source to
* listing.
*
* 161 3/21/98 7:36p Lawrance
* Move jump nodes to own lib.
*
*
* $NoKeywords: $
*/
#include "stdafx.h"
#include "Sexp_tree.h"
#include "FRED.h"
#include "FREDDoc.h"
#include "Management.h"
#include "parse/sexp.h"
#include "OperatorArgTypeSelect.h"
#include "globalincs/linklist.h"
#include "EventEditor.h"
#include "MissionGoalsDlg.h"
#include "ship/aigoals.h"
#include "mission/missionmessage.h"
#include "mission/missioncampaign.h"
#include "CampaignEditorDlg.h"
#include "hud/hudsquadmsg.h"
#include "IgnoreOrdersDlg.h"
#include "stats/medals.h"
#include "controlconfig/controlsconfig.h"
#include "hud/hudgauges.h"
#include "starfield/starfield.h"
#include "jumpnode/jumpnode.h"
#include "AddVariableDlg.h"
#include "ModifyVariableDlg.h"
#include "gamesnd/eventmusic.h" // for change-soundtrack
#include "menuui/techmenu.h" // for intel stuff
#include "weapon/emp.h"
#include "gamesnd/gamesnd.h"
#include "weapon/weapon.h"
#define MAX_OP_MENUS 30
#define MAX_SUBMENUS (MAX_OP_MENUS * MAX_OP_MENUS)
#define ID_VARIABLE_MENU 0xda00
#define ID_ADD_MENU 0xdc00
#define ID_REPLACE_MENU 0xde00
// note: stay below 0xe000 so we don't collide with MFC defines..
#ifdef _DEBUG
#define new DEBUG_NEW
#undef THIS_FILE
static char THIS_FILE[] = __FILE__;
#endif
BEGIN_MESSAGE_MAP(sexp_tree, CTreeCtrl)
//{{AFX_MSG_MAP(sexp_tree)
ON_NOTIFY_REFLECT(TVN_BEGINDRAG, OnBegindrag)
ON_WM_MOUSEMOVE()
ON_WM_LBUTTONUP()
ON_WM_DESTROY()
ON_WM_LBUTTONDOWN()
ON_NOTIFY_REFLECT(TVN_KEYDOWN, OnKeydown)
//}}AFX_MSG_MAP
END_MESSAGE_MAP()
static int Add_count, Replace_count;
static int Modify_variable;
struct sexp_help_struct {
int id;
char *help;
} Sexp_help[] = {
{ OP_PLUS, "Plus (Arithmetic operator)\r\n"
"\tAdds numbers and returns results.\r\n\r\n"
"Returns a number. Takes 2 or more numeric arguments." },
{ OP_MINUS, "Minus (Arithmetic operator)\r\n"
"\tSubtracts numbers and returns results.\r\n\r\n"
"Returns a number. Takes 2 or more numeric arguments." },
{ OP_MOD, "Mod (Arithmetic operator)\r\n"
"\tDivides numbers and returns the remainer.\r\n\r\n"
"Returns a number. Takes 2 or more numeric arguments." },
{ OP_MUL, "Multiply (Arithmetic operator)\r\n"
"\tMultiplies numbers and returns results.\r\n\r\n"
"Returns a number. Takes 2 or more numeric arguments." },
{ OP_DIV, "Divide (Arithmetic operator)\r\n"
"\tDivides numbers and returns results.\r\n\r\n"
"Returns a number. Takes 2 or more numeric arguments." },
{ OP_RAND, "Random number (Arithmetic operator)\r\n"
"\tGets a random number and returns result.\r\n\r\n"
"Returns a number. Takes 2 numeric arguments...\r\n"
"\t1:\tLow range of random number.\r\n"
"\t2:\tHigh range of random number." },
// Goober5000
{ OP_ABS, "Absolute value (Arithmetic operator)\r\n"
"\tReturns the absolute value of a number. Takes 1 numeric argument.\r\n" },
// Goober5000
{ OP_MIN, "Minimum value (Arithmetic operator)\r\n"
"\tReturns the minimum of a set of numbers. Takes 1 or more numeric arguments.\r\n" },
// Goober5000
{ OP_MAX, "Maximum value (Arithmetic operator)\r\n"
"\tReturns the maximum of a set of numbers. Takes 1 or more numeric arguments.\r\n" },
// Goober5000
{ OP_AVG, "Average value (Arithmetic operator)\r\n"
"\tReturns the average (rounded to the nearest integer) of a set of numbers. Takes 1 or more numeric arguments.\r\n" },
// Goober5000
{ OP_GET_OBJECT_X, "get-object-x\r\n"
"\tReturns the X position of a ship, wing, waypoint, or ship subsystem. "
"Takes 1 or 2 arguments...\r\n"
"\t1: The name of a ship, wing, or waypoint.\r\n"
"\t2: A ship subsystem (optional; ignored if the first argument is not a ship)." },
// Goober5000
{ OP_GET_OBJECT_Y, "get-object-y\r\n"
"\tReturns the Y position of a ship, wing, waypoint, or ship subsystem. "
"Takes 1 or 2 arguments...\r\n"
"\t1: The name of a ship.\r\n"
"\t2: A ship subsystem (optional; ignored if the first argument is not a ship)." },
// Goober5000
{ OP_GET_OBJECT_Z, "get-object-z\r\n"
"\tReturns the Z position of a ship, wing, waypoint, or ship subsystem. "
"Takes 1 or 2 arguments...\r\n"
"\t1: The name of a ship.\r\n"
"\t2: A ship subsystem (optional; ignored if the first argument is not a ship)." },
// Goober5000
{ OP_GET_OBJECT_RELATIVE_X, "get-object-relative-x\r\n"
"\tReturns the absolute X coordinate of a set of coordinates relative to a particular object. "
"In other words, the input coordinates are the coordinates relative to the object's position and orientation. "
"The coordinate returned is the absolute spatial coordinate. Takes 4 or 5 arguments...\r\n"
"\t1: The name of a ship, wing, or waypoint.\r\n"
"\t2: The relative X coordinate.\r\n"
"\t3: The relative Y coordinate.\r\n"
"\t4: The relative Z coordinate.\r\n"
"\t5: The name of a ship subsystem (optional)." },
// Goober5000
{ OP_GET_OBJECT_RELATIVE_Y, "get-object-relative-y\r\n"
"\tReturns the absolute Y coordinate of a set of coordinates relative to a particular object. "
"In other words, the input coordinates are the coordinates relative to the object's position and orientation. "
"The coordinate returned is the absolute spatial coordinate. Takes 4 or 5 arguments...\r\n"
"\t1: The name of a ship, wing, or waypoint.\r\n"
"\t2: The relative X coordinate.\r\n"
"\t3: The relative Y coordinate.\r\n"
"\t4: The relative Z coordinate.\r\n"
"\t5: The name of a ship subsystem (optional)." },
// Goober5000
{ OP_GET_OBJECT_RELATIVE_Z, "get-object-relative-z\r\n"
"\tReturns the absolute Z coordinate of a set of coordinates relative to a particular object. "
"In other words, the input coordinates are the coordinates relative to the object's position and orientation. "
"The coordinate returned is the absolute spatial coordinate. Takes 4 or 5 arguments...\r\n"
"\t1: The name of a ship, wing, or waypoint.\r\n"
"\t2: The relative X coordinate.\r\n"
"\t3: The relative Y coordinate.\r\n"
"\t4: The relative Z coordinate.\r\n"
"\t5: The name of a ship subsystem (optional)." },
// Goober5000
{ OP_SET_SHIP_POSITION, "set-ship-position\r\n"
"\tInstantaneously sets a ship's spatial coordinates."
"Takes 4 arguments...\r\n"
"\t1: The name of a ship.\r\n"
"\t2: The desired new X coordinate.\r\n"
"\t3: The desired new Y coordinate.\r\n"
"\t4: The desired new Z coordinate." },
{ OP_TRUE, "True (Boolean operator)\r\n"
"\tA true boolean state\r\n\r\n"
"Returns a boolean value." },
{ OP_FALSE, "False (Boolean operator)\r\n"
"\tA false boolean state\r\n\r\n"
"Returns a boolean value." },
{ OP_AND, "And (Boolean operator)\r\n"
"\tAnd is true if all of its arguments are true.\r\n\r\n"
"Returns a boolean value. Takes 2 or more boolean arguments." },
{ OP_OR, "Or (Boolean operator)\r\n"
"\tOr is true if any of its arguments are true.\r\n\r\n"
"Returns a boolean value. Takes 2 or more boolean arguments." },
{ OP_EQUALS, "Equals (Boolean operator)\r\n"
"\tIs true if all of its arguments are equal.\r\n\r\n"
"Returns a boolean value. Takes 2 or more numeric arguments." },
{ OP_GREATER_THAN, "Greater than (Boolean operator)\r\n"
"\tTrue if first argument is greater than the second argument.\r\n\r\n"
"Returns a boolean value. Takes 2 numeric arguments." },
{ OP_LESS_THAN, "Less than (Boolean operator)\r\n"
"\tTrue if first argument is less than the second argument.\r\n\r\n"
"Returns a boolean value. Takes 2 numeric arguments." },
// Goober5000 - added wing capability
{ OP_IS_IFF, "Is IFF (Boolean operator)\r\n"
"\tTrue if ship(s) or flight groups(s) are all of the specified IFF.\r\n\r\n"
"Returns a boolean value. Takes 2 or more arguments...\r\n"
"\t1:\tIff (\"Imperial\", \"Rebel\", \"Blue\", \"Yellow\", \"etc\").\r\n"
"\tRest:\tName of ship or flight group to check." },
{ OP_IS_TEAM, "Is team (Boolean operator)\r\n"
"\tTrue if ship(s) or flight groups(s) are all of the specified team.\r\n\r\n"
"Returns a boolean value. Takes 2 or more arguments...\r\n"
"\t1:\tTeam (\"friendly\", \"hostile\", \"neutral\", or \"unknown\").\r\n"
"\tRest:\tName of ship or flight group to check." },
// Goober5000
{ OP_IS_AI_CLASS, "Is AI Class (Boolean operator)\r\n"
"\tTrue if ship or ship subsystem(s) is/are all of the specified AI class.\r\n\r\n"
"Returns a boolean value. Takes 2 or more arguments...\r\n"
"\t1:\tAI class (\"None\", \"Coward\", \"Lieutenant\", etc.)\r\n"
"\t2:\tName of ship to check.\r\n"
"\tRest:\tName of ship subsystem(s) to check (optional)" },
// Goober5000
{ OP_IS_SHIP_TYPE, "Is Ship Type (Boolean operator)\r\n"
"\tTrue if ship or ships is/are all of the specified ship type.\r\n\r\n"
"Returns a boolean value. Takes 2 or more arguments...\r\n"
"\t1:\tShip type (\"fighter\", \"bomber\", etc.)\r\n"
"\t2:\tName of ship to check.\r\n" },
// Goober5000
{ OP_IS_SHIP_CLASS, "Is Ship Class (Boolean operator)\r\n"
"\tTrue if ship or ships is/are all of the specified ship class.\r\n\r\n"
"Returns a boolean value. Takes 2 or more arguments...\r\n"
"\t1:\tShip class\r\n"
"\t2:\tName of ship to check.\r\n" },
{ OP_HAS_TIME_ELAPSED, "Has time elapsed (Boolean operator)\r\n"
"\tBecomes true when the specified amount of time has elapsed (Mission time "
"becomes greater than the specified time).\r\n"
"Returns a boolean value. Takes 1 numeric argument...\r\n"
"\t1:\tThe amount of time in seconds." },
{ OP_NOT, "Not (Boolean operator)\r\n"
"\tReturns opposite boolean value of argument (True becomes false, and "
"false becomes true).\r\n\r\n"
"Returns a boolean value. Takes 1 boolean argument." },
{ OP_PREVIOUS_GOAL_TRUE, "Previous Mission Goal True (Boolean operator)\r\n"
"\tReturns true if the specified goal in the specified mission is true "
"(or succeeded). It returns false otherwise.\r\n\r\n"
"Returns a boolean value. Takes 2 required arguments and 1 optional argument...\r\n"
"\t1:\tName of the mission.\r\n"
"\t2:\tName of the goal in the mission.\r\n"
"\t3:\t(Optional) True/False which signifies what this sexpession should return when "
"this mission is played as a single mission." },
{ OP_PREVIOUS_GOAL_FALSE, "Previous Mission Goal False (Boolean operator)\r\n"
"\tReturns true if the specified goal in the specified mission "
"is false (or failed). It returns false otherwise.\r\n\r\n"
"Returns a boolean value. Takes 2 required arguments and 1 optional argument...\r\n"
"\t1:\tName of the mission.\r\n"
"\t2:\tName of the goal in the mission.\r\n"
"\t3:\t(Optional) True/False which signifies what this sexpession should return when "
"this mission is played as a single mission." },
{ OP_PREVIOUS_GOAL_INCOMPLETE, "Previous Mission Goal Incomplete (Boolean operator)\r\n"
"\tReturns true if the specified goal in the specified mission "
"is incomplete (not true or false). It returns false otherwise.\r\n\r\n"
"Returns a boolean value. Takes 2 required arguments and 1 optional argument...\r\n"
"\t1:\tName of the mission.\r\n"
"\t2:\tName of the goal in the mission.\r\n"
"\t3:\t(Optional) True/False which signifies what this sexpession should return when "
"this mission is played as a single mission." },
{ OP_PREVIOUS_EVENT_TRUE, "Previous Mission Event True (Boolean operator)\r\n"
"\tReturns true if the specified event in the specified mission is true "
"(or succeeded). It returns false otherwise.\r\n\r\n"
"Returns a boolean value. Takes 2 required arguments and 1 optional argument...\r\n"
"\t1:\tName of the mission.\r\n"
"\t2:\tName of the event in the mission.\r\n"
"\t3:\t(Optional) True/False which signifies what this sexpession should return when "
"this mission is played as a single mission." },
{ OP_PREVIOUS_EVENT_FALSE, "Previous Mission Event False (Boolean operator)\r\n"
"\tReturns true if the specified event in the specified mission "
"is false (or failed). It returns false otherwise.\r\n\r\n"
"Returns a boolean value. Takes 2 required arguments and 1 optional argument...\r\n"
"\t1:\tName of the mission.\r\n"
"\t2:\tName of the event in the mission.\r\n"
"\t3:\t(Optional) True/False which signifies what this sexpession should return when "
"this mission is played as a single mission." },
{ OP_PREVIOUS_EVENT_INCOMPLETE, "Previous Mission Event Incomplete (Boolean operator)\r\n"
"\tReturns true if the specified event in the specified mission "
"is incomplete (not true or false). It returns false otherwise.\r\n\r\n"
"Returns a boolean value. Takes 2 required arguments and 1 optional argument...\r\n"
"\t1:\tName of the mission.\r\n"
"\t2:\tName of the event in the mission.\r\n"
"\t3:\t(Optional) True/False which signifies what this sexpession should return when "
"this mission is played as a single mission." },
{ OP_GOAL_TRUE_DELAY, "Mission Goal True (Boolean operator)\r\n"
"\tReturns true N seconds after the specified goal in the this mission is true "
"(or succeeded). It returns false otherwise.\r\n\r\n"
"Returns a boolean value. Takes 2 required arguments and 1 optional argument...\r\n"
"\t1:\tName of the event in the mission.\r\n"
"\t2:\tNumber of seconds to delay before returning true."},
{ OP_GOAL_FALSE_DELAY, "Mission Goal False (Boolean operator)\r\n"
"\tReturns true N seconds after the specified goal in the this mission is false "
"(or failed). It returns false otherwise.\r\n\r\n"
"Returns a boolean value. Takes 2 required arguments and 1 optional argument...\r\n"
"\t1:\tName of the event in the mission.\r\n"
"\t2:\tNumber of seconds to delay before returning true."},
{ OP_GOAL_INCOMPLETE, "Mission Goal Incomplete (Boolean operator)\r\n"
"\tReturns true if the specified goal in the this mission is incomplete. This "
"sexpression will only be useful in conjunction with another sexpression like"
"has-time-elapsed. Used alone, it will return true upon misison startup."
"Returns a boolean value. Takes 1 argument...\r\n"
"\t1:\tName of the event in the mission."},
{ OP_EVENT_TRUE_DELAY, "Mission Event True (Boolean operator)\r\n"
"\tReturns true N seconds after the specified event in the this mission is true "
"(or succeeded). It returns false otherwise.\r\n\r\n"
"Returns a boolean value. Takes 2 arguments...\r\n"
"\t1:\tName of the event in the mission.\r\n"
"\t2:\tNumber of seconds to delay before returning true."},
{ OP_EVENT_FALSE_DELAY, "Mission Event False (Boolean operator)\r\n"
"\tReturns true N seconds after the specified event in the this mission is false "
"(or failed). It returns false otherwise.\r\n\r\n"
"Returns a boolean value. Takes 2 arguments...\r\n"
"\t1:\tName of the event in the mission.\r\n"
"\t2:\tNumber of seconds to delay before returning true."},
{ OP_EVENT_INCOMPLETE, "Mission Event Incomplete (Boolean operator)\r\n"
"\tReturns true if the specified event in the this mission is incomplete. This "
"sexpression will only be useful in conjunction with another sexpression like"
"has-time-elapsed. Used alone, it will return true upon misison startup."
"Returns a boolean value. Takes 1 argument...\r\n"
"\t1:\tName of the event in the mission."},
{ OP_IS_DESTROYED_DELAY, "Is destroyed delay (Boolean operator)\r\n"
"\tBecomes true <delay> seconds after all specified ships have been destroyed.\r\n\r\n"
"Returns a boolean value. Takes 2 or more arguments...\r\n"
"\t1:\tTime delay in seconds (see above).\r\n"
"\tRest:\tName of ship (or wing) to check status of." },
{ OP_IS_SUBSYSTEM_DESTROYED_DELAY, "Is subsystem destroyed delay (Boolean operator)\r\n"
"\tBecomes true <delay> seconds after the specified subsystem of the specified "
"ship is destroyed.\r\n\r\n"
"Returns a boolean value. Takes 3 arguments...\r\n"
"\t1:\tName of ship the subsystem we are checking is on.\r\n"
"\t2:\tThe name of the subsystem we are checking status of.\r\n"
"\t3:\tTime delay in seconds (see above)." },
{ OP_IS_DISABLED_DELAY, "Is disabled delay (Boolean operator)\r\n"
"\tBecomes true <delay> seconds after the specified ship(s) are disabled. A "
"ship is disabled when its system rating is 0%. All ships must be disabled "
"for this function to return true.\r\n\r\n"
"Returns a boolean value. Takes 2 or more arguments...\r\n"
"\t1:\tTime delay is seconds (see above).\r\n"
"\tRest:\tNames of ships to check disabled status of." },
{ OP_IS_DISARMED_DELAY, "Is disarmed delay (Boolean operator)\r\n"
"\tBecomes true <delay> seconds after the specified ship(s) are disarmed. A "
"ship is disarmed when all of its turret subsystems are destroyed. All "
"ships must be disarmed for this function to return true.\r\n\r\n"
"Returns a boolean value. Takes 2 or more arguments...\r\n"
"\t1:\tTime delay is seconds (see above).\r\n"
"\tRest:\tNames of ships to check disarmed status of." },
{ OP_HAS_DOCKED_DELAY, "Has docked delay (Boolean operator)\r\n"
"\tBecomes true <delay> seconds after the specified ships have docked the "
"specified number of times.\r\n\r\n"
"Returns a boolean value. Takes 4 arguments...\r\n"
"\t1:\tThe name of the docker ship\r\n"
"\t2:\tThe name of the dockee ship\r\n"
"\t3:\tThe number of times they have to have docked\r\n"
"\t4:\tTime delay in seconds (see above)." },
{ OP_HAS_UNDOCKED_DELAY, "Has undocked delay (Boolean operator)\r\n"
"\tBecomes true <delay> seconds after the specified ships have undocked the "
"specified number of times.\r\n\r\n"
"Returns a boolean value. Takes 4 arguments...\r\n"
"\t1:\tThe name of the docker ship\r\n"
"\t2:\tThe name of the dockee ship\r\n"
"\t3:\tThe number of times they have to have undocked\r\n"
"\t4:\tTime delay in seconds (see above)." },
{ OP_HAS_ARRIVED_DELAY, "Has arrived delay (Boolean operator)\r\n"
"\tBecomes true <delay> seconds after the specified ship(s) have arrived into the mission\r\n\r\n"
"Returns a boolean value. Takes 2 or more arguments...\r\n"
"\t1:\tTime delay in seconds (see above).\r\n"
"\tRest:\tName of ship (or wing) we want to check has arrived." },
{ OP_HAS_DEPARTED_DELAY, "Has departed delay (Boolean operator)\r\n"
"\tBecomes true <delay> seconds after the specified ship(s) or wing(s) have departed "
"from the mission by warping out. If any ship was destroyed, this operator will "
"never be true.\r\n\r\n"
"Returns a boolean value. Takes 2 or more arguments...\r\n"
"\t1:\tTime delay in seconds (see above).\r\n"
"\tRest:\tName of ship (or wing) we want to check has departed." },
{ OP_WAYPOINTS_DONE_DELAY, "Waypoints done delay (Boolean operator)\r\n"
"\tBecomes true <delay> seconds after the specified ship has completed flying the "
"specified waypoint path.\r\n\r\n"
"Returns a boolean value. Takes 3 arguments...\r\n"
"\t1:\tName of ship we are checking.\r\n"
"\t2:\tWaypoint path we want to check if ship has flown.\r\n"
"\t3:\tTime delay in seconds (see above)." },
{ OP_SHIP_TYPE_DESTROYED, "Ship Type Destroyed (Boolean operator)\r\n"
"\tBecomes true when the specified percentage of ship types in this mission "
"have been destroyed. The ship type is a generic type such as fighter/bomber, "
"transport, etc. Fighters and bombers count as the same type.\r\n\r\n"
"Returns a boolean value. Takes 2 arguments...\r\n"
"\t1:\tPercentage of ships that must be destroyed.\r\n"
"\t2:\tShip type to check for." },
{ OP_TIME_SHIP_DESTROYED, "Time ship destroyed (Time operator)\r\n"
"\tReturns the time the specified ship was destroy.\r\n\r\n"
"Returns a numeric value. Takes 1 argument...\r\n"
"\t1:\tName of ship we want to check." },
{ OP_TIME_SHIP_ARRIVED, "Time ship arrived (Time operator)\r\n"
"\tReturns the time the specified ship arrived into the mission.\r\n\r\n"
"Returns a numeric value. Takes 1 argument...\r\n"
"\t1:\tName of ship we want to check." },
{ OP_TIME_SHIP_DEPARTED, "Time ship departed (Time operator)\r\n"
"\tReturns the time the specified ship departed the mission by warping out. Being "
"destroyed doesn't count departed.\r\n\r\n"
"Returns a numeric value. Takes 1 argument...\r\n"
"\t1:\tName of ship we want to check." },
{ OP_TIME_WING_DESTROYED, "Time wing destroyed (Time operator)\r\n"
"\tReturns the time the specified wing was destroy.\r\n\r\n"
"Returns a numeric value. Takes 1 argument...\r\n"
"\t1:\tName of wing we want to check." },
{ OP_TIME_WING_ARRIVED, "Time wing arrived (Time operator)\r\n"
"\tReturns the time the specified wing arrived into the mission.\r\n\r\n"
"Returns a numeric value. Takes 1 argument...\r\n"
"\t1:\tName of wing we want to check." },
{ OP_TIME_WING_DEPARTED, "Time wing departed (Time operator)\r\n"
"\tReturns the time the specified wing departed the mission by warping out. All "
"ships in the wing have to have warped out. If any are destroyed, the wing can "
"never be considered departed.\r\n\r\n"
"Returns a numeric value. Takes 1 argument...\r\n"
"\t1:\tName of ship we want to check." },
{ OP_MISSION_TIME, "Mission time (Time operator)\r\n"
"\tReturns the current time into the mission.\r\n\r\n"
"Returns a numeric value." },
{ OP_TIME_DOCKED, "Time docked (Time operator)\r\n"
"\tReturns the time the specified ships docked.\r\n\r\n"
"Returns a numeric value. Takes 3 arguments...\r\n"
"\t1:\tThe name of the docker ship.\r\n"
"\t2:\tThe name of the dockee ship.\r\n"
"\t3:\tThe number of times they must have docked to be true." },
{ OP_TIME_UNDOCKED, "Time undocked (Time operator)\r\n"
"\tReturns the time the specified ships undocked.\r\n\r\n"
"Returns a numeric value. Takes 3 arguments...\r\n"
"\t1:\tThe name of the docker ship.\r\n"
"\t2:\tThe name of the dockee ship.\r\n"
"\t3:\tThe number of times they must have undocked to be true." },
{ OP_SHIELDS_LEFT, "Shields left (Status operator)\r\n"
"\tReturns the current level of the specified ship's shields as a percentage.\r\n\r\n"
"Returns a numeric value. Takes 1 argument...\r\n"
"\t1:\tName of ship to check." },
{ OP_HITS_LEFT, "Hits left (Status operator)\r\n"
"\tReturns the current level of the specified ship's hull as a percentage.\r\n\r\n"
"Returns a numeric value. Takes 1 argument...\r\n"
"\t1:\tName of ship to check." },
{ OP_HITS_LEFT_SUBSYSTEM, "Hits left subsystem (Status operator)\r\n"
"\tReturns the current level of the specified ship's subsystem integrity as a percentage.\r\n\r\n"
"Returns a numeric value. Takes 1 argument...\r\n"
"\t1:\tName of ship to check.\r\n"
"\t2:\tName of subsystem on ship to check." },
{ OP_DISTANCE, "Distance (Status operator)\r\n"
"\tReturns the distance between two objects. These objects can be either a ship, "
"a wing, or a waypoint.\r\n\r\n"
"Returns a numeric value. Takes 2 arguments...\r\n"
"\t1:\tThe name of one of the objects.\r\n"
"\t2:\tThe name of the other object." },
{ OP_DISTANCE_SUBSYSTEM, "Distance from ship subsystem (Status operator)\r\n"
"\tReturns the distance between an object and a ship subsystem. The object can be either a ship, "
"a wing, or a waypoint.\r\n\r\n"
"Returns a numeric value. Takes 3 arguments...\r\n"
"\t1:\tThe name of the object.\r\n"
"\t2:\tThe name of the ship which houses the subsystem.\r\n"
"\t3:\tThe name of the subsystem." },
{ OP_LAST_ORDER_TIME, "Last order time (Status operator)\r\n"
"\tReturns true if <count> seconds have elapsed since one or more ships have received "
"a meaningful order from the player. A meaningful order is currently any order that "
"is not the warp out order.\r\n\r\n"
"Returns a boolean value. Takes 2 or more arguments...\r\n"
"\t1:\tTime in seconds that must elapse.\r\n"
"\tRest:\tName of ship or wing to check for having received orders." },
{ OP_WHEN, "When (Conditional operator)\r\n"
"\tPerforms specified actions when a condition becomes true\r\n\r\n"
"Takes 2 or more arguments...\r\n"
"\t1:\tBoolean expression that must be true for actions to take place.\r\n"
"\tRest:\tActions to take when boolean expression becomes true." },
{ OP_COND, "Blah" },
// Goober5000
{ OP_EVERY_TIME, "Every-time (Conditional operator)\r\n"
"\tThis is a version of \"when\" that will always evaluate its arguments. It's useful "
"in situations where you need to repeatedly check things that may become true more than "
"once. Since this sexp will execute every time it's evaluated, you may need to use it as "
"an argument to \"when\" if you want to impose restrictions on how it's called.\r\n\r\n"
"Takes 2 or more arguments...\r\n"
"\t1:\tBoolean expression that must be true for actions to take place.\r\n"
"\tRest:\tActions to take when boolean expression is true." },
// Goober5000 - added wing capability
{ OP_CHANGE_IFF, "Change IFF (Action operator)\r\n"
"\tSets the specified ship(s) or flight group(s) to the specified team.\r\n"
"Takes 2 or more arguments...\r\n"
"\t1:\tIff to change to (\"Imperial\", \"Rebel\", \"Blue\", \"Yellow\", \"etc\").\r\n"
"\tRest:\tName of ship or wing to change team status of." },
{ OP_CHANGE_TEAM, "Change Team (Action operator)\r\n"
"\tSets the specified ship(s) or flight group(s) to the specified team.\r\n"
"Takes 2 or more arguments...\r\n"
"\t1:\tTeam to change to (\"friendly\", \"hostile\" or \"unknown\").\r\n"
"\tRest:\tName of ship or wing to change team status of." },
// Goober5000
{ OP_CHANGE_AI_CLASS, "Change AI Class (Action operator)\r\n"
"\tSets the specified ship or ship subsystem(s) to the specified ai class.\r\n"
"Takes 2 or more arguments...\r\n"
"\t1:\tAI Class to change to (\"None\", \"Coward\", \"Lieutenant\", etc.)\r\n"
"\t2:\tName of ship to change AI class of\r\n"
"\tRest:\tName of subsystem to change AI class of (optional)" },
{ OP_MODIFY_VARIABLE, "Modify-variable (Misc. operator)\r\n"
"\tModifies variable to specified value\r\n\r\n"
"Takes 2 arguments...\r\n"
"\t1:\tName of Variable.\r\n"
"\t2:\tValue to be set." },
{ OP_PROTECT_SHIP, "Protect ship (Action operator)\r\n"
"\tProtects a ship from being attacked by any enemy ship. Any ship"
"that is protected will not come under enemy fire.\r\n\r\n"
"Takes 1 or more arguments...\r\n"
"\tAll:\tName of ship(s) to protect." },
{ OP_UNPROTECT_SHIP, "Unprotect ship (Action operator)\r\n"
"\tUnprotects a ship from being attacked by any enemy ship. Any ship"
"that is not protected can come under enemy fire. This function is the opposite"
"of protect-ship.\r\n\r\n"
"Takes 1 or more arguments...\r\n"
"\tAll:\tName of ship(s) to protect." },
{ OP_BEAM_PROTECT_SHIP, "Beam Protect ship (Action operator)\r\n"
"\tProtects a ship from being attacked with beam weapon. Any ship"
"that is beam protected will not come under enemy beam fire.\r\n\r\n"
"Takes 1 or more arguments...\r\n"
"\tAll:\tName of ship(s) to protect." },
{ OP_BEAM_UNPROTECT_SHIP, "Beam Unprotect ship (Action operator)\r\n"
"\tUnprotects a ship from being attacked with beam weapon. Any ship"
"that is not beam protected can come under enemy beam fire. This function is the opposite"
"of beam-protect-ship.\r\n\r\n"
"Takes 1 or more arguments...\r\n"
"\tAll:\tName of ship(s) to protect." },
{ OP_SEND_MESSAGE, "Send message (Action operator)\r\n"
"\tSends a message to the player. Can be send by a ship, wing, or special "
"source. To send it from a special source, make the first character of the first "
"argument a \"#\".\r\n\r\n"
"Takes 3 arguments...\r\n"
"\t1:\tName of who the message is from.\r\n"
"\t2:\tPriority of message (\"Low\", \"Normal\" or \"High\").\r\n"
"\t3:\tName of message (from message editor)." },
{ OP_SELF_DESTRUCT, "Self destruct (Action operator)\r\n"
"\tCauses the specified ship(s) to self destruct.\r\n\r\n"
"Takes 1 or more arguments...\r\n"
"\tAll:\tName of ship to self destruct." },
{ OP_NEXT_MISSION, "Next Mission (Action operator)\r\n"
"\tThe next mission operator is used for campaign branching in the campaign editor. "
"It specifies which mission should played be next in the campaign. This operator "
"generally follows a 'when' or 'cond' statment in the campaign file.\r\n\r\n"
"Takes 1 argument...\r\n"
"\t1:\tName of mission (filename) to proceed to." },
{ OP_CLEAR_GOALS, "Clear goals (Action operator)\r\n"
"\tClears the goals for the specified ships and/or flight groups.\r\n\r\n"
"Takes 1 or more arguments...\r\n"
"\tAll:\tName of ship or flight group." },
{ OP_ADD_GOAL, "Add goal (Action operator)\r\n"
"\tAdds a goal to a ship or flight group.\r\n\r\n"
"Takes 2 arguments...\r\n"
"\t1:\tName of ship or flight group to all goal to.\r\n"
"\t2:\tGoal to add." },
{ OP_SABOTAGE_SUBSYSTEM, "Sabotage subystem (Action operator)\r\n"
"\tReduces the specified subsystem integrity by the specified percentage."
"If the percentage strength of the subsystem (after completion) is less than 0%,"
"subsystem strength is set to 0%.\r\n\r\n"
"Takes 3 arguments...\r\n"
"\t1:\tName of ship subsystem is on.\r\n"
"\t2:\tName of subsystem to sabotage.\r\n"
"\t3:\tPercentage to reduce subsystem integrity by." },
{ OP_REPAIR_SUBSYSTEM, "Repair Subystem (Action operator)\r\n"
"\tIncreases the specified subsystem integrity by the specified percentage."
"If the percntage strength of the subsystem (after completion) is greater than 100%,"
"subsystem strength is set to 100%.\r\n\r\n"
"Takes 3 arguments...\r\n"
"\t1:\tName of ship subsystem is on.\r\n"
"\t2:\tName of subsystem to repair.\r\n"
"\t3:\tPercentage to increase subsystem integrity by." },
{ OP_SET_SUBSYSTEM_STRNGTH, "Set Subsystem Strength (Action operator)\r\n"
"\tSets the specified subsystem to the the specified percentage."
"If the percentage specified is < 0, strength is set to 0. If the percentage is "
"> 100 % the subsystem strength is set to 100%.\r\n\r\n"
"Takes 3 arguments...\r\n"
"\t1:\tName of ship subsystem is on.\r\n"
"\t2:\tName of subsystem to set strength.\r\n"
"\t3:\tPercentage to set subsystem integrity to." },
{ OP_INVALIDATE_GOAL, "Invalidate goal (Action operator)\r\n"
"\tMakes a mission goal invalid, which causes it to now show up on mission goals "
"screen, or be evaluated.\r\n"
"Takes 1 or more arguments...\r\n"
"\tAll:\tName of mission goal to invalidate." },
{ OP_VALIDATE_GOAL, "Validate goal (Action operator)\r\n"
"\tMakes a mission goal valid again, so it shows up on mission goals screen.\r\n"
"Takes 1 or more arguments...\r\n"
"\tAll:\tName of mission goal to validate." },
{ OP_SEND_RANDOM_MESSAGE, "Send random message (Action operator)\r\n"
"\tSends a random message to the player from those supplied. Can be send by a "
"ship, wing, or special source. To send it from a special source, make the first "
"character of the first argument a \"#\".\r\n\r\n"
"Takes 3 or more arguments...\r\n"
"\t1:\tName of who the message is from.\r\n"
"\t2:\tPriority of message (\"Low\", \"Normal\" or \"High\")."
"\tRest:\tName of message (from message editor)." },
{ OP_TRANSFER_CARGO, "Transfer Cargo (Action operator)\r\n"
"\tTransfers the cargo from one ship to another ship.\r\n\r\n"
"Takes 2 arguments...\r\n"
"\t1:\tName of ship that cargo is being transferred from.\r\n"
"\t2:\tName of ship that cargo is being transferred to." },
{ OP_EXCHANGE_CARGO, "Exchange Cargo (Action operator)\r\n"
"\tExchanges the cargos of two ships. If one of the two ships contains no cargo, "
"the cargo is transferred instead.\r\n"
"Takes 2 arguments...\r\n"
"\t1:\tName of one of the ships.\r\n"
"\t2:\tName of the other ship." },
// Goober5000
{ OP_SET_CARGO, "Set Cargo (Action operator)\r\n"
"\tSets the cargo on a ship or ship subsystem. The cargo-no-deplete flag status is carried through to the new cargo.\r\n"
"Takes 2 or 3 arguments...\r\n"
"\t1:\tName of the cargo\r\n"
"\t2:\tName of the ship\r\n"
"\t3:\tName of the ship subsystem (optional)" },
// Goober5000
{ OP_IS_CARGO, "Is Cargo (Status operator)\r\n"
"\tChecks whether the specified ship or ship subsystem contains a particular cargo.\r\n"
"Takes 2 or 3 arguments...\r\n"
"\t1:\tName of the cargo\r\n"
"\t2:\tName of the ship\r\n"
"\t3:\tName of the ship subsystem (optional)" },
// Goober5000
{ OP_CHANGE_SOUNDTRACK, "change-soundtrack\r\n"
"\tChanges the mission music. Takes 1 argument...\r\n"
"\1: Name of the music selection (taken from music.tbl)" },
// Goober5000
{ OP_PLAY_SOUND_FROM_TABLE, "play-sound-from-table\r\n"
"\tPlays a sound listed in the Game Sounds section of sounds.tbl. Takes 4 arguments...\r\n"
"\t1: Origin X\r\n"
"\t2: Origin Y\r\n"
"\t3: Origin Z\r\n"
"\t4: Sound (index into sounds.tbl)" },
// Goober5000
{ OP_PLAY_SOUND_FROM_FILE, "play-sound-from-file\r\n"
"\tPlays a sound, such as a music soundtrack, from a file. Important: Only one sound at a time can be played with this sexp!\r\n"
"Takes 1 or 2 arguments...\r\n"
"\t1: Sound (file name)\r\n"
"\t2: Enter a non-zero number to loop. default is off (optional)."
},
// Goober5000
{ OP_CLOSE_SOUND_FROM_FILE, "close-sound-from-file\r\n"
"\tCloses the currently playing sound started by play-sound-from-file, if there is any. Takes 1 argument...\r\n"
"\t1: Fade (default is true)" },
// Goober5000
{ OP_EXPLOSION_EFFECT, "explosion-effect\r\n"
"\tCauses an explosion at a given origin, with the given parameters. "
"Takes 11 or 13 arguments...\r\n"
"\t1: Origin X\r\n"
"\t2: Origin Y\r\n"
"\t3: Origin Z\r\n"
"\t4: Damage\r\n"
"\t5: Blast force\r\n"
"\t6: Size of explosion (if 0, explosion will not be visible)\r\n"
"\t7: Inner radius to apply damage (if 0, explosion will not be visible)\r\n"
"\t8: Outer radius to apply damage (if 0, explosion will not be visible)\r\n"
"\t9: Shockwave speed (if 0, there will be no shockwave)\r\n"
"\t10: Type (0 = medium, 1 = large1, 2 = large2)\r\n"
"\t11: Sound (index into sounds.tbl)\r\n"
"\t12: EMP intensity (optional)\r\n"
"\t13: EMP duration in seconds (optional)" },
// Goober5000
{ OP_WARP_EFFECT, "warp-effect\r\n"
"\tCauses a subspace warp effect at a given origin, facing toward a given location, with the given parameters.\r\n"
"Takes 12 arguments...\r\n"
"\t1: Origin X\r\n"
"\t2: Origin Y\r\n"
"\t3: Origin Z\r\n"
"\t4: Location X\r\n"
"\t5: Location Y\r\n"
"\t6: Location Z\r\n"
"\t7: Radius\r\n"
"\t8: Duration in seconds\r\n"
"\t9: Warp opening sound (index into sounds.tbl)\r\n"
"\t10: Warp closing sound (index into sounds.tbl)\r\n"
"\t11: Type (0 for standard blue [default], 1 for Knossos green)\r\n"
"\t12: Effect (0 for Bobboau's new effect [default], 1 for original FS2 effect)" },
// Goober5000
{ OP_SET_SHIP_FACING, "set-ship-facing\r\n"
"\tSets a ship's orientation to face the specified coordinates."
"Takes 4 arguments...\r\n"
"\t1: The name of a ship.\r\n"
"\t2: The X coordinate to face.\r\n"
"\t3: The Y coordinate to face.\r\n"
"\t4: The Z coordinate to face." },
// Goober5000
{ OP_SET_SHIP_FACING_OBJECT, "set-ship-facing-object\r\n"
"\tSets a ship's orientation to face the specified object."
"Takes 2 arguments...\r\n"
"\t1: The name of a ship.\r\n"
"\t2: The object to face." },
/* made obsolete by Goober5000 - it only works in debug builds anyway
{ OP_INT3, "Error (Debug directive)\r\n"
"Causes the game to halt with an error." },
*/
{ OP_AI_CHASE, "Ai-chase (Ship goal)\r\n"
"\tCauses the specified ship to chase and attack the specified target.\r\n\r\n"
"Takes 2 arguments...\r\n"
"\t1:\tName of ship to chase.\r\n"
"\t2:\tGoal priority (number between 0 and 89)." },
{ OP_AI_DOCK, "Ai-dock (Ship goal)\r\n"
"\tCauses one ship to dock with another ship.\r\n\r\n"
"Takes 4 arguments...\r\n"
"\t1:\tName of dockee ship (The ship that \"docker\" will dock with).\r\n"
"\t2:\tDocker's docking point - Which dock point docker uses to dock.\r\n"
"\t3:\tDockee's docking point - Which dock point on dockee docker will move to.\r\n"
"\t4:\tGoal priority (number between 0 and 89)." },
{ OP_AI_UNDOCK, "Ai-undock (Ship goal)\r\n"
"\tCauses the specified ship to undock from who it is currently docked with.\r\n\r\n"
"Takes 1 argument...\r\n"
"\t1:\tGoal priority (number between 0 and 89)." },
{ OP_AI_WARP_OUT, "Ai-hyper-out (Ship/Flight Group Goal)\r\n"
"\tCauses the specified Ship/Flight Group to hyper out of the mission. If a hyperspace buoy "
"has been specified Ship/Flight Group will fly to it before hypering out. \r\n\r\n"
"Takes 1 arguments...\r\n"
"\t1:\tGoal priority (number between 0 and 89)." },
{ OP_AI_WAYPOINTS, "Ai-waypoints (Ship goal)\r\n"
"\tCauses the specified ship to fly a waypoint path continuously.\r\n\r\n"
"Takes 2 arguments...\r\n"
"\t1:\tName of waypoint path to fly.\r\n"
"\t2:\tGoal priority (number between 0 and 89)." },
{ OP_AI_WAYPOINTS_ONCE, "Ai-waypoints-once (Ship goal)\r\n"
"\tCauses the specified ship to fly a waypoint path.\r\n\r\n"
"Takes 2 arguments...\r\n"
"\t1:\tName of waypoint path to fly.\r\n"
"\t2:\tGoal priority (number between 0 and 89)." },
{ OP_AI_DESTROY_SUBSYS, "Ai-destroy subsys (Ship goal)\r\n"
"\tCauses the specified ship to attack and try and destroy the specified subsystem "
"on the specified ship.\r\n\r\n"
"Takes 3 arguments...\r\n"
"\t1:\tName of ship subsystem is on.\r\n"
"\t2:\tName of subsystem on the ship to attack and destroy.\r\n"
"\t3:\tGoal priority (number between 0 and 89)." },
{ OP_AI_CHASE_WING, "Ai-chase flight group (Ship goal)\r\n"
"\tCauses the specified ship to chase and attack the specified target.\r\n\r\n"
"Takes 2 arguments...\r\n"
"\t1:\tName of flight group to chase.\r\n"
"\t2:\tGoal priority (number between 0 and 89)." },
{ OP_AI_DISABLE_SHIP, "Ai-disable-ship (Ship/Flight Group goal)\r\n"
"\tThis AI goal causes a Ship/Flight Group to disable the craft for boarding.\r\n\r\n"
"Takes 2 arguments...\r\n"
"\t1:\tName of ship to be disabled\r\n"
"\t2:\tGoal priority (number between 0 and 89)." },
{ OP_AI_DISABLE_ENGINES, "Ai-disable-engines (Ship/Flight Group goal)\r\n"
"\tThis AI goal causes a Ship/Flight Group to destroy all of the engine subsystems on "
"the specified ship. This goal is different than ai-destroy-subsystem since a ship "
"may have multiple engine subsystems requiring the use of > 1 ai-destroy-subsystem "
"goals.\r\n\r\n"
"Takes 2 arguments...\r\n"
"\t1:\tName of ship whose engine subsystems should be destroyed\r\n"
"\t2:\tGoal priority (number between 0 and 89)." },
{ OP_AI_DISARM_SHIP, "Ai-disarm-ship (Ship/Flight Group goal)\r\n"
"\tThis AI goal causes a Ship/Flight Group to destroy all of the turret subsystems on "
"the specified ship. This goal is different than ai-destroy-subsystem since a ship "
"may have multiple turret subsystems requiring the use of > 1 ai-destroy-subsystem "
"goals.\r\n\r\n"
"Takes 2 arguments...\r\n"
"\t1:\tName of ship whose turret subsystems should be destroyed\r\n"
"\t2:\tGoal priority (number between 0 and 89)." },
{ OP_AI_GUARD, "Ai-guard (Ship goal)\r\n"
"\tCauses the specified ship to guard a ship from other ships not on the same team.\r\n\r\n"
"Takes 2 arguments...\r\n"
"\t1:\tName of ship to guard.\r\n"
"\t2:\tGoal priority (number between 0 and 89)." },
{ OP_AI_CHASE_ANY, "Ai-chase-any (Ship goal)\r\n"
"\tCauses the specified ship to chase and attack any ship on the opposite team.\r\n\r\n"
"Takes 1 argument...\r\n"
"\t1:\tGoal priority (number between 0 and 89)." },
// Goober5000
{ OP_AI_CHASE_ANY_EXCEPT, "Ai-chase-any-except (Ship goal)\r\n"
"\tCauses the specified ship to chase and attack any ship on the opposite team except those listed.\r\n\r\n"
"Takes between 1 and 33 arguments...\r\n"
"\t1:\tGoal priority (number between 0 and 89).\r\n"
"\tRest:\tList (up to 32 entries) of ships or flight groups to exclude from consideration as attackable targets (optional).\r\n\r\n"
"NOTE: If no ships or flight groups are specified, this will function just like the regular ai-chase-any sexp." },
{ OP_AI_GUARD_WING, "Ai-guard flight group (Ship goal)\r\n"
"\tCauses the specified ship to guard a flight group of ships from other ships not on the "
"same team.\r\n\r\n"
"Takes 2 arguments...\r\n"
"\t1:\tName of wing to guard.\r\n"
"\t2:\tGoal priority (number between 0 and 89)." },
{ OP_NOP, "Do-nothing (Action operator)\r\n"
"\tDoes nothing. This is used as the default for any required action arguments "
"of an operator." },
{ OP_KEY_PRESSED, "Key-pressed (Boolean training operator)\r\n"
"\tBecomes true when the specified default key has been pressed. Default key "
"refers to the what the key normally is when not remapped. FreeSpace will "
"automatically account for any keys that have been remapped. If the optional "
"delay is specified, becomes true that many seconds after the key has been pressed.\r\n\r\n"
"Returns a boolean value. Takes 1 or 2 arguments...\r\n"
"\t1:\tDefault key to check for.\r\n"
"\t2:\tDelay before operator registers as true (optional).\r\n" },
{ OP_KEY_RESET, "Key-reset (Training operator)\r\n"
"\tMarks the specified default key as having not been pressed, so key-pressed will be false "
"until the player presses it again. See key-pressed help for more information about "
"what a default key is.\r\n\r\n"
"Returns a boolean value. Takes 1 argument...\r\n"
"\t1:\tDefault key to reset." },
{ OP_TARGETED, "Targeted (Boolean training operator)\r\n"
"\tIs true as long as the player has the specified ship (or ship's subsystem) targeted, "
"or has been targeted for the specified amount of time.\r\n\r\n"
"Returns a boolean value. Takes 1 to 3 arguments (first required, rest optional):\r\n"
"\t1:\tName of ship to check if targeted by player.\r\n"
"\t2:\tLength of time target should have been kept for (optional).\r\n"
"\t3:\tName of subsystem on ship to check if targeted (optional)." },
// Sesquipedalian
{ OP_MISSILE_LOCKED, "Missile-locked (Boolean training operator)\r\n"
"\tIs true as long as the player has had a missile lock for the specified amount of time. "
"Optional arguments require lock to be maintained on a specified ship (or ship's subsystem).\r\n\r\n"
"Returns a boolean value. Takes 1 to 3 arguments (first required, rest optional):\r\n"
"\t1:\tLength of time missile lock should have been kept for.\r\n"
"\t2:\tName of ship to check if locked onto by player (optional).\r\n"
"\t3:\tName of subsystem on ship to check if locked onto (optional)." },
{ OP_SPEED, "Speed (Boolean training operator)\r\n"
"\tBecomes true when the player has been within the specified speed range set by "
"set-training-context-speed for the specified amount of time.\r\n\r\n"
"Returns a boolean value. Takes 1 argument...\r\n"
"\t1:\tTime in seconds." },
{ OP_FACING, "Facing (Boolean training operator)\r\n"
"\tIs true as long as the specified ship is within the player's specified "
"forward cone. A forward cone is defined as any point that the angle between the "
"vector of the point and the player, and the forward facing vector is within the "
"given angle.\r\n\r\n"
"Returns a boolean value. Takes 2 argument...\r\n"
"\t1:\tShip to check is withing forward cone.\r\n"
"\t2:\tAngle in degrees of the forward cone." },
{ OP_FACING2, "Facing Waypoint(Boolean training operator)\r\n"
"\tIs true as long as the specified first waypoint is within the player's specified "
"forward cone. A forward cone is defined as any point that the angle between the "
"vector of the point and the player, and the forward facing vector is within the "
"given angle.\r\n\r\n"
"Returns a boolean value. Takes 2 argument...\r\n"
"\t1:\tName of waypoint path whose first point is withing forward cone.\r\n"
"\t2:\tAngle in degrees of the forward cone." },
// fixed by Goober5000
{ OP_ORDER, "Order (Boolean training operator)\r\n"
"\tBecomes true when the player had given the specified ship or wing the specified order.\r\n\r\n"
"Returns a boolean value. Takes 2 or 3 arguments...\r\n"
"\t1:\tName of ship or wing to check if given order to.\r\n"
"\t2:\tName of order to check if player has given.\r\n"
"\t3:\tName of the target of the order (optional)." },
{ OP_WAYPOINT_MISSED, "Waypoint-missed (Boolean training operator)\r\n"
"\tBecomes true when a waypoint is flown, but the waypoint is ahead of the one "
"they are supposed to be flying. The one they are supposed to be flying is the "
"next one in sequence in the path after the last one they have hit.\r\n\r\n"
"Returns a boolean value. Takes no arguments." },
{ OP_PATH_FLOWN, "Path-flown (Boolean training operator)\r\n"
"\tBecomes true when all the waypoints in the path have been flown, in sequence.\r\n\r\n"
"Returns a boolean value. Takes no arguments." },
{ OP_WAYPOINT_TWICE, "Waypoint-twice (Boolean training operator)\r\n"
"\tBecomes true when a waypoint is hit that is before the last one hit, which "
"indicates they have flown a waypoint twice.\r\n\r\n"
"Returns a boolean value. Takes no arguments." },
{ OP_TRAINING_MSG, "Training-msg (Action training operator)\r\n"
"\tSends the player a training message. Uses the same messages as normal messages, "
"only they get displayed differently using this operator. If a secondary message "
"is specified, it is sent the last time, while the primary message is sent all other "
"times (event should have a repeat count greater than 1).\r\n\r\n"
"Takes 1-3 arguments...\r\n"
"\t1:\tName of primary message to send.\r\n"
"\t2:\tName of secondary message to send (optional).\r\n"
"\t3:\tDelay (in seconds) to wait before sending message. (optional)\r\n"
"\t4:\tAmount of Time (in seconds) to display message (optional)." },
{ OP_SET_TRAINING_CONTEXT_FLY_PATH, "Set-training-context-fly-path (Training context operator)\r\n"
"\tTells Imperial Alliance that the player is expected to fly a waypoint path. This must be "
"executed before waypoint-missed, waypoint-twice and path-flown operators become valid.\r\n\r\n"
"Takes 2 arguments...\r\n"
"\t1:\tName of waypoint path player should fly.\r\n"
"\t2:\tDistance away a player needs to be from a waypoint for it to be registered as flown." },
{ OP_SET_TRAINING_CONTEXT_SPEED, "Set-training-context-speed (Training context operator)\r\n"
"\tTells Imperial Alliance that the player is expected to fly within a certain speed range. Once "
"this operator has been executed, you can measure how long they have been within this "
"speed range with the speed operator.\r\n\r\n"
"Takes 2 arguments...\r\n"
"\t1:\tMinimum speed of range player is to fly between.\r\n"
"\t2:\tMaximum speed of range player is to fly between." },
{ OP_GRANT_PROMOTION, "Grant promotion (Action operator)\r\n"
"\tIn a single player game, this function grants a player an automatic promotion to the "
"next rank which the player can obtain. If he is already at the highest rank, this "
"operator has no effect. It takes no arguments." },
{ OP_GRANT_MEDAL, "Grant medal (Action operator)\r\n"
"\tIn single player missions, this function grants the given medal to the player. "
"Currently, only 1 medal will be allowed to be given per mission.\r\n\r\n"
"Takes 1 argument...\r\n"
"\t1:\tName of medal to grant to player." },
{ OP_GOOD_SECONDARY_TIME, "Set prefered secondary weapons\r\n"
"\tThis sexpression is used to inform the AI about prefered secondary weapons to "
"fire during combat. When this expression is evaulated, any AI ships of the given "
"team prefer to fire the given weapon at the given ship. (Prefered over other "
"secondary weapons)\r\n\r\n"
"Takes 4 argument...\r\n"
"\t1:\tTeam name which will prefer firing given weapon\r\n"
"\t2:\tMaximum number of this type of weapon above team can fire.\r\n"
"\t3:\tWeapon name (list includes only the valid weapons for this expression\r\n"
"\t4:\tShip name at which the above named team should fire the above named weapon." },
{ OP_AND_IN_SEQUENCE, "And in sequence (Boolean operator)\r\n"
"\tReturns true if all of its arguments have become true in the order they are "
"listed in.\r\n\r\n"
"Returns a boolean value. Takes 2 or more boolean arguments." },
{ OP_SKILL_LEVEL_AT_LEAST, "Skill level at least (Boolean operator)\r\n"
"\tReturns true if the player has selected the given skill level or higher.\r\n\r\n"
"Returns a boolean value. Takes 1 argument...\r\n"
"\t1:\tName of the skill level to check." },
{ OP_NUM_PLAYERS, "Num players (Status operator)\r\n"
"\tReturns the current number of players (multiplayer) playing in the current mission.\r\n\r\n"
"Returns a numeric value. Takes no arguments." },
{ OP_IS_CARGO_KNOWN, "Is cargo known (Boolean operator)\r\n"
"\tReturns true if all of the specified objects' cargo is known by the player (i.e. they "
"have scanned each one.\r\n\r\n"
"Returns a boolean value. Takes 1 or more arguments...\r\n"
"\tAll:\tName of ship to check if its cargo is known." },
{ OP_HAS_BEEN_TAGGED_DELAY, "Has ship been tagged (delay) (Boolean operator)\r\n"
"\tReturns true if all of the specified ships have been tagged.\r\n\r\n"
"Returns a boolean value after <delay> seconds when all ships have been tagged. Takes 2 or more arguments...\r\n"
"\t1:\tDelay in seconds after which sexpression will return true when all cargo scanned."
"\tRest:\tNames of ships to check if tagged.." },
{ OP_CAP_SUBSYS_CARGO_KNOWN_DELAY, "Is capital ship subsystem cargo known (delay) (Boolean operator)\r\n"
"\tReturns true if all of the specified subsystem cargo is known by the player.\r\n"
"\tNote: Cargo must be explicitly named.\r\n\r\n"
"Returns a boolean value after <delay> seconds when all cargo is known. Takes 3 or more arguments...\r\n"
"\t1:\tDelay in seconds after which sexpression will return true when all cargo scanned.\r\n"
"\t2:\tName of capital ship\r\n"
"\tRest:\tNames of subsystems to check for cargo known.." },
{ OP_CARGO_KNOWN_DELAY, "Is cargo known (delay) (Boolean operator)\r\n"
"\tReturns true if all of the specified objects' cargo is known by the player (i.e. they "
"have scanned each one.\r\n\r\n"
"Returns a boolean value after <delay> seconds when all cargo is known. Takes 2 or more arguments...\r\n"
"\t1:\tDelay in seconds after which sexpression will return true when all cargo scanned."
"\tRest:\tNames of ships/cargo to check for cargo known.." },
{ OP_WAS_PROMOTION_GRANTED, "Was promotion granted (Boolean operator)\r\n"
"\tReturns true if a promotion was granted via the 'Grant promotion' operator in the mission.\r\n\r\n"
"Returns a boolean value. Takes no arguments." },
{ OP_WAS_MEDAL_GRANTED, "Was medal granted (Boolean operator)\r\n"
"\tReturns true if a medal was granted via via the 'Grant medal' operator in the mission. "
"If you provide the optional argument to this operator, then true is only returned if the "
"specified medal was granted.\r\n\r\n"
"Returns a boolean value. Takes 0 or 1 arguments...\r\n"
"\t1:\tName of medal to specifically check for (optional)." },
{ OP_GOOD_REARM_TIME, "Good rearm time (Action operator)\r\n"
"\tInforms the game logic that right now is a good time for a given team to attempt to "
"rearm their ships. The time parameter specified how long the \"good time\" will last.\r\n\r\n"
"Takes 2 arguments...\r\n"
"\t1:\tTeam Name\r\n"
"\t2:\tTime in seconds rearm window should last" },
{ OP_ALLOW_SHIP, "Allow ship (Action operator)\r\n"
"\tThis operator makes the given ship type available to the Imperial team. Players will be "
"able to have ships of this type in their starting flight groups in all future missions of this "
"campaign.\r\n\r\n"
"Takes 1 argument...\r\n"
"\t1:\tName of ship type (or ship class) to allow." },
{ OP_ALLOW_WEAPON, "Allow weapon (Action operator)\r\n"
"\tThis operator makes the given weapon available to the Imperial team. Players will be "
"able to equip ships with in all future missions of this campaign.\r\n\r\n"
"Takes 1 argument...\r\n"
"\t1:\tName of weapon (primary or secondary) to allow." },
{ OP_TECH_ADD_SHIP, "Tech add ship (Action operator)\r\n"
"\tThis operator makes the given ship type available in the techroom database. Players will "
"then be able to view this ship's specs there.\r\n\r\n"
"Takes 1 or more arguments...\r\n"
"\tAll:\tName of ship type (or ship class) to add." },
{ OP_TECH_ADD_WEAPON, "Tech add weapon (Action operator)\r\n"
"\tThis operator makes the given weapon available in the techroom database. Players will "
"then be able to view this weapon's specs there.\r\n\r\n"
"Takes 1 or more arguments...\r\n"
"\tAll:\tName of weapon (primary or secondary) to add." },
{ OP_TECH_ADD_INTEL, "Tech add intel (Action operator)\r\n"
"\tThis operator makes the given intel entry available in the techroom database. Players will "
"then be able to view this intel entry there.\r\n\r\n"
"Takes 1 or more arguments...\r\n"
"\tAll:\tName of intel entry to add." },
{ OP_TECH_RESET_TO_DEFAULT, "Tech reset to default (Action operator)\r\n"
"\tThis operator resets the tech room to the default represented in the tables. This is "
"useful for starting new campaigns, so that the player will not see tech entries carried over "
"from previous campaigns.\r\n\r\n"
"Takes no arguments." },
{ OP_AI_EVADE_SHIP, "Ai-evade ship (Ship goal)\r\n"
"\tCauses the specified ship to go into evade mode and run away like the weak "
"sally-boy it is.\r\n\r\n"
"Takes 2 arguments...\r\n"
"\t1:\tName of ship to evade from.\r\n"
"\t2:\tGoal priority (number between 0 and 89)." },
{ OP_AI_STAY_NEAR_SHIP, "Ai-stay near ship (Ship goal)\r\n"
"\tCauses the specified ship to keep itself near the given ship and not stray too far "
"away from it.\r\n\r\n"
"Takes 2 arguments...\r\n"
"\t1:\tName of ship to stay near.\r\n"
"\t2:\tGoal priority (number between 0 and 89)." },
{ OP_AI_KEEP_SAFE_DISTANCE, "Ai-keep safe distance (Ship goal)\r\n"
"\tTells the specified ship to stay a safe distance away from any ship that isn't on the "
"same team as it.\r\n\r\n"
"Takes 1 argument...\r\n"
"\t1:\tGoal priority (number between 0 and 89)." },
{ OP_AI_IGNORE, "Ai-ignore (Ship goal)\r\n"
"\tTells the specified ship to ignore the given ship and not consider it as a valid "
"target to attack.\r\n\r\n"
"Takes 2 arguments...\r\n"
"\t1:\tName of ship to ignore.\r\n"
"\t2:\tGoal priority (number between 0 and 89)." },
{ OP_AI_STAY_STILL, "Ai-stay still (Ship goal)\r\n"
"\tCauses the specified ship to stay still. The ship will do nothing until attacked at "
"which time the ship will come to life and defend itself.\r\n\r\n"
"Takes 2 arguments...\r\n"
"\t1:\tShip or waypoint the ship staying still will directly face (currently not implemented)\r\n"
"\t2:\tGoal priority (number between 0 and 89)." },
{ OP_AI_PLAY_DEAD, "Ai-play dead (Ship goal)\r\n"
"\tCauses the specified ship to pretend that it is dead and not do anything. This "
"expression should be used to indicate that a ship has no pilot and cannot respond "
"to any enemy threats. A ship playing dead will not respond to any attack. This "
"should really be named ai-is-dead\r\n\r\n"
"Takes 1 argument...\r\n"
"\t1:\tGoal priority (number between 0 and 89)." },
{ OP_FLASH_HUD_GAUGE, "Ai-flash hud gauge (Training goal)\r\n"
"\tCauses the specified hud gauge to flash to draw the player's attention to it.\r\n\r\n"
"Takes 1 argument...\r\n"
"\t1:\tName of hud gauge to flash." },
{ OP_SHIP_VISIBLE, "ship-visible\r\n"
"\tCauses the ships listed in this sexpression to be visible with player sensors.\r\n\r\n"
"Takes 1 or more arguments...\r\n"
"\t1+:\tName of ships to make visible to sensors." },
{ OP_SHIP_INVISIBLE, "ship-invisible\r\n"
"\tCauses the ships listed in this sexpression to be invisible to player sensors.\r\n\r\n"
"Takes 1 or more arguments...\r\n"
"\t1+:\tName of ships to make invisible to sensors." },
{ OP_SHIP_VULNERABLE, "ship-vulnerable\r\n"
"\tCauses the ship listed in this sexpression to be vulnerable to weapons.\r\n\r\n"
"Takes 1 or more arguments...\r\n"
"\t1+:\tName of ships to make vulnerable to weapons." },
{ OP_SHIP_INVULNERABLE, "ship-invulnerable\r\n"
"\tCauses the ships listed in this sexpression to be invulnerable to weapons. Use with caution!!!!\r\n\r\n"
"Takes 1 or more arguments...\r\n"
"\t1+:\tName of ships to make invulnerable to weapons." },
{ OP_SHIELDS_ON, "shields-on\r\n" //-Sesquipedalian
"\tCauses the ship listed in this sexpression to have their shields activated.\r\n\r\n"
"Takes 1 or more arguments...\r\n"
"\t1+:\tName of ships to activate shields on." },
{ OP_SHIELDS_OFF, "shields-off\r\n" //-Sesquipedalian
"\tCauses the ships listed in this sexpression to have their shields deactivated. \r\n\r\n"
"Takes 1 or more arguments...\r\n"
"\t1+:\tName of ships to deactivate shields on." },
{ OP_SHIP_GUARDIAN, "ship-guardian\r\n"
"\tCauses the ships listed in this sexpression to not be killable by weapons. Use with caution!!!!\r\n\r\n"
"Takes 1 or more arguments...\r\n"
"\t1+:\tName of ships to make unkillable." },
{ OP_SHIP_NO_GUARDIAN, "ship-no-guardian\r\n"
"\tCauses the ships listed in this sexpression to be killable by weapons, if not invulnerable.\r\n\r\n"
"Takes 1 or more arguments...\r\n"
"\t1+:\tName of ships to make killable." },
// Goober5000
{ OP_SHIP_STEALTHY, "ship-stealthy\r\n"
"\tCauses the ships listed in this sexpression to become stealth ships (i.e. invisible to radar).\r\n\r\n"
"Takes 1 or more arguments...\r\n"
"\tAll:\tName of ships to make stealthy." },
// Goober5000
{ OP_SHIP_UNSTEALTHY, "ship-unstealthy\r\n"
"\tCauses the ships listed in this sexpression to become non-stealth ships (i.e. visible to radar).\r\n\r\n"
"Takes 1 or more arguments...\r\n"
"\tAll:\tName of ships to make non-stealthy." },
// Goober5000
{ OP_FRIENDLY_STEALTH_INVISIBLE, "friendly-stealth-invisible\r\n"
"\tCauses the friendly ships listed in this sexpression to be invisible to radar, just like hostile stealth ships."
"It doesn't matter if the ship is friendly at the time this sexp executes: as long as it is a stealth ship, it will"
"be invisible to radar both as hostile and as friendly.\r\n\r\n"
"Takes 1 or more arguments...\r\n"
"\tAll:\tName of ships" },
// Goober5000
{ OP_FRIENDLY_STEALTH_VISIBLE, "friendly-stealth-visible\r\n"
"\tCauses the friendly ships listed in this sexpression to resume their normal behavior of being visible to radar as"
"stealth friendlies. Does not affect their visibility as stealth hostiles.\r\n\r\n"
"Takes 1 or more arguments...\r\n"
"\tAll:\tName of ships" },
{ OP_PERCENT_SHIPS_DEPARTED, "percent-ships-departed\r\n"
"\tBoolean function which returns true if the percentage of ships in the listed ships and flight groups "
"which have departed is greater or equal to the given percentage. For flight groups, all ships of all waves "
"are used for calculation for the total possible ships to depart.\r\n\r\n"
"Takes 2 or more arguments...\r\n"
"\t1:\tPercentge of departed ships at which this function will return true.\r\n"
"\t2+:\tList of ships/flight groups whose departure status should be determined." },
{ OP_PERCENT_SHIPS_DESTROYED, "percent-ships-destroyed\r\n"
"\tBoolean function which returns true if the percentage of ships in the listed ships and flight groups "
"which have been destroyed is greater or equal to the given percentage. For wings, all ships of all waves "
"are used for calculation for the total possible ships to be destroyed.\r\n\r\n"
"Takes 2 or more arguments...\r\n"
"\t1:\tPercentge of destroyed ships at which this function will return true.\r\n"
"\t2+:\tList of ships/flight groups whose destroyed status should be determined." },
// Goober5000
{ OP_PERCENT_SHIPS_DISARMED, "percent-ships-disarmed\r\n"
"\tBoolean function which returns true if the percentage of ships in the listed ships "
"which have been disarmed is greater or equal to the given percentage.\r\n\r\n"
"Takes 2 or more arguments...\r\n"
"\t1:\tPercentge of disarmed ships at which this function will return true.\r\n"
"\t2+:\tList of ships whose disarmed status should be determined." },
// Goober5000
{ OP_PERCENT_SHIPS_DISABLED, "percent-ships-disabled\r\n"
"\tBoolean function which returns true if the percentage of ships in the listed ships "
"which have been disabled is greater or equal to the given percentage.\r\n\r\n"
"Takes 2 or more arguments...\r\n"
"\t1:\tPercentge of disabled ships at which this function will return true.\r\n"
"\t2+:\tList of ships whose disabled status should be determined." },
{ OP_RED_ALERT, "red-alert\r\n"
"\tCauses Red Alert status in a mission. This function ends the current mission, and moves to "
"the next mission in the campaign under red alert status. There should only be one branch from "
"a mission that uses this expression\r\n\r\n"
"Takes no arguments."},
//-Sesquipedalian
{ OP_END_MISSION, "end-mission\r\n"
"\tEnds the mission as if the player had engaged his hyperdrive, but without him doing so. Dumps the player back into a normal debriefing. Does not invoke red-alert status.\r\n"
"Takes no arguments." },
// Goober5000
{ OP_FORCE_JUMP, "force-jump\r\n"
"\tForces activation of the player's hyperdrive, thus ending the mission. Takes no arguments."
},
// Goober5000
{ OP_SET_SCANNED, "set-scanned\r\n"
"\tSets the cargo on the specified ship or ship subsystem as known or scanned. Takes 1 or more arguments...\r\n"
"\t1:\tName of a ship\r\n"
"\tRest:\tName of a subsystem on that ship (optional)\r\n" },
// Goober5000
{ OP_SET_UNSCANNED, "set-unscanned\r\n"
"\tSets the cargo on the specified ship or ship subsystem as unknown or unscanned. Takes 1 or more arguments...\r\n"
"\t1:\tName of a ship\r\n"
"\tRest:\tName of a subsystem on that ship (optional)\r\n" },
{ OP_DEPART_JUMP_DELAY, "depart-jump-delay\r\n"
"\tReturns true N seconds after the listed ships depart, if those ships depart within the "
"radius of the given hyper buoy. The delay value is given in seconds.\r\n\r\n"
"Takes 3 or more arguments...\r\n"
"\t1:\tDelay in seconds after the last ship listed departe before this expression can return true.\r\n"
"\t2:\tName of a hyper buoy\r\n"
"\t3+:\tList of ships to check for departure within radius of the hyper buoy." },
{ OP_DESTROYED_DEPARTED_DELAY, "destroyed-or-departed-delay\r\n"
"\tReturns true N seconds after all the listed ships or flight groups have been destroyed or have "
"departed.\r\n\r\n"
"Takes 2 or more arguments...\r\n"
"\t1:\tDelay in seconda after the last Ship/Flight Group is destroyed or departerd this expression can return true.\r\n"
"\t2+:\tName of a ship or flight group" },
// description added by Goober5000
{ OP_SPECIAL_CHECK, "Special-check\r\n"
"\tMike K.'s special training sexp. Returns a boolean value. Takes 1 argument as follows:\r\n"
"\t0: Ship \"Freighter 1\" is aspect locked by the player\r\n"
"\t1: Player has fired Interceptor#Weak at Freighter 1\r\n"
"\t2: Ship \"Freighter 1\", subsystem \"Weapons\" is aspect locked by the player\r\n"
"\t3: Apply 10 points of damage to player's forward shields (action operator)\r\n"
"\t4: Player's front shields are nearly gone\r\n"
"\t5: Quickly recharge player's front shields (action operator)\r\n"
"\t6: Reduce all shield quadrants except front to 0 (action operator)\r\n"
"\t7: Front shield quadrant is near maximum strength\r\n"
"\t8: Rear shield quadrant is near maximum strength\r\n"
"\t9: Reduce left and right shield quadrants to 0 (action operator)\r\n"
"\t10: Player has fewer than 8 missiles left\r\n"
"\t11: Player has 8 or more missiles left\r\n"
"\t12: Player has fewer than 4 missiles left\r\n"
"\t13: Reduce front shield quadrant to 0 (action operator)\r\n"
"\t100: Player is out of countermeasures\r\n"
"\t2000: Training failed"
},
{ OP_END_CAMPAIGN, "end-campaign\r\n"
"\tEnds the builtin campaign. Should only be used by the main Imperial Alliance campaign\r\n" },
{ OP_SHIP_VAPORIZE, "ship-vaporize\r\n"
"\tSets the ship to vaporize when it is destroyed. Does not actually destroy the ship - use self-destruct for that.\r\n"
"Takes 1 or more arguments...\r\n"
"\tAll:\tList of ships on which to set the vaporize flag" },
{ OP_SHIP_NO_VAPORIZE, "ship-no-vaporize\r\n"
"\tSets the ship to not vaporize when it is destroyed. Does not actually destroy the ship - use self-destruct for that.\r\n"
"Takes 1 or more arguments...\r\n"
"\tAll:\tList of ships on which to unset the vaporize flag" },
{ OP_DONT_COLLIDE_INVISIBLE, "don't-collide-invisible\r\n"
"\tSets the \"dont collide invisible\" flag on a list of ships. Takes 1 or more arguments..."
"\tAll:\tList of ships on which to set the \"dont collide invisible\" flag" },
{ OP_COLLIDE_INVISIBLE, "collide-invisible\r\n"
"\tUnsets the \"dont collide invisible\" flag on a list of ships. Takes 1 or more arguments..."
"\tAll:\tList of ships on which to unset the \"dont collide invisible\" flag" },
{ OP_WARP_BROKEN, "break-hyperdrive\r\n"
"\tBreak the hyperdrive on the specified ship. A broken hyperdrive can be repaired by "
"a repair ship. Takes 1 or more arguments...\r\n"
"\tAll:\tList of ships to break the hyperdrive on" },
{ OP_WARP_NOT_BROKEN, "fix-hyperdrive\r\n"
"\tFixes a broken hyperdrive instantaneously. This option applies to hyperdrives broken with "
"the break-hyperdrive sepxression. Takes 1 or more arguments...\r\n"
"\tAll:\tList of ships whose hyperdrive should be fixed"},
{ OP_WARP_NEVER, "never-hyper\r\n"
"\tNever allows a ship to hyper out. When this sexpression is used, the given ships will "
"never be able to hyper out. The hyperdrive cannot be repaired. Takes 1 or more arguments...\r\n"
"\tAll:\tList of ships whose are not allowed to warp out under any condition"},
{ OP_WARP_ALLOWED, "allow-hyper\r\n"
"\tAllows a ship which was previously not allowed to hyper out to do so. When this sexpression is "
"used, the given ships will be able to hyper out again. Takes 1 or more arguments...\r\n"
"\tAll:\tList of ships whose are allowed to hyper out"},
{ OP_JETTISON_CARGO, "jettison-cargo-delay\r\n"
"\tCauses a cargo carrying ship to jettison its cargo without the undocking procedure. Takes 2 arguments"},
{ OP_BEAM_FIRE, "beam-fire\r\n"
"\tFire a beam weapon from a specified subsystem\r\n"
"\t1:\tShip which will be firing\r\n"
"\t2:\tTurret which will fire the beam (note, this turret must have at least 1 beam weapon on it)\r\n"
"\t3:\tShip which will be targeted\r\n"
"Use add-data to add a specific subsystem to target on the specified target ship"},
{ OP_IS_TAGGED, "is-tagged\r\n"
"\tReturns whether a given ship is tagged or not\r\n"},
{ OP_NUM_KILLS, "num-kills\r\n"
"\tReturns the # of kills a player has. The ship specified in the first field should be the ship the player is in.\r\n"
"\tSo, for single player, this would be alpha 1. For multiplayer, it can be any ship with a player in it. If, at any\r\n"
"\ttime there is no player in a given ship, this sexpression will return 0"},
{ OP_NUM_TYPE_KILLS, "num-type-kills\r\n"
"\tReturns the # of kills a player has on a given ship type (fighter, bomber, cruiser, etc).\r\n"
"The ship specified in the first field should be the ship the player is in.\r\n"
"\tFor multiplayer, it can be any ship with a player in it. If, at any\r\n"
"\ttime there is no player in a given ship, this sexpression will return 0"},
{ OP_NUM_CLASS_KILLS, "num-class-kills\r\n"
"\tReturns the # of kills a player has on a specific ship class (TIE Fighter, X-wing, etc).\r\n"
"The ship specified in the first field should be the ship the player is in.\r\n"
"\tFor multiplayer, it can be any ship with a player in it. If, at any\r\n"
"\ttime there is no player in a given ship, this sexpression will return 0"},
{ OP_BEAM_FREE, "beam-free\r\n"
"\tSets one or more beam weapons to allow firing for a given ship\r\n"
"\t1: Ship to be operated on\r\n"
"\t2, 3, etc : List of turrets to activate\r\n"},
{ OP_BEAM_FREE_ALL, "beam-free-all\r\n"
"\tSets all beam weapons on the specified ship to be active\r\n"},
{ OP_BEAM_LOCK, "beam-lock\r\n"
"\tSets one or more beam weapons to NOT allow firing for a given ship\r\n"
"\t1: Ship to be operated on\r\n"
"\t2, 3, etc : List of turrets to deactivate\r\n"},
{ OP_BEAM_LOCK_ALL, "beam-lock-all\r\n"
"\tSets all beam weapons on the specified ship to be deactivated\r\n"},
{ OP_TURRET_FREE, "turret-free\r\n"
"\tSets one or more turret weapons to allow firing for a given ship\r\n"
"\t1: Ship to be operated on\r\n"
"\t2, 3, etc : List of turrets to activate\r\n"},
{ OP_TURRET_FREE_ALL, "turret-free-all\r\n"
"\tSets all turret weapons on the specified ship to be active\r\n"},
{ OP_TURRET_LOCK, "turret-lock\r\n"
"\tSets one or more turret weapons to NOT allow firing for a given ship\r\n"
"\t1: Ship to be operated on\r\n"
"\t2, 3, etc : List of turrets to deactivate\r\n"},
{ OP_TURRET_LOCK_ALL, "turret-lock-all\r\n"
"\tSets all turret weapons on the specified ship to be deactivated\r\n"},
{ OP_ADD_REMOVE_ESCORT, "add-remove-escort\r\n"
"\tAdds or removes a ship from an escort list.\r\n"
"\t1: Ship to be added or removed\r\n"
"\t2: 0 to remove from the list, any positive value to add to the list\r\n"
"NOTE : it _IS_ safe to add a ship which may already be on the list or remove\r\n"
"a ship which is not on the list\r\n"},
{ OP_AWACS_SET_RADIUS, "awacs-set-radius\r\n"
"\tSets the awacs radius for a given ship subsystem. NOTE : does not work properly in multiplayer\r\n"
"\t1: Ship which has the awacs subsystem\r\n"
"\t2: Awacs subsystem\r\n"
"\t3: New radius\r\n"},
// Goober5000
{ OP_PRIMITIVE_SENSORS_SET_RANGE, "primitive-sensors-set-range\r\n"
"\tSets the range of the primitive sensors on a ship. Ships outside of this range will not appear on "
"sensors. Has no effect on ships that do not have the \"primitive-sensors\" flag2 set. Takes 2 arguments...\r\n"
"\t1: Ship on which to set range\r\n"
"\t2: Range, in meters\r\n" },
{ OP_SEND_MESSAGE_LIST, "send-message-list\r\n"
"\tSends a series of delayed messages. All times are accumulated"
"\t1:\tName of who the message is from.\r\n"
"\t2:\tPriority of message (\"Low\", \"Normal\" or \"High\").\r\n"
"\t3:\tName of message (from message editor).\r\n"
"\t4:\tDelay in ms\r\n"
"Use Add-Data for multiple messages"
"IMPORTANT : each additional message in the list MUST HAVE 4 entries;\r\n"
"any message without the 4 proper fields will be ignored, as will any\r\n"
"successive messages"},
{ OP_CAP_WAYPOINT_SPEED, "cap-waypoint-speed\r\n"
"\tSets the maximum speed of a ship while flying waypoints.\r\n"
"\t1: Ship name\r\n"
"\t2: Maximum speed while flying waypoints\r\n"
"\tNOTE: This will only work if the ship is already in the game\r\n"
"\tNOTE: Set to -1 to reset\r\n"},
{ OP_TURRET_TAGGED_ONLY_ALL, "turret-tagged-only\r\n"
"\tMakes turrets target and hence fire strictly at tagged objects\r\n"
"\t1: Ship name\r\n"
"\tNOTE: Will not stop a turret already firing at an untagged ship\r\n"},
{ OP_TURRET_TAGGED_CLEAR_ALL, "turret-tagged-clear\r\n"
"\tRelaxes restriction on turrets targeting only tagged ships\r\n"
"\t1: Ship name\r\n"},
{ OP_PRIMARIES_DEPLETED, "primaries-depleted\r\n"
"\tReturns true if ship is out of primary weapons\r\n"
"\t1: Ship name\r\n"},
{ OP_SECONDARIES_DEPLETED, "secondaries-depleted\r\n"
"\tReturns true if ship is out of secondary weapons\r\n"
"\t1: Ship name\r\n"},
{ OP_SUBSYS_SET_RANDOM, "subsys-set-random\r\n"
"\tSets ship subsystem strength in a given range\r\n"
"\t1: Ship name\r\n"
"\t2: Low range\r\n"
"\t3: High range\r\n"
"\t4: List of subsys names not to be randomized\r\n"},
{ OP_SUPERNOVA_START, "supernova-start\r\n"
"\t1: Time in seconds until the supernova shockwave hits the player\r\n"},
{ OP_SHIELD_RECHARGE_PCT, "shield-recharge-pct\r\n"
"\tReturns a percentage from 0 to 100\r\n"
"\t1: Ship name\r\n" },
{ OP_ENGINE_RECHARGE_PCT, "engine-recharge-pct\r\n"
"\tReturns a percentage from 0 to 100\r\n"
"\t1: Ship name\r\n" },
{ OP_WEAPON_RECHARGE_PCT, "weapon-recharge-pct\r\n"
"\tReturns a percentage from 0 to 100\r\n"
"\t1: Ship name\r\n" },
{ OP_CARGO_NO_DEPLETE, "cargo-no-deplete\r\n"
"\tCauses the named ship to have unlimited cargo.\r\n"
"\tNote: only applies to BIG or HUGE ships\r\n"
"Takes 1 or more arguments...\r\n"
"\t1:\tName of one of the ships.\r\n"
"\t2:\toptional: 1 disallow depletion, 0 allow depletion." },
{ OP_SHIELD_QUAD_LOW, "shield-quad-low\r\n"
"\tReturns true if the specified ship has a shield quadrant below\r\n"
"\tthe specified threshold percentage\r\n"
"\t1: Ship name\r\n"
"\t2: Percentage\r\n" },
{ OP_PRIMARY_AMMO_PCT, "primary-ammo-pct\r\n"
"\tReturns the percentage of ammo remaining in the specified ballistic primary bank (0 to 100). Non-ballistic primary banks return as 100%.\r\n"
"\t1: Ship name\r\n"
"\t2: Bank to check (0 and 1 are legal banks. 2 will return the cumulative average for all banks" },
{ OP_SECONDARY_AMMO_PCT, "secondary-ammo-pct\r\n"
"\tReturns the percentage of ammo remaining in the specified bank (0 to 100)\r\n"
"\t1: Ship name\r\n"
"\t2: Bank to check (0, 1, 2 are legal banks. 3 will return the cumulative average for all banks" },
{ OP_IS_SECONDARY_SELECTED, "is-secondary-selected\r\n"
"\tReturns true if the specified bank is selected (0 .. num_banks - 1)\r\n"
"\t1: Ship name\r\n"
"\t2: Bank to check (0 .. num_banks - 1)\r\n"},
{ OP_IS_PRIMARY_SELECTED, "is-primary-selected\r\n"
"\tReturns true if the specified bank is selected (0 .. num_banks - 1)\r\n"
"\t1: Ship name\r\n"
"\t2: Bank to check (0 .. num_banks - 1)\r\n"},
{ OP_SPECIAL_WARP_DISTANCE, "special-warp-dist\r\n"
"\tReturns distance to the plane of the knossos device in percent length of ship\r\n"
"\t(ie, 100 means front of ship is 1 ship length from plane of knossos device)\r\n"
"\t1: Ship name\r\n"},
{ OP_SET_SPECIAL_WARPOUT_NAME, "special-warpout-name\r\n"
"\tSets the name of the knossos device to be used for warpout\r\n"
"\t1: Ship name to exit\r\n"
"\t2: Name of knossos device\r\n"},
{ OP_SHIP_VANISH, "ship-vanish\r\n"
"\tMakes the named ship vanish (no log and vanish)\r\n"
"\tSingle Player Only! Warning: This will cause ship exit not to be logged, so 'has-departed', etc. will not work\r\n"
"\t1: List of ship names to vanish\r\n"},
{ OP_IS_SHIP_VISIBLE, "is-ship-visible\r\n"
"\tCheck whether ship is visible on Player's radar\r\n"
"\tSingle Player Only! Returns 0 - not visible, 1 - partially visible, 2 - fully visible.\r\n"
"\t1: Name of ship to check\r\n"},
// Goober5000
{ OP_IS_SHIP_STEALTHY, "is-ship-stealthy\r\n"
"\tCheck whether ship is currently stealthy.\r\n"
"\tTrue if stealth flag set, false otherwise. Takes 1 argument...\r\n"
"\t1: Name of ship to check\r\n"},
// Goober5000
{ OP_IS_FRIENDLY_STEALTH_VISIBLE, "is-friendly-stealth-visible\r\n"
"\tCheck whether ship will be visible to radar as a stealth friendly.\r\n"
"\tTakes 1 argument...\r\n"
"\t1: Name of ship to check\r\n"},
{ OP_TEAM_SCORE, "team-score\r\n"
"\tGet the score of a multi team vs team game.\r\n"
"\t1: Team index (1 for team 1 and 2 for team 2)\r\n"},
// phreak
{ OP_DAMAGED_ESCORT_LIST, "damaged-escort-list\r\n"
"\tSets the most damaged ship in <ship list> to <priority1>, sets the others to <priority2>. Don't use this sexp in the same mission as damaged-escort-list-all, or strange results might occur.\r\n"
"\t1: Priority1\r\n"
"\t2: Priority2\r\n"
"\tRest: <ship_list>\r\n\r\n"
},
// Goober5000
{ OP_DAMAGED_ESCORT_LIST_ALL, "damaged-escort-list-all\r\n"
"\tSets the most damaged ship in the entire existing escort list (even what's not shown onscreen) to <priority1>, the next most damaged to <priority2>, and so on. "
"If there are more ships than priorities, the least most damaged ships are all set to the last priority in the list. Don't use this sexp in the same mission as damaged-escort-list, or strange results might occur.\r\n"
"\tTakes between 1 and MAX_COMPLETE_ESCORT_LIST (currently 20) arguments...\r\n"
"\t1: Priority 1\r\n"
"\tRest: Priorities 2 through 20 (optional)\r\n\r\n"
},
// Goober5000
{ OP_CHANGE_SHIP_MODEL, "change-ship-model\r\n"
"\tCauses the listed ships' models to be changed to the specified ship class's model. Takes 2 or more arguments...\r\n"
"\t1: The name of the new model's ship class\r\n"
"\tRest: The list of ships to change the models of"
},
// Goober5000
{ OP_CHANGE_SHIP_CLASS, "change-ship-class\r\n"
"\tCauses the listed ships' classes to be changed to the specified ship class. Takes 2 or more arguments...\r\n"
"\t1: The name of the new ship class\r\n"
"\tRest: The list of ships to change the classes of"
},
// Goober5000
{ OP_SET_SUPPORT_SHIP, "set-support-ship\r\n"
"\tSets information for all support ships in a mission. Takes 6 arguments...\r\n"
"\t1: Arrival location\r\n"
"\t2: Arrival anchor\r\n"
"\t3: Departure location\r\n"
"\t4: Departure anchor\r\n"
"\t5: Ship class\r\n"
"\t6: Maximum number of support ships in this mission (use a negative number for infinity)\r\n"
"\r\n"
"Note: The support ship will emerge from or depart into hyperspace if the location is set as hyperspace *or* the anchor is set as <no anchor>."
},
// Bobboau
{ OP_DEACTIVATE_GLOW_POINTS, "deactivate-glow-points\r\n"
"\tDeactivates all glow points on a ship. Takes 1 or more arguments...\r\n"
"\tAll: Name of ship on which to deactivate glow points\r\n"
},
// Bobboau
{ OP_ACTIVATE_GLOW_POINTS, "activate-glow-points\r\n"
"\tActivates all glow points on a ship. Takes 1 or more arguments...\r\n"
"\tAll: Name of ship on which to activate glow points\r\n"
},
// Bobboau
{ OP_DEACTIVATE_GLOW_MAPS, "deactivate-glow-maps\r\n"
"\tDeactivates the glow maps for a ship. Takes 1 or more arguments...\r\n"
"\tAll: Name of ship on which to deactivate glow maps\r\n"
},
// Bobboau
{ OP_ACTIVATE_GLOW_MAPS, "activate-glow-maps\r\n"
"\tActivates the glow maps for a ship. Takes 1 or more arguments...\r\n"
"\tAll: Name of ship on which to activate glow maps\r\n"
},
// Bobboau
{ OP_DEACTIVATE_GLOW_POINT_BANK, "deactivate-glow-point-bank\r\n"
"\tDeactivates one or more glow point bank(s) on a ship. Takes 2 or more arguments...\r\n"
"\t1: Name of ship on which to deactivate glow point bank(s)\r\n"
"\tRest: Name of glow point bank to deactivate\r\n"
},
// Bobboau
{ OP_ACTIVATE_GLOW_POINT_BANK, "activate-glow-point-bank\r\n"
"\tActivates one or more glow point bank(s) on a ship. Takes 2 or more arguments...\r\n"
"\t1: Name of ship on which to activate glow point bank(s)\r\n"
"\tRest: Name of glow point bank to activate\r\n"
},
//-Sesquipedalian
{ OP_KAMIKAZE, "kamikaze\r\n"
"\tTells ships to perform a kamikaze on its current target. Takes 2 or more arguments\r\n"
"\t1: Damage dealt when kamikaze is done\r\n"
"\tRest: Names of ships to perform kamikaze\r\n"
},
//-Sesquipedalian
{ OP_NOT_KAMIKAZE, "not-kamikaze\r\n"
"\tTells ships abort a kamikaze.\r\n"
"\tAll: Names of ships to abort kamikaze\r\n"
},
//phreak
{ OP_TURRET_TAGGED_SPECIFIC, "turret-tagged-specific\r\n"
"\tSpecific turrets on a ship only fire at tagged targets, as opposed to all turrets doing this using turret-tagged-only\r\n"
"\tIt is safe to slave turrets already slaved\r\n"
"\tTakes 2 or more arguments...\r\n"
"\t1: Name of ship to slave some turrets to target only tagged ships\r\n"
"\tRest: Turrets to slave\r\n"
},
//phreak
{ OP_TURRET_TAGGED_CLEAR_SPECIFIC, "turret-tagged-clear-specific\r\n"
"\tSpecific turrets on a ship are free to fire on untagged ships, as opposed to all turrets doing this using turret-tagged-clear\r\n"
"\tIt is safe to unslave turrets already free\r\n"
"\tTakes 2 or more arguments...\r\n"
"\t1: Name of ship to unslave some turrets to target any hostile ship\r\n"
"\tRest: Turrets to unslave\r\n"
},
// Goober5000
{ OP_LOCK_ROTATING_SUBSYSTEM, "lock-rotating-subsystem\r\n"
"\tLocks a rotating subsystem so that it cannot rotate unless freed by free-rotating-subsystem."
"Takes 2 or more arguments...\r\n"
"\t1:\tName of the ship housing the subsystem\r\n"
"\tRest:\tName of the rotating subsystem to lock."
},
// Goober5000
{ OP_FREE_ROTATING_SUBSYSTEM, "free-rotating-subsystem\r\n"
"\tFrees a rotating subsystem previously locked by lock-rotating-subsystem."
"Takes 2 or more arguments...\r\n"
"\t1:\tName of the ship housing the subsystem\r\n"
"\tRest:\tName of the rotating subsystem to free."
},
//phreak
{ OP_NUM_SHIPS_IN_BATTLE, "num-ships-in-battle\r\n"
"\tReturns the number of ships in battle or the number of ships in battle for a given team. Takes 1 argument...\r\n"
"\t1:\tTeam to query (optional)"
},
// Goober5000
{ OP_TOGGLE_HUD, "toggle-hud\r\n"
"\tToggles the hud display on or off. Takes 0 arguments."
},
// Goober5000
{ OP_PLAYER_USE_AI, "player-use-ai\r\n"
"\tFlags the AI to run for the player's ship, allowing it to receive orders. Takes 0 arguments."
},
// Goober5000
{ OP_PLAYER_NOT_USE_AI, "player-not-use-ai\r\n"
"\tFlags the AI to not run for the player's ship, restoring AI behavior to player-controlled."
},
{ OP_CLOAK_ON, "ship-cloak-on\r\n"
"\tTurns the cloak on selected ship."
},
{ OP_CLOAK_OFF, "ship-cloak-off\r\n"
"\tTurns the cloak off on selected ship."
},
};
typedef struct op_menu_struct {
char *name;
int id;
} op_menu_struct;
op_menu_struct op_menu[] =
{
{ "Objectives", OP_CATEGORY_OBJECTIVE },
{ "Time", OP_CATEGORY_TIME },
{ "Logical", OP_CATEGORY_LOGICAL },
{ "Arithmetic", OP_CATEGORY_ARITHMETIC },
{ "Status", OP_CATEGORY_STATUS },
{ "Change", OP_CATEGORY_CHANGE },
{ "Conditionals", OP_CATEGORY_CONDITIONAL },
/* { "Debugging", OP_CATEGORY_DEBUG }, discontinued by Goober5000 */
{ "Ai goals", OP_CATEGORY_AI },
{ "Event/Goals", OP_CATEGORY_GOAL_EVENT },
{ "Training", OP_CATEGORY_TRAINING },
};
// Goober5000's subcategorization of the Change menu (and possibly other menus in the future,
// if people so choose - see sexp.h)
op_menu_struct op_submenu[] =
{
{ "Messaging and Mission Goals", CHANGE_SUBCATEGORY_MESSAGING_AND_MISSION_GOALS },
{ "AI and IFF", CHANGE_SUBCATEGORY_AI_AND_IFF },
{ "Subsystems and Cargo", CHANGE_SUBCATEGORY_SUBSYSTEMS_AND_CARGO },
{ "Ship Status", CHANGE_SUBCATEGORY_SHIP_STATUS },
{ "P.O.D.", CHANGE_SUBCATEGORY_POD },
{ "Beams and Turrets", CHANGE_SUBCATEGORY_BEAMS_AND_TURRETS },
{ "Mission and Campaign", CHANGE_SUBCATEGORY_MISSION_AND_CAMPAIGN },
{ "Models and Textures", CHANGE_SUBCATEGORY_MODELS_AND_TEXTURES },
{ "Coordinate Manipulation", CHANGE_SUBCATEGORY_COORDINATE_MANIPULATION },
{ "Music and Sound", CHANGE_SUBCATEGORY_MUSIC_AND_SOUND },
{ "Special", CHANGE_SUBCATEGORY_SPECIAL },
// { "Hud", CHANGE_SUBCATEGORY_HUD },
};
int Num_op_menus = sizeof(op_menu) / sizeof(op_menu_struct);
int Num_submenus = sizeof(op_submenu) / sizeof(op_menu_struct);
// constructor
sexp_tree::sexp_tree()
{
select_sexp_node = -1;
root_item = -1;
m_mode = 0;
m_dragging = FALSE;
m_p_image_list = NULL;
help_box = NULL;
clear_tree();
}
// clears out the tree, so all the nodes are unused.
void sexp_tree::clear_tree(char *op)
{
int i;
total = flag = 0;
for (i=0; i<MAX_SEXP_TREE_SIZE; i++)
nodes[i].type = SEXPT_UNUSED;
if (op) {
DeleteAllItems();
if (strlen(op)) {
set_node(allocate_node(-1), (SEXPT_OPERATOR | SEXPT_VALID), op);
build_tree();
}
}
}
void sexp_tree::reset_handles()
{
int i;
for (i=0; i<MAX_SEXP_TREE_SIZE; i++)
nodes[i].handle = NULL;
}
// initializes and creates a tree from a given sexp startpoint.
void sexp_tree::load_tree(int index, char *deflt)
{
int cur;
clear_tree();
root_item = 0;
if (index < 0) {
cur = allocate_node(-1);
set_node(cur, (SEXPT_OPERATOR | SEXPT_VALID), deflt); // setup a default tree if none
build_tree();
return;
}
if (Sexp_nodes[index].subtype == SEXP_ATOM_NUMBER) { // handle numbers allender likes to use so much..
cur = allocate_node(-1);
if (atoi(Sexp_nodes[index].text))
set_node(cur, (SEXPT_OPERATOR | SEXPT_VALID), "true");
else
set_node(cur, (SEXPT_OPERATOR | SEXPT_VALID), "false");
build_tree();
return;
}
// assumption: first token is an operator. I require this because it would cause problems
// with child/parent relations otherwise, and it should be this way anyway, since the
// return type of the whole sexp is boolean, and only operators can satisfy this.
Assert(Sexp_nodes[index].subtype == SEXP_ATOM_OPERATOR);
load_branch(index, -1);
build_tree();
}
void get_combined_variable_name(char *combined_name, const char *sexp_var_name)
{
int sexp_var_index = get_index_sexp_variable_name(sexp_var_name);
Assert(sexp_var_index > -1);
sprintf(combined_name, "%s(%s)", Sexp_variables[sexp_var_index].variable_name, Sexp_variables[sexp_var_index].text);
}
// creates a tree from a given Sexp_nodes[] point under a given parent. Recursive.
void sexp_tree::load_branch(int index, int parent)
{
int cur = -1;
char combined_var_name[2*TOKEN_LENGTH + 2];
while (index != -1) {
Assert(Sexp_nodes[index].type != SEXP_NOT_USED);
if (Sexp_nodes[index].subtype == SEXP_ATOM_LIST) {
load_branch(Sexp_nodes[index].first, parent); // do the sublist and continue
} else if (Sexp_nodes[index].subtype == SEXP_ATOM_OPERATOR) {
cur = allocate_node(parent);
if ((index == select_sexp_node) && !flag) { // translate sexp node to our node
select_sexp_node = cur;
flag = 1;
}
set_node(cur, (SEXPT_OPERATOR | SEXPT_VALID), Sexp_nodes[index].text);
load_branch(Sexp_nodes[index].rest, cur); // operator is new parent now
return; // 'rest' was just used, so nothing left to use.
} else if (Sexp_nodes[index].subtype == SEXP_ATOM_NUMBER) {
cur = allocate_node(parent);
if (Sexp_nodes[index].type & SEXP_FLAG_VARIABLE) {
get_combined_variable_name(combined_var_name, Sexp_nodes[index].text);
set_node(cur, (SEXPT_VARIABLE | SEXPT_NUMBER | SEXPT_VALID), combined_var_name);
} else {
set_node(cur, (SEXPT_NUMBER | SEXPT_VALID), Sexp_nodes[index].text);
}
} else if (Sexp_nodes[index].subtype == SEXP_ATOM_STRING) {
cur = allocate_node(parent);
if (Sexp_nodes[index].type & SEXP_FLAG_VARIABLE) {
get_combined_variable_name(combined_var_name, Sexp_nodes[index].text);
set_node(cur, (SEXPT_VARIABLE | SEXPT_STRING | SEXPT_VALID), combined_var_name);
} else {
set_node(cur, (SEXPT_STRING | SEXPT_VALID), Sexp_nodes[index].text);
}
} else
Assert(0); // unknown and/or invalid sexp type
if ((index == select_sexp_node) && !flag) { // translate sexp node to our node
select_sexp_node = cur;
flag = 1;
}
index = Sexp_nodes[index].rest;
if (index == -1)
return;
}
}
int sexp_tree::query_false(int node)
{
if (node < 0)
node = root_item;
Assert(node >= 0);
Assert(nodes[node].type == (SEXPT_OPERATOR | SEXPT_VALID));
Assert(nodes[node].next == -1); // must make this assumption or else it will confuse code!
if (find_operator(nodes[node].text) == OP_FALSE){
return TRUE;
}
return FALSE;
}
// builds an sexp of the tree and returns the index of it. This allocates sexp nodes.
int sexp_tree::save_tree(int node)
{
if (node < 0)
node = root_item;
Assert(node >= 0);
Assert(nodes[node].type == (SEXPT_OPERATOR | SEXPT_VALID));
Assert(nodes[node].next == -1); // must make this assumption or else it will confuse code!
return save_branch(node);
}
// get variable name from sexp_tree node .text
void var_name_from_sexp_tree_text(char *var_name, const char *text)
{
int var_name_length = strcspn(text, "(");
Assert(var_name_length < TOKEN_LENGTH - 1);
strncpy(var_name, text, var_name_length);
var_name[var_name_length] = '\0';
}
#define NO_PREVIOUS_NODE -9
// called recursively to save a tree branch and everything under it
int sexp_tree::save_branch(int cur, int at_root)
{
int start, node = -1, last = NO_PREVIOUS_NODE;
char var_name_text[TOKEN_LENGTH];
start = -1;
while (cur != -1) {
if (nodes[cur].type & SEXPT_OPERATOR) {
node = alloc_sexp(nodes[cur].text, SEXP_ATOM, SEXP_ATOM_OPERATOR, -1, save_branch(nodes[cur].child));
if ((nodes[cur].parent >= 0) && !at_root) {
node = alloc_sexp("", SEXP_LIST, SEXP_ATOM_LIST, node, -1);
}
} else if (nodes[cur].type & SEXPT_NUMBER) {
// allocate number, maybe variable
if (nodes[cur].type & SEXPT_VARIABLE) {
var_name_from_sexp_tree_text(var_name_text, nodes[cur].text);
node = alloc_sexp(var_name_text, (SEXP_ATOM | SEXP_FLAG_VARIABLE), SEXP_ATOM_NUMBER, -1, -1);
} else {
node = alloc_sexp(nodes[cur].text, SEXP_ATOM, SEXP_ATOM_NUMBER, -1, -1);
}
} else if (nodes[cur].type & SEXPT_STRING) {
// allocate string, maybe variable
if (nodes[cur].type & SEXPT_VARIABLE) {
var_name_from_sexp_tree_text(var_name_text, nodes[cur].text);
node = alloc_sexp(var_name_text, (SEXP_ATOM | SEXP_FLAG_VARIABLE), SEXP_ATOM_STRING, -1, -1);
} else {
node = alloc_sexp(nodes[cur].text, SEXP_ATOM, SEXP_ATOM_STRING, -1, -1);
}
} else if (nodes[cur].type & SEXPT_STRING) {
Assert( !(nodes[cur].type & SEXPT_VARIABLE) );
Int3();
} else {
Assert(0); // unknown and/or invalid type
}
if (last == NO_PREVIOUS_NODE){
start = node;
} else if (last >= 0){
Sexp_nodes[last].rest = node;
}
last = node;
Assert(last != NO_PREVIOUS_NODE); // should be impossible
cur = nodes[cur].next;
if (at_root){
return start;
}
}
return start;
}
// allocate a node. Remains used until freed.
int sexp_tree::allocate_node()
{
int i;
for (i=0; i<MAX_SEXP_TREE_SIZE; i++)
if (nodes[i].type == SEXPT_UNUSED) {
nodes[i].type = SEXPT_UNINIT;
nodes[i].parent = -1;
nodes[i].child = -1;
nodes[i].next = -1;
total++;
return i;
}
Error(LOCATION, "Out of sexp tree nodes!");
return -1;
}
// allocate a child node under 'parent'. Appends to end of list.
int sexp_tree::allocate_node(int parent, int after)
{
int i, index = allocate_node();
if (parent != -1) {
i = nodes[parent].child;
if (i == -1) {
nodes[parent].child = index;
} else {
while ((i != after) && (nodes[i].next != -1))
i = nodes[i].next;
nodes[index].next = nodes[i].next;
nodes[i].next = index;
}
}
nodes[index].parent = parent;
return index;
}
// free a node and all its children. Also clears pointers to it, if any.
// node = node chain to free
// cascade = 0: free just this node and children under it. (default)
// !0: free this node and all siblings after it.
//
void sexp_tree::free_node(int node, int cascade)
{
int i;
// clear the pointer to node
i = nodes[node].parent;
Assert(i != -1);
if (nodes[i].child == node)
nodes[i].child = nodes[node].next;
else {
i = nodes[i].child;
while (nodes[i].next != -1) {
if (nodes[i].next == node) {
nodes[i].next = nodes[node].next;
break;
}
i = nodes[i].next;
}
}
if (!cascade)
nodes[node].next = -1;
// now free up the node and its children
free_node2(node);
}
// more simple node freer, which works recursively. It frees the given node and all siblings
// that come after it, as well as all children of these. Doesn't clear any links to any of
// these freed nodes, so make sure all links are broken first. (i.e. use free_node() if you can)
//
void sexp_tree::free_node2(int node)
{
Assert(node != -1);
Assert(nodes[node].type != SEXPT_UNUSED);
Assert(total > 0);
*modified = 1;
nodes[node].type = SEXPT_UNUSED;
total--;
if (nodes[node].child != -1)
free_node2(nodes[node].child);
if (nodes[node].next != -1)
free_node2(nodes[node].next);
}
// initialize the data for a node. Should be called right after a new node is allocated.
void sexp_tree::set_node(int node, int type, char *text)
{
Assert(type != SEXPT_UNUSED);
Assert(nodes[node].type != SEXPT_UNUSED);
nodes[node].type = type;
size_t max_length;
if (type & SEXPT_VARIABLE) {
max_length = 2 * TOKEN_LENGTH + 2;
} else {
max_length = TOKEN_LENGTH;
}
Assert(strlen(text) < max_length);
strcpy(nodes[node].text, text);
}
void sexp_tree::post_load()
{
if (!flag)
select_sexp_node = -1;
}
// build or rebuild a CTreeCtrl object with the current tree data
void sexp_tree::build_tree()
{
if (!flag)
select_sexp_node = -1;
DeleteAllItems();
add_sub_tree(0, TVI_ROOT);
}
// Create the CTreeCtrl tree from the tree data. The tree data should already be setup by
// this point.
void sexp_tree::add_sub_tree(int node, HTREEITEM root)
{
// char str[80];
int node2;
Assert(node >= 0 && node < MAX_SEXP_TREE_SIZE);
node2 = nodes[node].child;
// check for single argument operator case (prints as one line)
/* if (node2 != -1 && nodes[node2].child == -1 && nodes[node2].next == -1) {
sprintf(str, "%s %s", nodes[node].text, nodes[node2].text);
nodes[node].handle = insert(str, root);
nodes[node].flags = OPERAND | EDITABLE;
nodes[node2].flags = COMBINED;
return;
}*/
// bitmap to draw in tree
int bitmap;
if (nodes[node].type & SEXPT_OPERATOR) {
nodes[node].flags = OPERAND;
bitmap = BITMAP_OPERATOR;
} else {
if (nodes[node].type & SEXPT_VARIABLE) {
nodes[node].flags = NOT_EDITABLE;
bitmap = BITMAP_VARIABLE;
} else {
nodes[node].flags = EDITABLE;
bitmap = BITMAP_DATA;
}
}
root = nodes[node].handle = insert(nodes[node].text, bitmap, bitmap, root);
node = node2;
while (node != -1) {
Assert(node >= 0 && node < MAX_SEXP_TREE_SIZE);
Assert(nodes[node].type & SEXPT_VALID);
if (nodes[node].type & SEXPT_OPERATOR) {
add_sub_tree(node, root);
} else {
Assert(nodes[node].child == -1);
if (nodes[node].type & SEXPT_VARIABLE) {
nodes[node].handle = insert(nodes[node].text, BITMAP_VARIABLE, BITMAP_VARIABLE, root);
nodes[node].flags = NOT_EDITABLE;
} else {
nodes[node].handle = insert(nodes[node].text, BITMAP_DATA, BITMAP_DATA, root);
nodes[node].flags = EDITABLE;
}
}
node = nodes[node].next;
}
}
void sexp_tree::setup_selected(HTREEITEM h)
{
int i;
item_index = -1;
item_handle = h;
if (!h)
item_handle = GetSelectedItem();
for (i=0; i<MAX_SEXP_TREE_SIZE; i++)
if (nodes[i].handle == item_handle) {
item_index = i;
break;
}
}
int sexp_tree::get_ambiguous_type(int parent)
{
int first_arg_index = get_modify_variable_first_arg_index();
int sexp_var_index = get_tree_name_to_sexp_variable_index(nodes[first_arg_index].text);
Assert(sexp_var_index != -1);
if (Sexp_variables[sexp_var_index].type & SEXP_VARIABLE_NUMBER) {
return OPF_NUMBER;
} else {
return OPF_AMBIGUOUS;
}
}
int sexp_tree::get_modify_variable_first_arg_index()
{
int index;
Assert( item_index >= 0);
// get parent and check "modify-variable"
index = nodes[item_index].parent;
Assert( index != -1 );
Assert( !(stricmp(nodes[index].text, "modify-variable")) );
// get first child and verify type variable
index = nodes[index].child;
Assert( index != -1 );
Assert( nodes[index].type & SEXPT_VARIABLE);
return index;
}
// Goober5000
int get_sexp_id(char *sexp_name)
{
for (int i = 0; i < Num_operators; i++)
{
if (!stricmp(sexp_name, Operators[i].text))
return Operators[i].value;
}
return -1;
}
// Goober5000
int category_of_subcategory(int subcategory_id)
{
return (subcategory_id & OP_CATEGORY_MASK);
}
// Goober5000
int get_category_id(char *category_name)
{
for (int i = 0; i < Num_op_menus; i++)
{
if (!stricmp(category_name, op_menu[i].name))
{
return op_menu[i].id;
}
}
return -1;
}
// Goober5000
int has_submenu(char *category_name)
{
int category_id = get_category_id(category_name);
if (category_id != -1)
{
for (int i = 0; i < Num_submenus; i++)
{
if (category_of_subcategory(op_submenu[i].id) == category_id)
return 1;
}
}
return 0;
}
// handler for right mouse button clicks.
void sexp_tree::right_clicked(int mode)
{
char buf[256];
int i, j, z, count, op, add_type, replace_type, type, subcategory_id;
sexp_list_item *list;
UINT _flags;
HTREEITEM h;
POINT click_point, mouse;
CMenu menu, *mptr, *popup_menu, *add_data_menu = NULL, *replace_data_menu = NULL;
CMenu *add_op_menu, add_op_submenu[MAX_OP_MENUS];
CMenu *replace_op_menu, replace_op_submenu[MAX_OP_MENUS];
CMenu *insert_op_menu, insert_op_submenu[MAX_OP_MENUS];
CMenu *replace_variable_menu = NULL;
CMenu add_op_subcategory_menu[MAX_SUBMENUS];
CMenu replace_op_subcategory_menu[MAX_SUBMENUS];
CMenu insert_op_subcategory_menu[MAX_SUBMENUS];
m_mode = mode;
add_instance = replace_instance = -1;
Assert(Num_operators <= MAX_OPERATORS);
Assert(Num_op_menus < MAX_OP_MENUS);
Assert(Num_submenus < MAX_SUBMENUS);
GetCursorPos(&mouse);
click_point = mouse;
ScreenToClient(&click_point);
h = HitTest(CPoint(click_point), &_flags); // find out what they clicked on
if (h && menu.LoadMenu(IDR_MENU_EDIT_SEXP_TREE)) {
update_help(h);
popup_menu = menu.GetSubMenu(0);
ASSERT(popup_menu != NULL);
SelectDropTarget(h);
add_op_menu = replace_op_menu = insert_op_menu = NULL;
// get pointers to several key popup menus we'll need to modify
i = popup_menu->GetMenuItemCount();
while (i--) {
if ( (mptr = popup_menu->GetSubMenu(i)) > 0 ) {
popup_menu->GetMenuString(i, buf, sizeof(buf), MF_BYPOSITION);
if (!stricmp(buf, "add operator")) {
add_op_menu = mptr;
} else if (!stricmp(buf, "replace operator")) {
replace_op_menu = mptr;
} else if (!stricmp(buf, "add data")) {
add_data_menu = mptr;
} else if (!stricmp(buf, "replace data")) {
replace_data_menu = mptr;
} else if (!stricmp(buf, "insert operator")) {
insert_op_menu = mptr;
} else if (!stricmp(buf, "replace variable")) {
replace_variable_menu = mptr;
}
}
}
// add popup menus for all the operator categories
for (i=0; i<Num_op_menus; i++)
{
add_op_submenu[i].CreatePopupMenu();
replace_op_submenu[i].CreatePopupMenu();
insert_op_submenu[i].CreatePopupMenu();
add_op_menu->AppendMenu(MF_POPUP, (UINT) add_op_submenu[i].m_hMenu, op_menu[i].name);
replace_op_menu->AppendMenu(MF_POPUP, (UINT) replace_op_submenu[i].m_hMenu, op_menu[i].name);
insert_op_menu->AppendMenu(MF_POPUP, (UINT) insert_op_submenu[i].m_hMenu, op_menu[i].name);
}
// get rid of the placeholders we needed to ensure popup menus stayed popup menus,
// i.e. MSDEV will convert empty popup menus into normal menu items.
add_op_menu->DeleteMenu(ID_PLACEHOLDER, MF_BYCOMMAND);
replace_op_menu->DeleteMenu(ID_PLACEHOLDER, MF_BYCOMMAND);
insert_op_menu->DeleteMenu(ID_PLACEHOLDER, MF_BYCOMMAND);
replace_variable_menu->DeleteMenu(ID_PLACEHOLDER, MF_BYCOMMAND);
// get item_index
item_index = -1;
for (i=0; i<MAX_SEXP_TREE_SIZE; i++) {
if (nodes[i].handle == h) {
item_index = i;
break;
}
}
// Do SEXP_VARIABLE stuff here.
if (m_mode != MODE_EVENTS) {
// only allow variables in event mode
menu.EnableMenuItem(ID_SEXP_TREE_ADD_VARIABLE, MF_GRAYED);
menu.EnableMenuItem(ID_SEXP_TREE_MODIFY_VARIABLE, MF_GRAYED);
} else {
menu.EnableMenuItem(ID_SEXP_TREE_ADD_VARIABLE, MF_ENABLED);
menu.EnableMenuItem(ID_SEXP_TREE_MODIFY_VARIABLE, MF_ENABLED);
// check not root (-1)
if (item_index >= 0) {
// get type of sexp_tree item clicked on
int type = get_type(h);
int parent = nodes[item_index].parent;
if (parent >= 0) {
op = identify_operator(nodes[parent].text);
Assert(op >= 0);
int first_arg = nodes[parent].child;
// get arg count of item to replace
Replace_count = 0;
int temp = first_arg;
while (temp != item_index) {
Replace_count++;
temp = nodes[temp].next;
// DB - added 3/4/99
if(temp == -1){
break;
}
}
int op_type = query_operator_argument_type(op, Replace_count); // check argument type at this position
// special case dont allow replace data for variable names
if (op_type != OPF_AMBIGUOUS) {
if ( (type & SEXPT_STRING) || (type & SEXPT_NUMBER) ) {
int max_sexp_vars = MAX_SEXP_VARIABLES;
// prevent collisions in id numbers: ID_VARIABLE_MENU + 512 = ID_ADD_MENU
Assert(max_sexp_vars < 512);
for (int idx=0; idx<max_sexp_vars; idx++) {
if (Sexp_variables[idx].type & SEXP_VARIABLE_SET) {
UINT flag = MF_STRING | MF_GRAYED;
// maybe gray flag MF_GRAYED
// get type -- gray "string" or number accordingly
if ( type & SEXPT_STRING ) {
if ( Sexp_variables[idx].type & SEXP_VARIABLE_STRING ) {
flag &= ~MF_GRAYED;
}
} else if ( type & SEXPT_NUMBER ) {
if ( Sexp_variables[idx].type & SEXP_VARIABLE_NUMBER ) {
flag &= ~MF_GRAYED;
}
}
// if modify-variable and changing variable, enable all variables
if (op_type == OPF_VARIABLE_NAME) {
Modify_variable = 1;
flag &= ~MF_GRAYED;
} else {
Modify_variable = 0;
}
char buf[128];
// append list of variable names and values
// set id as ID_VARIABLE_MENU + idx
sprintf(buf, "%s (%s)", Sexp_variables[idx].variable_name, Sexp_variables[idx].text);
replace_variable_menu->AppendMenu(flag, (ID_VARIABLE_MENU + idx), buf);
}
}
}
}
}
}
// cant modify if no variables
if (sexp_variable_count() == 0) {
menu.EnableMenuItem(ID_SEXP_TREE_MODIFY_VARIABLE, MF_GRAYED);
}
}
// add all the submenu items first
for (i=0; i<Num_submenus; i++)
{
add_op_subcategory_menu[i].CreatePopupMenu();
replace_op_subcategory_menu[i].CreatePopupMenu();
insert_op_subcategory_menu[i].CreatePopupMenu();
for (j=0; j<Num_op_menus; j++)
{
if (op_menu[j].id == category_of_subcategory(op_submenu[i].id))
{
add_op_submenu[j].AppendMenu(MF_POPUP, (UINT) add_op_subcategory_menu[i].m_hMenu, op_submenu[i].name);
replace_op_submenu[j].AppendMenu(MF_POPUP, (UINT) replace_op_subcategory_menu[i].m_hMenu, op_submenu[i].name);
insert_op_submenu[j].AppendMenu(MF_POPUP, (UINT) insert_op_subcategory_menu[i].m_hMenu, op_submenu[i].name);
break; // only 1 category valid
}
}
}
// add operator menu items to the various CATEGORY submenus they belong in
for (i=0; i<Num_operators; i++)
{
// add only if it is not in a subcategory
subcategory_id = get_subcategory(Operators[i].value);
if (subcategory_id == -1)
{
// put it in the appropriate menu
for (j=0; j<Num_op_menus; j++)
{
if (op_menu[j].id == (Operators[i].value & OP_CATEGORY_MASK))
{
// Commented out by Goober5000 to allow these sexps to be selectable
/*#ifdef NDEBUG
switch (Operators[i].value) {
case OP_WAS_PROMOTION_GRANTED:
case OP_WAS_MEDAL_GRANTED:
case OP_GRANT_PROMOTION:
case OP_GRANT_MEDAL:
case OP_TECH_ADD_SHIP:
case OP_TECH_ADD_WEAPON:
case OP_TECH_ADD_INTEL:
case OP_TECH_RESET_TO_DEFAULT:
j = Num_op_menus; // don't allow these operators in final release
}
#endif*/
if (j < Num_op_menus) {
add_op_submenu[j].AppendMenu(MF_STRING | MF_GRAYED, Operators[i].value, Operators[i].text);
replace_op_submenu[j].AppendMenu(MF_STRING | MF_GRAYED, Operators[i].value | OP_REPLACE_FLAG, Operators[i].text);
insert_op_submenu[j].AppendMenu(MF_STRING, Operators[i].value | OP_INSERT_FLAG, Operators[i].text);
}
break; // only 1 category valid
}
}
}
// if it is in a subcategory, handle it
else
{
// put it in the appropriate submenu
for (j=0; j<Num_submenus; j++)
{
if (op_submenu[j].id == subcategory_id)
{
add_op_subcategory_menu[j].AppendMenu(MF_STRING | MF_GRAYED, Operators[i].value, Operators[i].text);
replace_op_subcategory_menu[j].AppendMenu(MF_STRING | MF_GRAYED, Operators[i].value | OP_REPLACE_FLAG, Operators[i].text);
insert_op_subcategory_menu[j].AppendMenu(MF_STRING, Operators[i].value | OP_INSERT_FLAG, Operators[i].text);
break; // only 1 subcategory valid
}
}
}
}
// find local index (i) of current item (from its handle)
SelectItem(item_handle = h);
for (i=0; i<MAX_SEXP_TREE_SIZE; i++) {
if (nodes[i].handle == h) {
break;
}
}
// special case: item is a ROOT node, and a label that can be edited (not an item in the sexp tree)
if ((item_index == -1) && (m_mode & ST_LABELED_ROOT)) {
if (m_mode & ST_ROOT_EDITABLE) {
menu.EnableMenuItem(ID_EDIT_TEXT, MF_ENABLED);
} else {
menu.EnableMenuItem(ID_EDIT_TEXT, MF_GRAYED);
}
// disable copy, insert op
menu.EnableMenuItem(ID_EDIT_COPY, MF_GRAYED);
for (j=0; j<Num_operators; j++) {
menu.EnableMenuItem(Operators[j].value | OP_INSERT_FLAG, MF_GRAYED);
}
gray_menu_tree(popup_menu);
popup_menu->TrackPopupMenu(TPM_LEFTALIGN | TPM_RIGHTBUTTON, mouse.x, mouse.y, this);
return;
}
Assert(item_index != -1); // handle not found, which should be impossible.
if (!(nodes[item_index].flags & EDITABLE)) {
menu.EnableMenuItem(ID_EDIT_TEXT, MF_GRAYED);
}
if (nodes[item_index].parent == -1) { // root node
menu.EnableMenuItem(ID_DELETE, MF_GRAYED); // can't delete the root item.
}
/* if ((nodes[item_index].flags & OPERAND) && (nodes[item_index].flags & EDITABLE)) // expandable?
menu.EnableMenuItem(ID_SPLIT_LINE, MF_ENABLED);
z = nodes[item_index].child;
if (z != -1 && nodes[z].next == -1 && nodes[z].child == -1)
menu.EnableMenuItem(ID_SPLIT_LINE, MF_ENABLED);
z = nodes[nodes[item_index].parent].child;
if (z != -1 && nodes[z].next == -1 && nodes[z].child == -1)
menu.EnableMenuItem(ID_SPLIT_LINE, MF_ENABLED);*/
// change enabled status of 'add' type menu options.
add_type = 0;
if (nodes[item_index].flags & OPERAND) {
add_type = OPR_STRING;
int child = nodes[item_index].child;
Add_count = count_args(child);
op = identify_operator(nodes[item_index].text);
Assert(op >= 0);
// get listing of valid argument values and add to menus
type = query_operator_argument_type(op, Add_count);
list = get_listing_opf(type, item_index, Add_count);
if (list) {
sexp_list_item *ptr;
int data_idx = 0;
ptr = list;
while (ptr) {
if (ptr->op >= 0) {
// enable operators with correct return type
menu.EnableMenuItem(Operators[ptr->op].value, MF_ENABLED);
} else {
// add data
if ( (data_idx + 3) % 30) {
add_data_menu->AppendMenu(MF_STRING | MF_ENABLED, ID_ADD_MENU + data_idx, ptr->text);
} else {
add_data_menu->AppendMenu(MF_MENUBARBREAK | MF_STRING | MF_ENABLED, ID_ADD_MENU + data_idx, ptr->text);
}
}
data_idx++;
ptr = ptr->next;
}
}
// special handling for the non-string formats
if (type == OPF_NONE) { // an argument can't be added
add_type = 0;
} else if (type == OPF_NULL) { // arguments with no return values
add_type = OPR_NULL;
} else if (type == OPF_NUMBER) { // takes numbers
add_type = OPR_NUMBER;
menu.EnableMenuItem(ID_ADD_NUMBER, MF_ENABLED);
} else if (type == OPF_POSITIVE) { // takes non-negative numbers
add_type = OPR_POSITIVE;
menu.EnableMenuItem(ID_ADD_NUMBER, MF_ENABLED);
} else if (type == OPF_BOOL) { // takes true/false bool values
add_type = OPR_BOOL;
} else if (type == OPF_AI_GOAL) {
add_type = OPR_AI_GOAL;
}
// add_type unchanged from above
if (add_type == OPR_STRING) {
menu.EnableMenuItem(ID_ADD_STRING, MF_ENABLED);
}
list->destroy();
}
// disable operators that do not have arguments available
for (j=0; j<Num_operators; j++) {
if (!query_default_argument_available(j)) {
menu.EnableMenuItem(Operators[j].value, MF_GRAYED);
}
}
// change enabled status of 'replace' type menu options.
replace_type = 0;
int parent = nodes[item_index].parent;
if (parent >= 0) {
replace_type = OPR_STRING;
op = identify_operator(nodes[parent].text);
Assert(op >= 0);
int first_arg = nodes[parent].child;
count = count_args(nodes[parent].child);
// already at minimum number of arguments?
if (count <= Operators[op].min) {
menu.EnableMenuItem(ID_DELETE, MF_GRAYED);
}
// get arg count of item to replace
Replace_count = 0;
int temp = first_arg;
while (temp != item_index) {
Replace_count++;
temp = nodes[temp].next;
// DB - added 3/4/99
if(temp == -1){
break;
}
}
// maybe gray delete
for (i=Replace_count+1; i<count; i++) {
if (query_operator_argument_type(op, i-1) != query_operator_argument_type(op, i)) {
menu.EnableMenuItem(ID_DELETE, MF_GRAYED);
break;
}
}
type = query_operator_argument_type(op, Replace_count); // check argument type at this position
// special case reset type for ambiguous
if (type == OPF_AMBIGUOUS) {
type = get_ambiguous_type(parent);
}
list = get_listing_opf(type, parent, Replace_count);
// special case dont allow replace data for variable names
if ( (type != OPF_VARIABLE_NAME) && list) {
sexp_list_item *ptr;
int data_idx = 0;
ptr = list;
while (ptr) {
if (ptr->op >= 0) {
menu.EnableMenuItem(Operators[ptr->op].value | OP_REPLACE_FLAG, MF_ENABLED);
} else {
if ( (data_idx + 3) % 30)
replace_data_menu->AppendMenu(MF_STRING | MF_ENABLED, ID_REPLACE_MENU + data_idx, ptr->text);
else
replace_data_menu->AppendMenu(MF_MENUBARBREAK | MF_STRING | MF_ENABLED, ID_REPLACE_MENU + data_idx, ptr->text);
}
data_idx++;
ptr = ptr->next;
}
}
if (type == OPF_NONE) { // takes no arguments
replace_type = 0;
} else if (type == OPF_NUMBER) { // takes numbers
replace_type = OPR_NUMBER;
menu.EnableMenuItem(ID_REPLACE_NUMBER, MF_ENABLED);
} else if (type == OPF_POSITIVE) { // takes non-negative numbers
replace_type = OPR_POSITIVE;
menu.EnableMenuItem(ID_REPLACE_NUMBER, MF_ENABLED);
} else if (type == OPF_BOOL) { // takes true/false bool values
replace_type = OPR_BOOL;
} else if (type == OPF_NULL) { // takes operator that doesn't return a value
replace_type = OPR_NULL;
} else if (type == OPF_AI_GOAL) {
replace_type = OPR_AI_GOAL;
}
// default to string
if (replace_type == OPR_STRING) {
menu.EnableMenuItem(ID_REPLACE_STRING, MF_ENABLED);
}
// modify string or number if (modify_variable)
if ( !stricmp(Operators[op].text, "modify-variable") ) {
int modify_type = get_modify_variable_type();
if (modify_type == OPF_NUMBER) {
menu.EnableMenuItem(ID_REPLACE_NUMBER, MF_ENABLED);
menu.EnableMenuItem(ID_REPLACE_STRING, MF_GRAYED);
}
// no change for string type
}
list->destroy();
} else { // top node, so should be a Boolean type.
if (m_mode == MODE_EVENTS) { // return type should be null
replace_type = OPR_NULL;
for (j=0; j<Num_operators; j++)
if (query_operator_return_type(j) == OPR_NULL)
menu.EnableMenuItem(Operators[j].value | OP_REPLACE_FLAG, MF_ENABLED);
} else {
replace_type = OPR_BOOL;
for (j=0; j<Num_operators; j++)
if (query_operator_return_type(j) == OPR_BOOL)
menu.EnableMenuItem(Operators[j].value | OP_REPLACE_FLAG, MF_ENABLED);
}
}
for (j=0; j<Num_operators; j++)
if (!query_default_argument_available(j))
menu.EnableMenuItem(Operators[j].value | OP_REPLACE_FLAG, MF_GRAYED);
// change enabled status of 'insert' type menu options.
z = nodes[item_index].parent;
Assert(z >= -1);
if (z != -1) {
op = identify_operator(nodes[z].text);
Assert(op != -1);
j = nodes[z].child;
count = 0;
while (j != item_index) {
count++;
j = nodes[j].next;
}
type = query_operator_argument_type(op, count); // check argument type at this position
} else {
if (m_mode == MODE_EVENTS)
type = OPF_NULL;
else
type = OPF_BOOL;
}
for (j=0; j<Num_operators; j++) {
z = query_operator_return_type(j);
if (!sexp_query_type_match(type, z) || (Operators[j].min < 1))
menu.EnableMenuItem(Operators[j].value | OP_INSERT_FLAG, MF_GRAYED);
z = query_operator_argument_type(j, 0);
if ((type == OPF_NUMBER) && (z == OPF_POSITIVE))
z = OPF_NUMBER;
// Goober5000's number hack
if ((type == OPF_POSITIVE) && (z == OPF_NUMBER))
z = OPF_POSITIVE;
if (z != type)
menu.EnableMenuItem(Operators[j].value | OP_INSERT_FLAG, MF_GRAYED);
}
for (j=0; j<Num_operators; j++)
if (!query_default_argument_available(j))
menu.EnableMenuItem(Operators[j].value | OP_INSERT_FLAG, MF_GRAYED);
// disable non campaign operators if in campaign mode
for (j=0; j<Num_operators; j++) {
z = 0;
if (m_mode == MODE_CAMPAIGN) {
if (Operators[j].value & OP_NONCAMPAIGN_FLAG)
z = 1;
} else {
if (Operators[j].value & OP_CAMPAIGN_ONLY_FLAG)
z = 1;
}
if (z) {
menu.EnableMenuItem(Operators[j].value, MF_GRAYED);
menu.EnableMenuItem(Operators[j].value | OP_REPLACE_FLAG, MF_GRAYED);
menu.EnableMenuItem(Operators[j].value | OP_INSERT_FLAG, MF_GRAYED);
}
}
if ((Sexp_clipboard > -1) && (Sexp_nodes[Sexp_clipboard].type != SEXP_NOT_USED)) {
Assert(Sexp_nodes[Sexp_clipboard].subtype != SEXP_ATOM_LIST);
if (Sexp_nodes[Sexp_clipboard].subtype == SEXP_ATOM_OPERATOR) {
j = find_operator(CTEXT(Sexp_clipboard));
Assert(j);
z = query_operator_return_type(j);
if ((z == OPR_POSITIVE) && (replace_type == OPR_NUMBER))
z = OPR_NUMBER;
// Goober5000's number hack
if ((z == OPR_NUMBER) && (replace_type == OPR_POSITIVE))
z = OPR_POSITIVE;
if (replace_type == z)
menu.EnableMenuItem(ID_EDIT_PASTE, MF_ENABLED);
z = query_operator_return_type(j);
if ((z == OPR_POSITIVE) && (add_type == OPR_NUMBER))
z = OPR_NUMBER;
if (add_type == z)
menu.EnableMenuItem(ID_EDIT_PASTE_SPECIAL, MF_ENABLED);
} else if (Sexp_nodes[Sexp_clipboard].subtype == SEXP_ATOM_NUMBER) {
if ((replace_type == OPR_POSITIVE) && (atoi(CTEXT(Sexp_clipboard)) > -1))
menu.EnableMenuItem(ID_EDIT_PASTE, MF_ENABLED);
else if (replace_type == OPR_NUMBER)
menu.EnableMenuItem(ID_EDIT_PASTE, MF_ENABLED);
if ((add_type == OPR_POSITIVE) && (atoi(CTEXT(Sexp_clipboard)) > -1))
menu.EnableMenuItem(ID_EDIT_PASTE_SPECIAL, MF_ENABLED);
else if (add_type == OPR_NUMBER)
menu.EnableMenuItem(ID_EDIT_PASTE_SPECIAL, MF_ENABLED);
} else if (Sexp_nodes[Sexp_clipboard].subtype == SEXP_ATOM_STRING) {
if (replace_type == OPR_STRING)
menu.EnableMenuItem(ID_EDIT_PASTE, MF_ENABLED);
if (add_type == OPR_STRING)
menu.EnableMenuItem(ID_EDIT_PASTE_SPECIAL, MF_ENABLED);
} else
Int3(); // unknown and/or invalid sexp type
}
if (!(menu.GetMenuState(ID_DELETE, MF_BYCOMMAND) & MF_GRAYED))
menu.EnableMenuItem(ID_EDIT_CUT, MF_ENABLED);
gray_menu_tree(popup_menu);
popup_menu->TrackPopupMenu(TPM_LEFTALIGN | TPM_RIGHTBUTTON, mouse.x, mouse.y, this);
}
}
// counts the number of arguments an operator has. Call this with the node of the first
// argument of the operator
int sexp_tree::count_args(int node)
{
int count = 0;
while (node != -1) {
count++;
node = nodes[node].next;
}
return count;
}
// identify what type of argument this is. You call it with the node of the first argument
// of an operator. It will search through enough of the arguments to determine what type of
// data they are.
int sexp_tree::identify_arg_type(int node)
{
int type = -1;
while (node != -1) {
Assert(nodes[node].type & SEXPT_VALID);
switch (SEXPT_TYPE(nodes[node].type)) {
case SEXPT_OPERATOR:
type = find_operator(nodes[node].text);
Assert(type);
return query_operator_return_type(type);
case SEXPT_NUMBER:
return OPR_NUMBER;
case SEXPT_STRING: // either a ship or a wing
type = SEXP_ATOM_STRING;
break; // don't return, because maybe we can narrow selection down more.
}
node = nodes[node].next;
}
return type;
}
// determine if an item should be editable. This doesn't actually edit the label.
int sexp_tree::edit_label(HTREEITEM h)
{
int i;
for (i=0; i<MAX_SEXP_TREE_SIZE; i++) {
if (nodes[i].handle == h) {
break;
}
}
// Check if tree root
if (i == MAX_SEXP_TREE_SIZE) {
if (m_mode & ST_ROOT_EDITABLE) {
return 1;
}
return 0;
}
// Operators are editable
if (nodes[i].type & SEXPT_OPERATOR) {
return 1;
}
// Variables must be edited through dialog box
if (nodes[i].type & SEXPT_VARIABLE) {
return 0;
}
// Don't edit if not flaged as editable
if (!(nodes[i].flags & EDITABLE)) {
return 0;
}
// Otherwise, allow editing
return 1;
/*
if (nodes[i].flags & OPERAND) {
data = nodes[i].child;
SetItemText(h, nodes[i].text);
nodes[i].flags = OPERAND;
item_handle = nodes[data].handle = insert(nodes[data].text, nodes[data].type, nodes[data].flags, h);
nodes[data].flags = EDITABLE;
Expand(h, TVE_EXPAND);
SelectItem(item_handle);
return 2;
}
*/
}
int sexp_tree::end_label_edit(HTREEITEM h, char *str)
{
int len, node, r = 1;
*modified = 1;
if (!str)
return 0;
for (node=0; node<MAX_SEXP_TREE_SIZE; node++)
if (nodes[node].handle == h)
break;
if (node == MAX_SEXP_TREE_SIZE) {
if (m_mode == MODE_EVENTS) {
item_index = GetItemData(h);
Assert(Event_editor_dlg);
node = Event_editor_dlg->handler(ROOT_RENAMED, item_index, str);
return 1;
} else
Int3(); // root labels shouldn't have been editable!
}
Assert(node < MAX_SEXP_TREE_SIZE);
if (nodes[node].type & SEXPT_OPERATOR) {
str = match_closest_operator(str, node);
SetItemText(h, str);
item_index = node;
add_or_replace_operator(identify_operator(str), 1);
r = 0;
}
// Error checking would not hurt here
len = strlen(str);
if (len >= TOKEN_LENGTH)
len = TOKEN_LENGTH - 1;
strncpy(nodes[node].text, str, len);
nodes[node].text[len] = 0;
/* node = nodes[node].parent;
if (node != -1) {
child = nodes[node].child;
if (child != -1 && nodes[child].next == -1 && nodes[child].child == -1) {
merge_operator(child);
return 0;
}
}*/
return r;
}
// Check if 'op' is a valid operator match for operator format (OPF) 'type'. Returns true if it
// is, false if not.
//
int sexp_tree::check_operator_validity(int op, int type)
{
int rtype;
rtype = query_operator_return_type(op);
switch (type) {
case OPF_NUMBER:
return ( (rtype == OPR_NUMBER) || (rtype == OPR_POSITIVE) );
case OPF_POSITIVE:
// Goober5000's number hack
return ( (rtype == OPR_POSITIVE) || (rtype == OPR_NUMBER) );
case OPF_BOOL:
return (rtype == OPR_BOOL);
case OPF_NULL:
return (rtype == OPR_NULL);
case OPF_AI_GOAL:
return (rtype == OPR_AI_GOAL);
}
return 0;
}
// Look for the valid operator that is the closest match for 'str' and return the operator
// number of it. What operators are valid is determined by 'node', and an operator is valid
// if it is allowed to fit at position 'node'
//
char *sexp_tree::match_closest_operator(char *str, int node)
{
int z, n, i, op, arg_num, type;
char *sub_best = NULL, *best = NULL;
z = nodes[node].parent;
if (z < 0) {
return str;
}
op = identify_operator(nodes[z].text);
if (op < 0)
return str;
// determine which argument we are of the parent
arg_num = 0;
n = nodes[z].child;
while (n != node) {
Assert(n >= 0);
arg_num++;
n = nodes[n].next;
}
type = query_operator_argument_type(op, arg_num); // check argument type at this position
for (i=0; i<Num_operators; i++) {
if (check_operator_validity(i, type)) {
if ( (stricmp(str, Operators[i].text) <= 0) && (!best || (stricmp(str, best) < 0)) )
best = Operators[i].text;
if ( !sub_best || (stricmp(Operators[i].text, sub_best) > 0) )
sub_best = Operators[i].text;
}
}
if (!best)
best = sub_best; // no best found, use our plan #2 best found.
Assert(best); // we better have some valid operator at this point.
return best;
/* char buf[256];
int child;
if (nodes[node].flags == EDITABLE) // data
node = nodes[node].parent;
if (node != -1) {
child = nodes[node].child;
if (child != -1 && nodes[child].next == -1 && nodes[child].child == -1) {
sprintf(buf, "%s %s", nodes[node].text, nodes[child].text);
SetItemText(nodes[node].handle, buf);
nodes[node].flags = OPERAND | EDITABLE;
nodes[child].flags = COMBINED;
DeleteItem(nodes[child].handle);
nodes[child].handle = NULL;
return;
}
}*/
}
// this really only handles messages generated by the right click popup menu
BOOL sexp_tree::OnCommand(WPARAM wParam, LPARAM lParam)
{
int i, z, id, node, op, type;
sexp_list_item *list, *ptr;
HTREEITEM h;
if ((item_index >= 0) && (item_index < total))
item_handle = nodes[item_index].handle;
id = LOWORD(wParam);
// Add variable
if (id == ID_SEXP_TREE_ADD_VARIABLE) {
CAddVariableDlg dlg;
dlg.DoModal();
if ( dlg.m_create ) {
// set type
int type;
if ( dlg.m_type_number ) {
type = SEXP_VARIABLE_NUMBER;
} else {
type = SEXP_VARIABLE_STRING;
}
if ( dlg.m_type_campaign_persistent ) {
type |= SEXP_VARIABLE_CAMPAIGN_PERSISTENT;
} else if ( dlg.m_type_player_persistent ) {
type |= SEXP_VARIABLE_PLAYER_PERSISTENT;
}
// add variable
sexp_add_variable(dlg.m_default_value, dlg.m_variable_name, type);
// sort variable
sexp_variable_sort();
}
return 1;
}
// Modify variable
if (id == ID_SEXP_TREE_MODIFY_VARIABLE) {
CModifyVariableDlg dlg;
// get sexp_variable index for item index
dlg.m_start_index = get_item_index_to_var_index();
// get pointer to tree
dlg.m_p_sexp_tree = this;
dlg.DoModal();
Assert( !(dlg.m_deleted && dlg.m_do_modify) );
if (dlg.m_deleted) {
// find index in sexp_variable list
int sexp_var_index = get_index_sexp_variable_name(dlg.m_cur_variable_name);
Assert(sexp_var_index != -1);
// delete from list
sexp_variable_delete(sexp_var_index);
// sort list
sexp_variable_sort();
// delete from sexp_tree, replacing with "number" or "string" as needed
// further error checking from add_data()
delete_sexp_tree_variable(dlg.m_cur_variable_name);
return 1;
}
if (dlg.m_do_modify) {
// check sexp_tree -- warn on type
// find index and change either (1) name, (2) type, (3) value
int sexp_var_index = get_index_sexp_variable_name(dlg.m_old_var_name);
Assert(sexp_var_index != -1);
// save old name, since name may be modified
char old_name[TOKEN_LENGTH];
strcpy(old_name, Sexp_variables[sexp_var_index].variable_name);
// set type
int type;
if (dlg.m_type_number) {
type = SEXP_VARIABLE_NUMBER;
} else {
type = SEXP_VARIABLE_STRING;
}
if ( dlg.m_type_campaign_persistent ) {
type |= SEXP_VARIABLE_CAMPAIGN_PERSISTENT;
} else if ( dlg.m_type_player_persistent ) {
type |= SEXP_VARIABLE_PLAYER_PERSISTENT;
}
// update sexp_variable
sexp_fred_modify_variable(dlg.m_default_value, dlg.m_cur_variable_name, sexp_var_index, type);
// modify sexp_tree
modify_sexp_tree_variable(old_name, sexp_var_index);
// Don't sort until after modify, since modify uses index
if (dlg.m_modified_name) {
sexp_variable_sort();
}
return 1;
}
// no change
return 1;
}
// check if REPLACE_VARIABLE_MENU
if ( (id >= ID_VARIABLE_MENU) && (id < ID_VARIABLE_MENU + 511)) {
Assert(item_index >= 0);
// get index into list of type valid variables
int var_idx = id - ID_VARIABLE_MENU;
Assert( (var_idx >= 0) && (var_idx < MAX_SEXP_VARIABLES) );
int type = get_type(item_handle);
Assert( (type & SEXPT_NUMBER) || (type & SEXPT_STRING) );
// dont do type check for modify-variable
if (Modify_variable) {
if (Sexp_variables[var_idx].type & SEXP_VARIABLE_NUMBER) {
type = SEXPT_NUMBER;
} else if (Sexp_variables[var_idx].type & SEXP_VARIABLE_STRING) {
type = SEXPT_STRING;
} else {
Int3(); // unknown type
}
} else {
// verify type in tree is same as type in Sexp_variables array
if (type & SEXPT_NUMBER) {
Assert(Sexp_variables[var_idx].type & SEXP_VARIABLE_NUMBER);
}
if (type & SEXPT_STRING) {
Assert( (Sexp_variables[var_idx].type & SEXP_VARIABLE_STRING) );
}
}
// Replace data
replace_variable_data(var_idx, (type | SEXPT_VARIABLE));
return 1;
}
if ((id >= ID_ADD_MENU) && (id < ID_ADD_MENU + 511)) {
Assert(item_index >= 0);
op = identify_operator(nodes[item_index].text);
Assert(op >= 0);
type = query_operator_argument_type(op, Add_count);
list = get_listing_opf(type, item_index, Add_count);
Assert(list);
id -= ID_ADD_MENU;
ptr = list;
while (id) {
id--;
ptr = ptr->next;
Assert(ptr);
}
Assert((SEXPT_TYPE(ptr->type) != SEXPT_OPERATOR) && (ptr->op < 0));
expand_operator(item_index);
add_data(ptr->text, ptr->type);
list->destroy();
return 1;
}
if ((id >= ID_REPLACE_MENU) && (id < ID_REPLACE_MENU + 511)) {
Assert(item_index >= 0);
Assert(nodes[item_index].parent >= 0);
op = identify_operator(nodes[nodes[item_index].parent].text);
Assert(op >= 0);
type = query_operator_argument_type(op, Replace_count); // check argument type at this position
list = get_listing_opf(type, nodes[item_index].parent, Replace_count);
Assert(list);
id -= ID_REPLACE_MENU;
ptr = list;
while (id) {
id--;
ptr = ptr->next;
Assert(ptr);
}
Assert((SEXPT_TYPE(ptr->type) != SEXPT_OPERATOR) && (ptr->op < 0));
expand_operator(item_index);
replace_data(ptr->text, ptr->type);
list->destroy();
return 1;
}
for (op=0; op<Num_operators; op++) {
if (id == Operators[op].value) {
add_or_replace_operator(op);
return 1;
}
if (id == (Operators[op].value | OP_REPLACE_FLAG)) {
add_or_replace_operator(op, 1);
return 1;
}
if (id == (Operators[op].value | OP_INSERT_FLAG)) {
int flags;
z = nodes[item_index].parent;
flags = nodes[item_index].flags;
node = allocate_node(z, item_index);
set_node(node, (SEXPT_OPERATOR | SEXPT_VALID), Operators[op].text);
nodes[node].flags = flags;
if (z >= 0)
h = nodes[z].handle;
else {
h = GetParentItem(nodes[item_index].handle);
if (m_mode == MODE_GOALS) {
Assert(Goal_editor_dlg);
Goal_editor_dlg->insert_handler(item_index, node);
SetItemData(h, node);
} else if (m_mode == MODE_EVENTS) {
Assert(Event_editor_dlg);
Event_editor_dlg->insert_handler(item_index, node);
SetItemData(h, node);
} else if (m_mode == MODE_CAMPAIGN) {
Campaign_tree_formp->insert_handler(item_index, node);
SetItemData(h, node);
} else {
h = TVI_ROOT;
root_item = node;
}
}
item_handle = nodes[node].handle = insert(Operators[op].text, BITMAP_OPERATOR, BITMAP_OPERATOR, h, nodes[item_index].handle);
move_branch(item_index, node);
item_index = node;
for (i=1; i<Operators[op].min; i++)
add_default_operator(op, i);
Expand(item_handle, TVE_EXPAND);
*modified = 1;
return 1;
}
}
switch (id) {
case ID_EDIT_COPY:
// If a clipboard already exist, unmark it as persistent and free old clipboard
if (Sexp_clipboard != -1) {
sexp_unmark_persistent(Sexp_clipboard);
free_sexp2(Sexp_clipboard);
}
// Allocate new clipboard and mark persistent
Sexp_clipboard = save_branch(item_index, 1);
sexp_mark_persistent(Sexp_clipboard);
return 1;
case ID_EDIT_PASTE:
// the following assumptions are made..
Assert((Sexp_clipboard > -1) && (Sexp_nodes[Sexp_clipboard].type != SEXP_NOT_USED));
Assert(Sexp_nodes[Sexp_clipboard].subtype != SEXP_ATOM_LIST);
if (Sexp_nodes[Sexp_clipboard].subtype == SEXP_ATOM_OPERATOR) {
expand_operator(item_index);
replace_operator(CTEXT(Sexp_clipboard));
if (Sexp_nodes[Sexp_clipboard].rest != -1) {
load_branch(Sexp_nodes[Sexp_clipboard].rest, item_index);
i = nodes[item_index].child;
while (i != -1) {
add_sub_tree(i, nodes[item_index].handle);
i = nodes[i].next;
}
}
} else if (Sexp_nodes[Sexp_clipboard].subtype == SEXP_ATOM_NUMBER) {
Assert(Sexp_nodes[Sexp_clipboard].rest == -1);
expand_operator(item_index);
replace_data(CTEXT(Sexp_clipboard), (SEXPT_NUMBER | SEXPT_VALID));
} else if (Sexp_nodes[Sexp_clipboard].subtype == SEXP_ATOM_STRING) {
Assert(Sexp_nodes[Sexp_clipboard].rest == -1);
expand_operator(item_index);
replace_data(CTEXT(Sexp_clipboard), (SEXPT_STRING | SEXPT_VALID));
} else
Assert(0); // unknown and/or invalid sexp type
return 1;
case ID_EDIT_PASTE_SPECIAL: // add paste, instead of replace.
// the following assumptions are made..
Assert((Sexp_clipboard > -1) && (Sexp_nodes[Sexp_clipboard].type != SEXP_NOT_USED));
Assert(Sexp_nodes[Sexp_clipboard].subtype != SEXP_ATOM_LIST);
if (Sexp_nodes[Sexp_clipboard].subtype == SEXP_ATOM_OPERATOR) {
expand_operator(item_index);
add_operator(CTEXT(Sexp_clipboard));
if (Sexp_nodes[Sexp_clipboard].rest != -1) {
load_branch(Sexp_nodes[Sexp_clipboard].rest, item_index);
i = nodes[item_index].child;
while (i != -1) {
add_sub_tree(i, nodes[item_index].handle);
i = nodes[i].next;
}
}
} else if (Sexp_nodes[Sexp_clipboard].subtype == SEXP_ATOM_NUMBER) {
Assert(Sexp_nodes[Sexp_clipboard].rest == -1);
expand_operator(item_index);
add_data(CTEXT(Sexp_clipboard), (SEXPT_NUMBER | SEXPT_VALID));
} else if (Sexp_nodes[Sexp_clipboard].subtype == SEXP_ATOM_STRING) {
Assert(Sexp_nodes[Sexp_clipboard].rest == -1);
expand_operator(item_index);
add_data(CTEXT(Sexp_clipboard), (SEXPT_STRING | SEXPT_VALID));
} else
Assert(0); // unknown and/or invalid sexp type
return 1;
/* case ID_SPLIT_LINE:
if ((nodes[item_index].flags & OPERAND) && (nodes[item_index].flags & EDITABLE)) // expandable?
expand_operator(item_index);
else
merge_operator(item_index);
return 1;*/
case ID_EXPAND_ALL:
expand_branch(item_handle);
return 1;
case ID_EDIT_TEXT:
if (edit_label(item_handle)) {
*modified = 1;
EditLabel(item_handle);
}
return 1;
case ID_ADD_STRING: {
int node;
node = add_data("string", (SEXPT_STRING | SEXPT_VALID));
EditLabel(nodes[node].handle);
return 1;
}
case ID_ADD_NUMBER: {
int node;
node = add_data("number", (SEXPT_NUMBER | SEXPT_VALID));
EditLabel(nodes[node].handle);
return 1;
}
case ID_EDIT_CUT:
if (Sexp_clipboard != -1) {
sexp_unmark_persistent(Sexp_clipboard);
free_sexp2(Sexp_clipboard);
}
Sexp_clipboard = save_branch(item_index, 1);
sexp_mark_persistent(Sexp_clipboard);
// fall through to ID_DELETE case.
case ID_DELETE: {
int parent, node;
HTREEITEM h;
if ((m_mode & ST_ROOT_DELETABLE) && (item_index == -1)) {
item_index = GetItemData(item_handle);
if (m_mode == MODE_GOALS) {
Assert(Goal_editor_dlg);
node = Goal_editor_dlg->handler(ROOT_DELETED, item_index);
} else if (m_mode == MODE_EVENTS) {
Assert(Event_editor_dlg);
node = Event_editor_dlg->handler(ROOT_DELETED, item_index);
} else {
Assert(m_mode == MODE_CAMPAIGN);
node = Campaign_tree_formp->handler(ROOT_DELETED, item_index);
}
Assert(node >= 0);
free_node2(node);
DeleteItem(item_handle);
*modified = 1;
return 1;
}
Assert(item_index >= 0);
h = GetParentItem(item_handle);
parent = nodes[item_index].parent;
if ((parent == -1) && (m_mode == MODE_EVENTS))
Int3(); // no longer used, temporary to check if called still.
Assert(parent != -1 && nodes[parent].handle == h);
free_node(item_index);
DeleteItem(item_handle);
node = nodes[parent].child;
/* if (node != -1 && nodes[node].next == -1 && nodes[node].child == -1) {
sprintf(buf, "%s %s", nodes[parent].text, nodes[node].text);
SetItem(h, TVIF_TEXT, buf, 0, 0, 0, 0, 0);
nodes[parent].flags = OPERAND | EDITABLE;
nodes[node].flags = COMBINED;
DeleteItem(nodes[node].handle);
}*/
*modified = 1;
return 1;
}
}
return CTreeCtrl::OnCommand(wParam, lParam);
}
// adds to or replaces (based on passed in flag) the current operator
void sexp_tree::add_or_replace_operator(int op, int replace_flag)
{
int i, op_index, op2;
op_index = item_index;
if (replace_flag) {
if (nodes[item_index].flags & OPERAND) { // are both operators?
op2 = identify_operator(nodes[item_index].text);
Assert(op2 >= 0);
i = count_args(nodes[item_index].child);
if ((i >= Operators[op].min) && (i <= Operators[op].max)) { // are old num args valid?
while (i--)
if (query_operator_argument_type(op2, i) != query_operator_argument_type(op, i)) // does each arg match expected type?
break;
if (i < 0) { // everything is ok, so we can keep old arguments with new operator
set_node(item_index, (SEXPT_OPERATOR | SEXPT_VALID), Operators[op].text);
SetItemText(nodes[item_index].handle, Operators[op].text);
nodes[item_index].flags = OPERAND;
return;
}
}
}
replace_operator(Operators[op].text);
} else
add_operator(Operators[op].text);
// fill in all the required (minimum) arguments with default values
for (i=0; i<Operators[op].min; i++)
add_default_operator(op, i);
Expand(item_handle, TVE_EXPAND);
}
// initialize node, type operator
//
void sexp_list_item::set_op(int op_num)
{
int i;
if (op_num >= FIRST_OP) { // do we have an op value instead of an op number (index)?
for (i=0; i<Num_operators; i++)
if (op_num == Operators[i].value)
op_num = i; // convert op value to op number
}
op = op_num;
text = Operators[op].text;
type = (SEXPT_OPERATOR | SEXPT_VALID);
}
// initialize node, type data
// Defaults: t = SEXPT_STRING
//
void sexp_list_item::set_data(char *str, int t)
{
op = -1;
text = str;
type = t;
}
// initialize node, type data, allocating memory for the text
// Defaults: t = SEXPT_STRING
//
void sexp_list_item::set_data_dup(char *str, int t)
{
op = -1;
text = strdup(str);
flags |= SEXP_ITEM_F_DUP;
type = t;
}
// add a node to end of list
//
void sexp_list_item::add_op(int op_num)
{
sexp_list_item *item, *ptr;
item = new sexp_list_item;
ptr = this;
while (ptr->next)
ptr = ptr->next;
ptr->next = item;
item->set_op(op_num);
}
// add a node to end of list
// Defaults: t = SEXPT_STRING
//
void sexp_list_item::add_data(char *str, int t)
{
sexp_list_item *item, *ptr;
item = new sexp_list_item;
ptr = this;
while (ptr->next)
ptr = ptr->next;
ptr->next = item;
item->set_data(str, t);
}
// add a node to end of list, allocating memory for the text
// Defaults: t = SEXPT_STRING
//
void sexp_list_item::add_data_dup(char *str, int t)
{
sexp_list_item *item, *ptr;
item = new sexp_list_item;
ptr = this;
while (ptr->next)
ptr = ptr->next;
ptr->next = item;
item->set_data(strdup(str), t);
item->flags |= SEXP_ITEM_F_DUP;
}
// add an sexp list to end of another list (join lists)
//
void sexp_list_item::add_list(sexp_list_item *list)
{
sexp_list_item *ptr;
ptr = this;
while (ptr->next)
ptr = ptr->next;
ptr->next = list;
}
// free all nodes of list
//
void sexp_list_item::destroy()
{
sexp_list_item *ptr, *ptr2;
ptr = this;
while (ptr) {
ptr2 = ptr->next;
if (ptr->flags & SEXP_ITEM_F_DUP)
free(ptr->text);
delete ptr;
ptr = ptr2;
}
}
int sexp_tree::add_default_operator(int op, int argnum)
{
char buf[256];
int index;
sexp_list_item item;
HTREEITEM h;
h = item_handle;
index = item_index;
item.text = buf;
if (get_default_value(&item, op, argnum))
return -1;
if (item.type & SEXPT_OPERATOR) {
Assert((item.op >= 0) && (item.op < Num_operators));
add_or_replace_operator(item.op);
item_index = index;
item_handle = h;
} else {
// special case for modify-variable (data added 1st arg is variable)
if ( !stricmp(Operators[op].text, "modify-variable") ) {
if (argnum == 0) {
int sexp_var_index = get_index_sexp_variable_name(item.text);
Assert(sexp_var_index != -1);
int type = SEXPT_VALID | SEXPT_VARIABLE;
if (Sexp_variables[sexp_var_index].type & SEXP_VARIABLE_STRING) {
type |= SEXPT_STRING;
} else if (Sexp_variables[sexp_var_index].type & SEXP_VARIABLE_NUMBER) {
type |= SEXPT_NUMBER;
} else {
Int3();
}
char node_text[2*TOKEN_LENGTH + 2];
sprintf(node_text, "%s(%s)", item.text, Sexp_variables[sexp_var_index].text);
add_variable_data(node_text, type);
} else {
// the the variable name
char buf2[256];
Assert(argnum == 1);
sexp_list_item temp_item;
temp_item.text = buf2;
get_default_value(&temp_item, op, 0);
int sexp_var_index = get_index_sexp_variable_name(temp_item.text);
Assert(sexp_var_index != -1);
// from name get type
int temp_type = Sexp_variables[sexp_var_index].type;
int type = 0;
if (temp_type & SEXP_VARIABLE_NUMBER) {
type = SEXPT_VALID | SEXPT_NUMBER;
} else if (temp_type & SEXP_VARIABLE_STRING) {
type = SEXPT_VALID | SEXPT_STRING;
} else {
Int3();
}
add_data(item.text, type);
}
} else {
add_data(item.text, item.type);
}
}
return 0;
}
int sexp_tree::get_default_value(sexp_list_item *item, int op, int i)
{
char *str = NULL;
int type, index;
sexp_list_item *list;
HTREEITEM h;
h = item_handle;
index = item_index;
type = query_operator_argument_type(op, i);
switch (type) {
case OPF_NULL:
item->set_op(OP_NOP);
return 0;
case OPF_BOOL:
item->set_op(OP_TRUE);
return 0;
case OPF_NUMBER:
case OPF_POSITIVE:
case OPF_AMBIGUOUS:
// if the top level operators is an AI goal, and we are adding the last number required,
// assume that this number is a priority and make it 89 instead of 1.
if ((query_operator_return_type(op) == OPR_AI_GOAL) && (i == (Operators[op].min - 1)))
{
item->set_data("89", (SEXPT_NUMBER | SEXPT_VALID));
}
else if (((Operators[op].value == OP_HAS_DOCKED_DELAY) || (Operators[op].value == OP_HAS_UNDOCKED_DELAY)) && (i == 2))
{
item->set_data("1", (SEXPT_NUMBER | SEXPT_VALID));
}
else if ( (Operators[op].value == OP_SHIP_TYPE_DESTROYED) || (Operators[op].value == OP_GOOD_SECONDARY_TIME) )
{
item->set_data("100", (SEXPT_NUMBER | SEXPT_VALID));
}
else if ( (Operators[op].value == OP_SET_SUPPORT_SHIP) )
{
item->set_data("-1", (SEXPT_NUMBER | SEXPT_VALID));
}
else if ( (Operators[op].value == OP_EXPLOSION_EFFECT) )
{
int temp;
char str[TOKEN_LENGTH];
switch (i)
{
case 3:
temp = 10;
break;
case 4:
temp = 10;
break;
case 5:
temp = 100;
break;
case 6:
temp = 10;
break;
case 7:
temp = 100;
break;
case 10:
temp = SND_SHIP_EXPLODE_1;
break;
case 11:
temp = (int)EMP_DEFAULT_INTENSITY;
break;
case 12:
temp = (int)EMP_DEFAULT_TIME;
break;
default:
temp = 0;
break;
}
// Goober5000 - set_data_dup is required if we're passing a variable
sprintf(str, "%d", temp);
item->set_data_dup(str, (SEXPT_NUMBER | SEXPT_VALID));
}
else if ( (Operators[op].value == OP_WARP_EFFECT) )
{
int temp;
char str[TOKEN_LENGTH];
switch (i)
{
case 6:
temp = 100;
break;
case 7:
temp = 10;
break;
case 8:
temp = SND_CAPITAL_WARP_IN;
break;
case 9:
temp = SND_CAPITAL_WARP_OUT;
break;
default:
temp = 0;
break;
}
// Goober5000 - set_data_dup is required if we're passing a variable
sprintf(str, "%d", temp);
item->set_data_dup(str, (SEXPT_NUMBER | SEXPT_VALID));
}
else
{
item->set_data("0", (SEXPT_NUMBER | SEXPT_VALID));
}
return 0;
}
list = get_listing_opf(type, index, i);
if (list) {
char *ptr;
ptr = item->text;
*item = *list;
item->text = ptr;
strcpy(item->text, list->text);
list->destroy();
return 0;
}
// catch anything that doesn't have a default value. Just describe what should be here instead
switch (type) {
case OPF_SHIP:
case OPF_SHIP_NOT_PLAYER:
case OPF_SHIP_WING:
case OPF_SHIP_POINT:
case OPF_SHIP_WING_POINT:
str = "<name of ship here>";
break;
case OPF_WING:
str = "<name of wing here>";
break;
case OPF_DOCKER_POINT:
str = "<docker point>";
break;
case OPF_DOCKEE_POINT:
str = "<dockee point>";
break;
case OPF_SUBSYSTEM:
case OPF_AWACS_SUBSYSTEM:
case OPF_ROTATING_SUBSYSTEM:
str = "<name of subsystem>";
break;
case OPF_POINT:
str = "<waypoint>";
break;
case OPF_MESSAGE:
str = "<Message>";
break;
case OPF_WHO_FROM:
//str = "<any allied>";
str = "<any wingman>";
break;
case OPF_WAYPOINT_PATH:
str = "<waypoint path>";
break;
case OPF_MISSION_NAME:
str = "<mission name>";
break;
case OPF_GOAL_NAME:
str = "<goal name>";
break;
case OPF_SHIP_TYPE:
str = "<ship type here>";
break;
case OPF_EVENT_NAME:
str = "<event name>";
break;
case OPF_HUGE_WEAPON:
str = "<huge weapon type>";
break;
case OPF_JUMP_NODE_NAME:
str = "<hyper buoy name>";
break;
default:
str = "<new default required!>";
break;
}
item->set_data(str, (SEXPT_STRING | SEXPT_VALID));
return 0;
}
int sexp_tree::query_default_argument_available(int op)
{
int i;
Assert(op >= 0);
for (i=0; i<Operators[op].min; i++)
if (!query_default_argument_available(op, i))
return 0;
return 1;
}
int sexp_tree::query_default_argument_available(int op, int i)
{
int j, type;
object *ptr;
type = query_operator_argument_type(op, i);
switch (type) {
case OPF_NULL:
case OPF_BOOL:
case OPF_NUMBER:
case OPF_POSITIVE:
case OPF_IFF:
case OPF_TEAM:
case OPF_AI_CLASS:
case OPF_WHO_FROM:
case OPF_PRIORITY:
case OPF_SHIP_TYPE:
case OPF_SUBSYSTEM:
case OPF_AWACS_SUBSYSTEM:
case OPF_ROTATING_SUBSYSTEM:
case OPF_DOCKER_POINT:
case OPF_DOCKEE_POINT:
case OPF_AI_GOAL:
case OPF_KEYPRESS:
case OPF_AI_ORDER:
case OPF_SKILL_LEVEL:
case OPF_MEDAL_NAME:
case OPF_WEAPON_NAME:
case OPF_INTEL_NAME:
case OPF_SHIP_CLASS_NAME:
case OPF_HUD_GAUGE_NAME:
case OPF_HUGE_WEAPON:
case OPF_JUMP_NODE_NAME:
case OPF_AMBIGUOUS:
case OPF_CARGO:
case OPF_ARRIVAL_LOCATION:
case OPF_DEPARTURE_LOCATION:
case OPF_ARRIVAL_ANCHOR_ALL:
case OPF_SUPPORT_SHIP_CLASS:
case OPF_SHIP_WITH_BAY:
case OPF_SOUNDTRACK_NAME:
case OPF_STRING:
return 1;
case OPF_SHIP:
case OPF_SHIP_NOT_PLAYER:
case OPF_SHIP_WING:
case OPF_SHIP_POINT:
case OPF_SHIP_WING_POINT:
ptr = GET_FIRST(&obj_used_list);
while (ptr != END_OF_LIST(&obj_used_list)) {
if (ptr->type == OBJ_SHIP)
return 1;
ptr = GET_NEXT(ptr);
}
return 0;
case OPF_WING:
for (j=0; j<MAX_WINGS; j++)
if (Wings[j].wave_count)
return 1;
return 0;
case OPF_POINT:
case OPF_WAYPOINT_PATH:
if (Num_waypoint_lists)
return 1;
return 0;
case OPF_MISSION_NAME:
if (m_mode != MODE_CAMPAIGN) {
if (!(*Mission_filename))
return 0;
return 1;
}
if (Campaign.num_missions > 0)
return 1;
return 0;
case OPF_GOAL_NAME: {
int value;
value = Operators[op].value;
if (m_mode == MODE_CAMPAIGN)
return 1;
// need to be sure that previous-goal functions are available. (i.e. we are providing a default argument for them)
else if ((value == OP_PREVIOUS_GOAL_TRUE) || (value == OP_PREVIOUS_GOAL_FALSE) || (value == OP_PREVIOUS_GOAL_INCOMPLETE) || Num_goals)
return 1;
return 0;
}
case OPF_EVENT_NAME: {
int value;
value = Operators[op].value;
if (m_mode == MODE_CAMPAIGN)
return 1;
// need to be sure that previous-event functions are available. (i.e. we are providing a default argument for them)
else if ((value == OP_PREVIOUS_EVENT_TRUE) || (value == OP_PREVIOUS_EVENT_FALSE) || (value == OP_PREVIOUS_EVENT_INCOMPLETE) || Num_mission_events)
return 1;
return 0;
}
case OPF_MESSAGE:
if (m_mode == MODE_EVENTS) {
Assert(Event_editor_dlg);
if (Event_editor_dlg->current_message_name(0))
return 1;
} else {
if (Num_messages > Num_builtin_messages)
return 1;
}
return 0;
case OPF_VARIABLE_NAME:
if (sexp_variable_count() > 0) {
return 1;
} else {
return 0;
}
default:
Int3();
}
return 0;
}
// expand a combined line (one with an operator and it's one argument on the same line) into
// 2 lines.
void sexp_tree::expand_operator(int node)
{
int data;
HTREEITEM h;
if (nodes[node].flags & COMBINED) {
node = nodes[node].parent;
Assert((nodes[node].flags & OPERAND) && (nodes[node].flags & EDITABLE));
}
if ((nodes[node].flags & OPERAND) && (nodes[node].flags & EDITABLE)) { // expandable?
Assert(nodes[node].type & SEXPT_OPERATOR);
h = nodes[node].handle;
data = nodes[node].child;
Assert(data != -1 && nodes[data].next == -1 && nodes[data].child == -1);
SetItem(h, TVIF_TEXT, nodes[node].text, 0, 0, 0, 0, 0);
nodes[node].flags = OPERAND;
nodes[data].handle = insert(nodes[data].text, BITMAP_DATA, BITMAP_DATA, h);
nodes[data].flags = EDITABLE;
Expand(h, TVE_EXPAND);
}
}
// expand a CTreeCtrl branch and all of its children
void sexp_tree::expand_branch(HTREEITEM h)
{
Expand(h, TVE_EXPAND);
h = GetChildItem(h);
while (h) {
expand_branch(h);
h = GetNextSiblingItem(h);
}
}
void sexp_tree::merge_operator(int node)
{
/* char buf[256];
int child;
if (nodes[node].flags == EDITABLE) // data
node = nodes[node].parent;
if (node != -1) {
child = nodes[node].child;
if (child != -1 && nodes[child].next == -1 && nodes[child].child == -1) {
sprintf(buf, "%s %s", nodes[node].text, nodes[child].text);
SetItemText(nodes[node].handle, buf);
nodes[node].flags = OPERAND | EDITABLE;
nodes[child].flags = COMBINED;
DeleteItem(nodes[child].handle);
nodes[child].handle = NULL;
return;
}
}*/
}
// add a data node under operator pointed to by item_index
int sexp_tree::add_data(char *data, int type)
{
int node;
expand_operator(item_index);
node = allocate_node(item_index);
set_node(node, type, data);
nodes[node].handle = insert(data, BITMAP_DATA, BITMAP_DATA, nodes[item_index].handle);
nodes[node].flags = EDITABLE;
*modified = 1;
return node;
}
// add a (variable) data node under operator pointed to by item_index
int sexp_tree::add_variable_data(char *data, int type)
{
int node;
Assert(type & SEXPT_VARIABLE);
expand_operator(item_index);
node = allocate_node(item_index);
set_node(node, type, data);
nodes[node].handle = insert(data, BITMAP_VARIABLE, BITMAP_VARIABLE, nodes[item_index].handle);
nodes[node].flags = NOT_EDITABLE;
*modified = 1;
return node;
}
// add an operator under operator pointed to by item_index. Updates item_index to point
// to this new operator.
void sexp_tree::add_operator(char *op, HTREEITEM h)
{
int node;
if (item_index == -1) {
node = allocate_node(-1);
set_node(node, (SEXPT_OPERATOR | SEXPT_VALID), op);
item_handle = nodes[node].handle = insert(op, BITMAP_OPERATOR, BITMAP_OPERATOR, h);
} else {
expand_operator(item_index);
node = allocate_node(item_index);
set_node(node, (SEXPT_OPERATOR | SEXPT_VALID), op);
item_handle = nodes[node].handle = insert(op, BITMAP_OPERATOR, BITMAP_OPERATOR, nodes[item_index].handle);
}
nodes[node].flags = OPERAND;
item_index = node;
*modified = 1;
}
// add an operator with one argument under operator pointed to by item_index. This function
// exists because the one arg case is a special case. The operator and argument is
// displayed on the same line.
/*void sexp_tree::add_one_arg_operator(char *op, char *data, int type)
{
char str[80];
int node1, node2;
expand_operator(item_index);
node1 = allocate_node(item_index);
node2 = allocate_node(node1);
set_node(node1, SEXPT_OPERATOR, op);
set_node(node2, type, data);
sprintf(str, "%s %s", op, data);
nodes[node1].handle = insert(str, nodes[item_index].handle);
nodes[node1].flags = OPERAND | EDITABLE;
nodes[node2].flags = COMBINED;
*modified = 1;
}*/
/*
int sexp_tree::verify_tree(int *bypass)
{
return verify_tree(0, bypass);
}
// check the sexp tree for errors. Return -1 if error, or 0 if no errors. If an error
// is found, item_index = node of error.
int sexp_tree::verify_tree(int node, int *bypass)
{
int i, type, count, op, type2, op2, argnum = 0;
if (!total)
return 0; // nothing to check
Assert(node >= 0 && node < MAX_SEXP_TREE_SIZE);
Assert(nodes[node].type == SEXPT_OPERATOR);
op = identify_operator(nodes[node].text);
if (op == -1)
return node_error(node, "Unknown operator", bypass);
count = count_args(nodes[node].child);
if (count < Operators[op].min)
return node_error(node, "Too few arguments for operator", bypass);
if (count > Operators[op].max)
return node_error(node, "Too many arguments for operator", bypass);
node = nodes[node].child; // get first argument
while (node != -1) {
type = query_operator_argument_type(op, argnum);
Assert(nodes[node].type & SEXPT_VALID);
if (nodes[node].type == SEXPT_OPERATOR) {
if (verify_tree(node) == -1)
return -1;
op2 = identify_operator(nodes[node].text); // no error checking, because it was done in the call above.
type2 = query_operator_return_type(op2);
} else if (nodes[node].type == SEXPT_NUMBER) {
char *ptr;
type2 = OPR_NUMBER;
ptr = nodes[node].text;
while (*ptr)
if (!isdigit(*ptr++))
return node_error(node, "Number is invalid", bypass);
} else if (nodes[node].type == SEXPT_STRING) {
type2 = SEXP_ATOM_STRING;
} else
Assert(0); // unknown and invalid sexp node type.
switch (type) {
case OPF_NUMBER:
if (type2 != OPR_NUMBER)
return node_error(node, "Number or number return type expected here", bypass);
break;
case OPF_SHIP:
if (type2 == SEXP_ATOM_STRING)
if (ship_name_lookup(nodes[node].text, 1) == -1)
type2 = 0;
if (type2 != SEXP_ATOM_STRING)
return node_error(node, "Ship name expected here", bypass);
break;
case OPF_WING:
if (type2 == SEXP_ATOM_STRING)
if (wing_name_lookup(nodes[node].text) == -1)
type2 = 0;
if (type2 != SEXP_ATOM_STRING)
return node_error(node, "Wing name expected here", bypass);
break;
case OPF_SHIP_WING:
if (type2 == SEXP_ATOM_STRING)
if (ship_name_lookup(nodes[node].text, 1) == -1)
if (wing_name_lookup(nodes[node].text) == -1)
type2 = 0;
if (type2 != SEXP_ATOM_STRING)
return node_error(node, "Ship or wing name expected here", bypass);
break;
case OPF_BOOL:
if (type2 != OPR_BOOL)
return node_error(node, "Boolean return type expected here", bypass);
break;
case OPF_NULL:
if (type2 != OPR_NULL)
return node_error(node, "No return type operator expected here", bypass);
break;
case OPF_POINT:
if (type2 != SEXP_ATOM_STRING || verify_vector(nodes[node].text))
return node_error(node, "3d coordinate expected here", bypass);
break;
case OPF_SUBSYSTEM:
case OPF_AWACS_SUBSYSTEM:
case OPF_ROTATING_SUBSYSTEM:
if (type2 == SEXP_ATOM_STRING)
if (ai_get_subsystem_type(nodes[node].text) == SUBSYSTEM_UNKNOWN)
type2 = 0;
if (type2 != SEXP_ATOM_STRING)
return node_error(node, "Subsystem name expected here", bypass);
break;
case OPF_IFF:
if (type2 == SEXP_ATOM_STRING) {
for (i=0; i<Num_team_names; i++)
if (!stricmp(Team_names[i], nodes[node].text))
break;
}
if (i == Num_team_names)
return node_error(node, "Iff team type expected here", bypass);
break;
case OPF_AI_GOAL:
if (type2 != OPR_AI_GOAL)
return node_error(node, "Ai goal return type expected here", bypass);
break;
case OPF_DOCKER_POINT:
if (type2 != SEXP_ATOM_STRING)
return node_error(node, "Docker docking point name expected here", bypass);
break;
case OPF_DOCKEE_POINT:
if (type2 != SEXP_ATOM_STRING)
return node_error(node, "Dockee docking point name expected here", bypass);
break;
}
node = nodes[node].next;
argnum++;
}
return 0;
}
*/
// display an error message and position to point of error (a node)
int sexp_tree::node_error(int node, char *msg, int *bypass)
{
char text[512];
if (bypass)
*bypass = 1;
item_index = node;
item_handle = nodes[node].handle;
if (nodes[node].flags & COMBINED)
item_handle = nodes[nodes[node].parent].handle;
ensure_visible(node);
SelectItem(item_handle);
sprintf(text, "%s\n\nContinue checking for more errors?", msg);
if (MessageBox(text, "Sexp error", MB_YESNO | MB_ICONEXCLAMATION) == IDNO)
return -1;
else
return 0;
}
void sexp_tree::hilite_item(int node)
{
ensure_visible(node);
SelectItem(nodes[node].handle);
}
// because the MFC function EnsureVisible() doesn't do what it says it does, I wrote this.
void sexp_tree::ensure_visible(int node)
{
Assert(node != -1);
if (nodes[node].parent != -1)
ensure_visible(nodes[node].parent); // expand all parents first
if (nodes[node].child != -1) // expandable?
Expand(nodes[node].handle, TVE_EXPAND); // expand this item
}
void sexp_tree::link_modified(int *ptr)
{
modified = ptr;
}
void get_variable_default_text_from_variable_text(char *text, char *default_text)
{
int len;
char *start;
// find '('
start = strstr(text, "(");
Assert(start);
start++;
// get length and copy all but last char ")"
len = strlen(start);
strncpy(default_text, start, len-1);
// add null termination
default_text[len-1] = '\0';
}
void get_variable_name_from_sexp_tree_node_text(const char *text, char *var_name)
{
int length;
length = strcspn(text, "(");
strncpy(var_name, text, length);
var_name[length] = '\0';
}
int sexp_tree::get_modify_variable_type()
{
Assert(item_index > -1);
int sexp_var_index = -1;
// get arg
int parent = nodes[item_index].parent;
Assert(parent != -1);
if ( !stricmp(nodes[parent].text, "modify-variable") ) {
Assert(nodes[parent].child != -1);
sexp_var_index = get_tree_name_to_sexp_variable_index(nodes[nodes[parent].child].text);
Assert(sexp_var_index != -1);
} else {
Int3(); // should not be called otherwise
}
if (Sexp_variables[sexp_var_index].type & SEXP_VARIABLE_NUMBER) {
return OPF_NUMBER;
} else if (Sexp_variables[sexp_var_index].type & SEXP_VARIABLE_STRING) {
return OPF_AMBIGUOUS;
} else {
Int3();
return 0;
}
}
void sexp_tree::verify_and_fix_arguments(int node)
{
int op, arg_num, type, tmp;
static int flag = 0;
sexp_list_item *list, *ptr;
if (flag)
return;
flag++;
op = identify_operator(nodes[node].text);
if (op < 0)
return;
tmp = item_index;
item_index = node;
arg_num = 0;
item_index = nodes[node].child;
while (item_index >= 0) {
// get listing of valid argument values for node item_index
type = query_operator_argument_type(op, arg_num);
// special case for modify-variable
if (type == OPF_AMBIGUOUS) {
// check if parent variable type is number, returns OPF_NUMBER or OPF_AMBIGUOUS
type = get_modify_variable_type();
}
if (query_restricted_opf_range(type)) {
list = get_listing_opf(type, node, arg_num);
if (!list && (arg_num >= Operators[op].min)) {
free_node(item_index, 1);
item_index = tmp;
flag--;
return;
}
if (list) {
// get a pointer to nodes[item_index].text for normal value
// or default variable value if variable
char *text_ptr;
char default_variable_text[TOKEN_LENGTH];
if (nodes[item_index].type & SEXPT_VARIABLE) {
// special case for modify-variable
if ( !stricmp(Operators[op].text, "modify-variable") ) {
// make text_ptr to start - before '('
get_variable_name_from_sexp_tree_node_text(nodes[item_index].text, default_variable_text);
text_ptr = default_variable_text;
} else {
get_variable_default_text_from_variable_text(nodes[item_index].text, default_variable_text);
text_ptr = default_variable_text;
}
} else {
text_ptr = nodes[item_index].text;
}
ptr = list;
while (ptr) {
if (ptr->text != NULL) {
// make sure text is not NULL
// check that proposed text is valid for operator
if ( !stricmp(ptr->text, text_ptr) )
break;
ptr = ptr->next;
} else {
// text is NULL, so set ptr to NULL to end loop
ptr = NULL;
}
}
if (!ptr) { // argument isn't in list of valid choices,
if (list->op >= 0) {
replace_operator(list->text);
} else {
replace_data(list->text, list->type);
}
}
} else {
bool invalid = false;
if (type == OPF_AMBIGUOUS) {
if (SEXPT_TYPE(nodes[item_index].type) == SEXPT_OPERATOR) {
invalid = true;
}
} else {
if (SEXPT_TYPE(nodes[item_index].type) != SEXPT_OPERATOR) {
invalid = true;
}
}
if (invalid) {
replace_data("<Invalid>", (SEXPT_STRING | SEXPT_VALID));
}
}
if (nodes[item_index].type & SEXPT_OPERATOR)
verify_and_fix_arguments(item_index);
}
item_index = nodes[item_index].next;
arg_num++;
}
item_index = tmp;
flag--;
}
void sexp_tree::replace_data(char *data, int type)
{
int node;
HTREEITEM h;
node = nodes[item_index].child;
if (node != -1)
free_node2(node);
nodes[item_index].child = -1;
h = nodes[item_index].handle;
while (ItemHasChildren(h))
DeleteItem(GetChildItem(h));
set_node(item_index, type, data);
SetItemText(h, data);
SetItemImage(h, BITMAP_DATA, BITMAP_DATA);
nodes[item_index].flags = EDITABLE;
// check remaining data beyond replaced data for validity (in case any of it is dependent on data just replaced)
verify_and_fix_arguments(nodes[item_index].parent);
*modified = 1;
update_help(GetSelectedItem());
}
// Replaces data with sexp_variable type data
void sexp_tree::replace_variable_data(int var_idx, int type)
{
int node;
HTREEITEM h;
char buf[128];
Assert(type & SEXPT_VARIABLE);
node = nodes[item_index].child;
if (node != -1)
free_node2(node);
nodes[item_index].child = -1;
h = nodes[item_index].handle;
while (ItemHasChildren(h)) {
DeleteItem(GetChildItem(h));
}
// Assemble name
sprintf(buf, "%s(%s)", Sexp_variables[var_idx].variable_name, Sexp_variables[var_idx].text);
set_node(item_index, type, buf);
SetItemText(h, buf);
SetItemImage(h, BITMAP_VARIABLE, BITMAP_VARIABLE);
nodes[item_index].flags = NOT_EDITABLE;
// check remaining data beyond replaced data for validity (in case any of it is dependent on data just replaced)
verify_and_fix_arguments(nodes[item_index].parent);
*modified = 1;
update_help(GetSelectedItem());
}
void sexp_tree::replace_operator(char *op)
{
int node;
HTREEITEM h;
node = nodes[item_index].child;
if (node != -1)
free_node2(node);
nodes[item_index].child = -1;
h = nodes[item_index].handle;
while (ItemHasChildren(h))
DeleteItem(GetChildItem(h));
set_node(item_index, (SEXPT_OPERATOR | SEXPT_VALID), op);
SetItemText(h, op);
nodes[item_index].flags = OPERAND;
*modified = 1;
update_help(GetSelectedItem());
// hack added at Allender's request. If changing ship in an ai-dock operator, re-default
// docking point.
}
/*void sexp_tree::replace_one_arg_operator(char *op, char *data, int type)
{
char str[80];
int node;
HTREEITEM h;
node = nodes[item_index].child;
if (node != -1)
free_node2(node);
nodes[item_index].child = -1;
h = nodes[item_index].handle;
while (ItemHasChildren(h))
DeleteItem(GetChildItem(h));
node = allocate_node(item_index);
set_node(item_index, SEXPT_OPERATOR, op);
set_node(node, type, data);
sprintf(str, "%s %s", op, data);
SetItemText(h, str);
nodes[item_index].flags = OPERAND | EDITABLE;
nodes[node].flags = COMBINED;
*modified = 1;
update_help(GetSelectedItem());
}*/
// moves a whole sexp tree branch to a new position under 'parent' and after 'after'.
// The expansion state is preserved, and node handles are updated.
void sexp_tree::move_branch(int source, int parent)
{
int node;
// if no source, skip everything
if (source != -1) {
node = nodes[source].parent;
if (node != -1) {
if (nodes[node].child == source)
nodes[node].child = nodes[source].next;
else {
node = nodes[node].child;
while (nodes[node].next != source) {
node = nodes[node].next;
Assert(node != -1);
}
nodes[node].next = nodes[source].next;
}
}
nodes[source].parent = parent;
nodes[source].next = -1;
if (parent) {
if (nodes[parent].child == -1)
nodes[parent].child = source;
else {
node = nodes[parent].child;
while (nodes[node].next != -1)
node = nodes[node].next;
nodes[node].next = source;
}
move_branch(nodes[source].handle, nodes[parent].handle);
} else
move_branch(nodes[source].handle);
}
}
HTREEITEM sexp_tree::move_branch(HTREEITEM source, HTREEITEM parent, HTREEITEM after)
{
int i, image1, image2;
HTREEITEM h = 0, child, next;
if (source) {
for (i=0; i<MAX_SEXP_TREE_SIZE; i++)
if (nodes[i].handle == source)
break;
if (i < MAX_SEXP_TREE_SIZE) {
GetItemImage(source, image1, image2);
h = insert(GetItemText(source), image1, image2, parent, after);
nodes[i].handle = h;
} else {
GetItemImage(source, image1, image2);
h = insert(GetItemText(source), image1, image2, parent, after);
}
SetItemData(h, GetItemData(source));
child = GetChildItem(source);
while (child) {
next = GetNextSiblingItem(child);
move_branch(child, h);
child = next;
}
if (GetItemState(source, TVIS_EXPANDED) & TVIS_EXPANDED)
Expand(h, TVE_EXPAND);
DeleteItem(source);
}
return h;
}
void sexp_tree::copy_branch(HTREEITEM source, HTREEITEM parent, HTREEITEM after)
{
int i, image1, image2;
HTREEITEM h, child;
if (source) {
for (i=0; i<MAX_SEXP_TREE_SIZE; i++)
if (nodes[i].handle == source)
break;
if (i < MAX_SEXP_TREE_SIZE) {
GetItemImage(source, image1, image2);
h = insert(GetItemText(source), image1, image2, parent, after);
nodes[i].handle = h;
} else {
GetItemImage(source, image1, image2);
h = insert(GetItemText(source), image1, image2, parent, after);
}
SetItemData(h, GetItemData(source));
child = GetChildItem(source);
while (child) {
copy_branch(child, h);
child = GetNextSiblingItem(child);
}
if (GetItemState(source, TVIS_EXPANDED) & TVIS_EXPANDED)
Expand(h, TVE_EXPAND);
}
}
void sexp_tree::swap_roots(HTREEITEM one, HTREEITEM two)
{
HTREEITEM h;
Assert(!GetParentItem(one));
Assert(!GetParentItem(two));
// copy_branch(one, TVI_ROOT, two);
// move_branch(two, TVI_ROOT, one);
// DeleteItem(one);
h = move_branch(one, TVI_ROOT, two);
SelectItem(h);
SelectItem(h);
*modified = 1;
}
void sexp_tree::OnBegindrag(NMHDR* pNMHDR, LRESULT* pResult)
{
UINT flags;
// ScreenToClient(&m_pt);
ASSERT(!m_dragging);
m_h_drag = HitTest(m_pt, &flags);
m_h_drop = NULL;
if (!m_mode || GetParentItem(m_h_drag))
return;
ASSERT(m_p_image_list == NULL);
m_p_image_list = CreateDragImage(m_h_drag); // get the image list for dragging
if (!m_p_image_list)
return;
m_p_image_list->DragShowNolock(TRUE);
m_p_image_list->SetDragCursorImage(0, CPoint(0, 0));
m_p_image_list->BeginDrag(0, CPoint(0,0));
m_p_image_list->DragMove(m_pt);
m_p_image_list->DragEnter(this, m_pt);
SetCapture();
m_dragging = TRUE;
}
void sexp_tree::OnLButtonDown(UINT nFlags, CPoint point)
{
m_pt = point;
CTreeCtrl::OnLButtonDown(nFlags, point);
}
void sexp_tree::OnMouseMove(UINT nFlags, CPoint point)
{
HTREEITEM hitem;
UINT flags;
if (m_dragging) {
ASSERT(m_p_image_list != NULL);
m_p_image_list->DragMove(point);
if ((hitem = HitTest(point, &flags)) != NULL)
if (!GetParentItem(hitem)) {
m_p_image_list->DragLeave(this);
SelectDropTarget(hitem);
m_h_drop = hitem;
m_p_image_list->DragEnter(this, point);
}
}
CTreeCtrl::OnMouseMove(nFlags, point);
}
void sexp_tree::OnLButtonUp(UINT nFlags, CPoint point)
{
int index1, index2;
if (m_dragging) {
ASSERT(m_p_image_list != NULL);
m_p_image_list->DragLeave(this);
m_p_image_list->EndDrag();
delete m_p_image_list;
m_p_image_list = NULL;
if (m_h_drop && m_h_drag != m_h_drop) {
Assert(m_h_drag);
index1 = GetItemData(m_h_drag);
index2 = GetItemData(m_h_drop);
swap_roots(m_h_drag, m_h_drop);
if (m_mode == MODE_GOALS) {
Assert(Goal_editor_dlg);
Goal_editor_dlg->swap_handler(index1, index2);
} else if (m_mode == MODE_EVENTS) {
Assert(Event_editor_dlg);
Event_editor_dlg->swap_handler(index1, index2);
} else if (m_mode == MODE_CAMPAIGN) {
Campaign_tree_formp->swap_handler(index1, index2);
} else
Assert(0);
} else
MessageBeep(0);
ReleaseCapture();
m_dragging = FALSE;
SelectDropTarget(NULL);
}
CTreeCtrl::OnLButtonUp(nFlags, point);
}
void sexp_tree::setup(CEdit *ptr)
{
CImageList *pimagelist;
CBitmap bitmap;
help_box = ptr;
if (help_box) {
int stops[2] = { 10, 30 };
help_box -> SetTabStops(2, (LPINT) stops);
}
pimagelist = GetImageList(TVSIL_NORMAL);
if (!pimagelist) {
pimagelist = new CImageList();
pimagelist->Create(16, 16, TRUE/*bMask*/, 2, 9);
bitmap.LoadBitmap(IDB_OPERATOR);
pimagelist->Add(&bitmap, (COLORREF) 0xFFFFFF);
bitmap.DeleteObject();
bitmap.LoadBitmap(IDB_DATA);
pimagelist->Add(&bitmap, (COLORREF) 0xFF00FF);
bitmap.DeleteObject();
bitmap.LoadBitmap(IDB_VARIABLE);
pimagelist->Add(&bitmap, (COLORREF) 0xFF00FF);
bitmap.DeleteObject();
bitmap.LoadBitmap(IDB_ROOT);
pimagelist->Add(&bitmap, (COLORREF) 0xFF00FF);
bitmap.DeleteObject();
bitmap.LoadBitmap(IDB_ROOT_DIRECTIVE);
pimagelist->Add(&bitmap, (COLORREF) 0xFFFFFF);
bitmap.DeleteObject();
bitmap.LoadBitmap(IDB_CHAINED);
pimagelist->Add(&bitmap, (COLORREF) 0xFF00FF);
bitmap.DeleteObject();
bitmap.LoadBitmap(IDB_CHAINED_DIRECTIVE);
pimagelist->Add(&bitmap, (COLORREF) 0xFFFFFF);
bitmap.DeleteObject();
bitmap.LoadBitmap(IDB_GREEN_DOT);
pimagelist->Add(&bitmap, (COLORREF) 0xFFFFFF);
bitmap.DeleteObject();
bitmap.LoadBitmap(IDB_BLACK_DOT);
pimagelist->Add(&bitmap, (COLORREF) 0xFFFFFF);
bitmap.DeleteObject();
SetImageList(pimagelist, TVSIL_NORMAL);
}
}
//#define BITMAP_OPERATOR 0
//#define BITMAP_DATA 1
//#define BITMAP_VARIABLE 2
//#define BITMAP_ROOT 3
//#define BITMAP_ROOT_DIRECTIVE 4
//#define BITMAP_CHAIN 5
//#define BITMAP_CHAIN_DIRECTIVE 6
//#define BITMAP_GREEN_DOT 7
//#define BITMAP_BLACK_DOT 8
HTREEITEM sexp_tree::insert(LPCTSTR lpszItem, int image, int sel_image, HTREEITEM hParent, HTREEITEM hInsertAfter)
{
return InsertItem(lpszItem, image, sel_image, hParent, hInsertAfter);
}
void sexp_tree::OnDestroy()
{
CImageList *pimagelist;
pimagelist = GetImageList(TVSIL_NORMAL);
if (pimagelist) {
pimagelist->DeleteImageList();
delete pimagelist;
}
CTreeCtrl::OnDestroy();
}
HTREEITEM sexp_tree::handle(int node)
{
return nodes[node].handle;
}
char *sexp_tree::help(int code)
{
int i;
i = sizeof(Sexp_help) / sizeof(sexp_help_struct);
while (i--) {
if (Sexp_help[i].id == code)
break;
}
if (i >= 0)
return Sexp_help[i].help;
return NULL;
}
// get type of item clicked on
int sexp_tree::get_type(HTREEITEM h)
{
int i;
// get index into sexp_tree
for (i=0; i<MAX_SEXP_TREE_SIZE; i++)
if (nodes[i].handle == h)
break;
if ( (i >= MAX_SEXP_TREE_SIZE) ) {
// Int3(); // This would be the root of the tree -- ie, event name
return -1;
}
return nodes[i].type;
}
void sexp_tree::update_help(HTREEITEM h)
{
char *str;
int i, j, z, c, code;
CString text;
for (i=0; i<Num_operators; i++)
for (j=0; j<Num_op_menus; j++)
if ((Operators[i].value & OP_CATEGORY_MASK) == op_menu[j].id) {
if (!help(Operators[i].value))
Int3(); // Allender! If you add new sexp operators, add help for them too! :)
}
help_box = (CEdit *) GetParent()->GetDlgItem(IDC_HELP_BOX);
if (!help_box || !::IsWindow(help_box->m_hWnd))
return;
for (i=0; i<MAX_SEXP_TREE_SIZE; i++)
if (nodes[i].handle == h)
break;
if ((i >= MAX_SEXP_TREE_SIZE) || !nodes[i].type) {
help_box->SetWindowText("");
return;
}
if (SEXPT_TYPE(nodes[i].type) != SEXPT_OPERATOR) {
z = nodes[i].parent;
if (z < 0) {
Warning(LOCATION, "Sexp data \"%s\" has no parent!", nodes[i].text);
return;
}
code = identify_operator(nodes[z].text);
if (code >= 0) {
c = 0;
j = nodes[z].child;
while ((j >= 0) && (j != i)) {
j = nodes[j].next;
c++;
}
Assert(j >= 0);
if (query_operator_argument_type(code, c) == OPF_MESSAGE) {
for (j=0; j<Num_messages; j++)
if (!stricmp(Messages[j].name, nodes[i].text)) {
text.Format("Message Text:\r\n%s", Messages[j].message);
help_box->SetWindowText(text);
return;
}
}
}
i = z;
}
code = find_operator(nodes[i].text);
str = help(code);
if (!str)
str = "No help available";
help_box->SetWindowText(str);
}
// find list of sexp_tree nodes with text
// stuff node indices into find[]
int sexp_tree::find_text(char *text, int *find)
{
int i, find_count;
// initialize find
for (i=0; i<MAX_SEARCH_MESSAGE_DEPTH; i++) {
find[i] = -1;
}
find_count = 0;
for (i=0; i<MAX_SEXP_TREE_SIZE; i++) {
// only look at used and editable nodes
if ((nodes[i].flags & EDITABLE && (nodes[i].type != SEXPT_UNUSED))) {
// find the text
if ( !stricmp(nodes[i].text, text) ) {
find[find_count++] = i;
// don't exceed max count - array bounds
if (find_count == MAX_SEARCH_MESSAGE_DEPTH) {
break;
}
}
}
}
return find_count;
}
void sexp_tree::OnKeydown(NMHDR *pNMHDR, LRESULT *pResult)
{
int key;
TV_KEYDOWN *pTVKeyDown = (TV_KEYDOWN *) pNMHDR;
key = pTVKeyDown->wVKey;
if (key == VK_SPACE)
EditLabel(GetSelectedItem());
*pResult = 0;
}
// Determine if a given opf code has a restricted argument range (i.e. has a specific, limited
// set of argument values, or has virtually unlimited possibilities. For example, boolean values
// only have true or false, so it is restricted, but a number could be anything, so it's not.
//
int sexp_tree::query_restricted_opf_range(int opf)
{
switch (opf) {
case OPF_NUMBER:
case OPF_POSITIVE:
case OPF_WHO_FROM:
return 0;
}
return 1;
}
// generate listing of valid argument values.
// opf = operator format to generate list for
// parent_node = the parent node we are generating list for
// arg_index = argument number of parent this argument will go at
//
sexp_list_item *sexp_tree::get_listing_opf(int opf, int parent_node, int arg_index)
{
switch (opf) {
case OPF_NONE:
return NULL;
case OPF_NULL:
return get_listing_opf_null();
case OPF_BOOL:
return get_listing_opf_bool(parent_node);
case OPF_NUMBER:
return get_listing_opf_number();
case OPF_SHIP:
return get_listing_opf_ship(parent_node);
case OPF_WING:
return get_listing_opf_wing();
case OPF_AWACS_SUBSYSTEM:
case OPF_ROTATING_SUBSYSTEM:
case OPF_SUBSYSTEM:
return get_listing_opf_subsystem(parent_node, arg_index);
case OPF_POINT:
return get_listing_opf_point();
case OPF_IFF:
return get_listing_opf_iff();
case OPF_TEAM:
return get_listing_opf_team();
case OPF_AI_CLASS:
return get_listing_opf_ai_class();
case OPF_SUPPORT_SHIP_CLASS:
return get_listing_opf_support_ship_class();
case OPF_ARRIVAL_LOCATION:
return get_listing_opf_arrival_location();
case OPF_DEPARTURE_LOCATION:
return get_listing_opf_departure_location();
case OPF_ARRIVAL_ANCHOR_ALL:
return get_listing_opf_arrival_anchor_all();
case OPF_SHIP_WITH_BAY:
return get_listing_opf_ship_with_bay();
case OPF_SOUNDTRACK_NAME:
return get_listing_opf_soundtrack_name();
case OPF_AI_GOAL:
return get_listing_opf_ai_goal(parent_node);
case OPF_DOCKER_POINT:
return get_listing_opf_docker_point(parent_node);
case OPF_DOCKEE_POINT:
return get_listing_opf_dockee_point(parent_node);
case OPF_MESSAGE:
return get_listing_opf_message();
case OPF_WHO_FROM:
return get_listing_opf_who_from();
case OPF_PRIORITY:
return get_listing_opf_priority();
case OPF_WAYPOINT_PATH:
return get_listing_opf_waypoint_path();
case OPF_POSITIVE:
return get_listing_opf_positive();
case OPF_MISSION_NAME:
return get_listing_opf_mission_name();
case OPF_SHIP_POINT:
return get_listing_opf_ship_point();
case OPF_GOAL_NAME:
return get_listing_opf_goal_name(parent_node);
case OPF_SHIP_WING:
return get_listing_opf_ship_wing();
case OPF_SHIP_WING_POINT:
return get_listing_opf_ship_wing_point();
case OPF_SHIP_TYPE:
return get_listing_opf_ship_type();
case OPF_KEYPRESS:
return get_listing_opf_keypress();
case OPF_EVENT_NAME:
return get_listing_opf_event_name(parent_node);
case OPF_AI_ORDER:
return get_listing_opf_ai_order();
case OPF_SKILL_LEVEL:
return get_listing_opf_skill_level();
case OPF_CARGO:
return get_listing_opf_cargo();
case OPF_STRING:
return get_listing_opf_string();
case OPF_MEDAL_NAME:
return get_listing_opf_medal_name();
case OPF_WEAPON_NAME:
return get_listing_opf_weapon_name();
case OPF_INTEL_NAME:
return get_listing_opf_intel_name();
case OPF_SHIP_CLASS_NAME:
return get_listing_opf_ship_class_name();
case OPF_HUD_GAUGE_NAME:
return get_listing_opf_hud_gauge_name();
case OPF_HUGE_WEAPON:
return get_listing_opf_huge_weapon();
case OPF_SHIP_NOT_PLAYER:
return get_listing_opf_ship_not_player();
case OPF_JUMP_NODE_NAME:
return get_listing_opf_jump_nodes();
case OPF_VARIABLE_NAME:
return get_listing_opf_variable_names();
case OPF_AMBIGUOUS:
return NULL();
default:
Int3(); // unknown OPF code
}
return NULL;
}
sexp_list_item *sexp_tree::get_listing_opf_null()
{
int i;
sexp_list_item head;
for (i=0; i<Num_operators; i++)
if (query_operator_return_type(i) == OPR_NULL)
head.add_op(i);
return head.next;
}
sexp_list_item *sexp_tree::get_listing_opf_bool(int parent_node)
{
int i, only_basic;
sexp_list_item head;
// search for the previous goal/event operators. If found, only add the true/false
// sexpressions to the list
only_basic = 0;
if ( parent_node != -1 ) {
int op;
op = find_operator(nodes[parent_node].text);
if ( (op == OP_PREVIOUS_GOAL_TRUE) || (op == OP_PREVIOUS_GOAL_FALSE) || (op == OP_PREVIOUS_EVENT_TRUE) || (op == OP_PREVIOUS_EVENT_FALSE) )
only_basic = 1;
}
for (i=0; i<Num_operators; i++) {
if (query_operator_return_type(i) == OPR_BOOL) {
if ( !only_basic || (only_basic && ((Operators[i].value == OP_TRUE) || (Operators[i].value == OP_FALSE))) ) {
head.add_op(i);
}
}
}
return head.next;
}
sexp_list_item *sexp_tree::get_listing_opf_positive()
{
int i, z;
sexp_list_item head;
for (i=0; i<Num_operators; i++) {
z = query_operator_return_type(i);
// Goober5000's number hack
if ((z == OPR_NUMBER) || (z == OPR_POSITIVE))
head.add_op(i);
}
return head.next;
}
sexp_list_item *sexp_tree::get_listing_opf_number()
{
int i, z;
sexp_list_item head;
for (i=0; i<Num_operators; i++) {
z = query_operator_return_type(i);
if ((z == OPR_NUMBER) || (z == OPR_POSITIVE))
head.add_op(i);
}
return head.next;
}
sexp_list_item *sexp_tree::get_listing_opf_ship(int parent_node)
{
object *ptr;
sexp_list_item head;
int op = 0, dock_ship = -1, require_cap_ship = 0;
// look at the parent node and get the operator. Some ship lists should be filtered based
// on what the parent operator is
if ( parent_node >= 0 ) {
op = find_operator(nodes[parent_node].text);
// prune out to only capital ships
if (!stricmp(nodes[parent_node].text, "cap-subsys-cargo-known-delay")) {
require_cap_ship = 1;
}
// get the dock_ship number of if this goal is an ai dock goal. used to prune out unwanted ships out
// of the generated ship list
dock_ship = -1;
if ( op == OP_AI_DOCK ) {
int z;
z = nodes[parent_node].parent;
Assert(z >= 0);
Assert(!stricmp(nodes[z].text, "add-ship-goal") || !stricmp(nodes[z].text, "add-wing-goal") || !stricmp(nodes[z].text, "add-goal"));
z = nodes[z].child;
Assert(z >= 0);
dock_ship = ship_name_lookup(nodes[z].text, 1);
Assert( dock_ship != -1 );
}
}
ptr = GET_FIRST(&obj_used_list);
while (ptr != END_OF_LIST(&obj_used_list)) {
if ((ptr->type == OBJ_SHIP) || (ptr->type == OBJ_START)) {
if ( op == OP_AI_DOCK ) {
// only include those ships in the list which the given ship can dock with.
if ( (dock_ship != ptr->instance) && ship_docking_valid(dock_ship , ptr->instance) )
head.add_data(Ships[ptr->instance].ship_name );
} else {
if ( !require_cap_ship || (Ship_info[Ships[ptr->instance].ship_info_index].flags & SIF_HUGE_SHIP) ) {
head.add_data(Ships[ptr->instance].ship_name);
}
}
}
ptr = GET_NEXT(ptr);
}
return head.next;
}
sexp_list_item *sexp_tree::get_listing_opf_wing()
{
int i;
sexp_list_item head;
for (i=0; i<MAX_WINGS; i++){
if (Wings[i].wave_count){
head.add_data(Wings[i].name);
}
}
return head.next;
}
// specific types of subsystems we're looking for
#define OPS_CAP_CARGO 1
#define OPS_STRENGTH 2
#define OPS_BEAM_TURRET 3
#define OPS_AWACS 4
#define OPS_ROTATE 5
sexp_list_item *sexp_tree::get_listing_opf_subsystem(int parent_node, int arg_index)
{
int op, child, sh;
int special_subsys = 0;
sexp_list_item head;
ship_subsys *subsys;
// determine if the parent is one of the set subsystem strength items. If so,
// we want to append the "Hull" name onto the end of the menu
Assert(parent_node >= 0);
// get the operator type of the node
op = find_operator(nodes[parent_node].text);
// first child node
child = nodes[parent_node].child;
Assert(child >= 0);
switch(op){
// where we care about hull strength
case OP_REPAIR_SUBSYSTEM:
case OP_SABOTAGE_SUBSYSTEM:
case OP_SET_SUBSYSTEM_STRNGTH:
special_subsys = OPS_STRENGTH;
break;
// awacs subsystems
case OP_AWACS_SET_RADIUS:
special_subsys = OPS_AWACS;
break;
// rotating
case OP_LOCK_ROTATING_SUBSYSTEM:
case OP_FREE_ROTATING_SUBSYSTEM:
special_subsys = OPS_ROTATE;
break;
// where we care about capital ship subsystem cargo
case OP_CAP_SUBSYS_CARGO_KNOWN_DELAY:
special_subsys = OPS_CAP_CARGO;
// get the next sibling
child = nodes[child].next;
break;
// where we care about turrets carrying beam weapons
case OP_BEAM_FIRE:
special_subsys = OPS_BEAM_TURRET;
// if this is arg index 3 (targeted ship)
if(arg_index == 3){
Assert(arg_index == 3);
child = nodes[child].next;
Assert(child >= 0);
child = nodes[child].next;
} else {
Assert(arg_index == 1);
}
break;
// these sexps check the subsystem of the *second entry* on the list, not the first
case OP_DISTANCE_SUBSYSTEM:
case OP_SET_CARGO:
case OP_IS_CARGO:
case OP_CHANGE_AI_CLASS:
case OP_IS_AI_CLASS:
case OP_MISSILE_LOCKED:
child = nodes[child].next; // iterate to the next field
break;
}
// now find the ship and add all relevant subsystems
Assert(child >= 0);
sh = ship_name_lookup(nodes[child].text, 1);
if (sh >= 0) {
subsys = GET_FIRST(&Ships[sh].subsys_list);
while (subsys != END_OF_LIST(&Ships[sh].subsys_list)) {
// add stuff
switch(special_subsys){
// subsystem cargo
case OPS_CAP_CARGO:
if (valid_cap_subsys_cargo_list(subsys->system_info->subobj_name) ) {
head.add_data(subsys->system_info->subobj_name);
}
break;
// beam fire
case OPS_BEAM_TURRET:
head.add_data(subsys->system_info->subobj_name);
break;
// awacs level
case OPS_AWACS:
if (subsys->system_info->flags & MSS_FLAG_AWACS) {
head.add_data(subsys->system_info->subobj_name);
}
break;
// rotating
case OPS_ROTATE:
if (subsys->system_info->flags & MSS_FLAG_ROTATES) {
head.add_data(subsys->system_info->subobj_name);
}
break;
// everything else
default:
// don't want s-foils added to the list
if (subsys->system_info->type == SUBSYSTEM_SFOIL) {
break;
}
head.add_data(subsys->system_info->subobj_name);
break;
}
// next subsystem
subsys = GET_NEXT(subsys);
}
}
// if one of the subsystem strength operators, append the Hull string
if(special_subsys == OPS_STRENGTH){
head.add_data(SEXP_HULL_STRING);
}
return head.next;
}
sexp_list_item *sexp_tree::get_listing_opf_point()
{
char buf[NAME_LENGTH+8];
int i, j;
sexp_list_item head;
for (i=0; i<Num_waypoint_lists; i++)
for (j=0; j<Waypoint_lists[i].count; j++) {
sprintf(buf, "%s:%d", Waypoint_lists[i].name, j + 1);
head.add_data_dup(buf);
}
return head.next;
}
sexp_list_item *sexp_tree::get_listing_opf_team()
{
int i;
sexp_list_item head;
for (i=0; i<Num_team_names; i++)
head.add_data(Team_names[i]);
return head.next;
}
sexp_list_item *sexp_tree::get_listing_opf_iff()
{
int i;
sexp_list_item head;
for (i=0; i<MAX_IFF; i++)
head.add_data(Iff_names[i]);
return head.next;
}
sexp_list_item *sexp_tree::get_listing_opf_ai_class()
{
int i;
sexp_list_item head;
for (i=0; i<Num_ai_classes; i++)
head.add_data(Ai_class_names[i]);
return head.next;
}
sexp_list_item *sexp_tree::get_listing_opf_support_ship_class()
{
int i;
sexp_list_item head;
head.add_data("<any support ship class>");
for (i=0; i<Num_ship_types; i++)
{
if (Ship_info[i].flags & SIF_SUPPORT)
{
head.add_data(Ship_info[i].name);
}
}
return head.next;
}
sexp_list_item *sexp_tree::get_listing_opf_ship_with_bay()
{
object *objp;
sexp_list_item head;
for ( objp = GET_FIRST(&obj_used_list); objp != END_OF_LIST(&obj_used_list); objp = GET_NEXT(objp) )
{
if ( (objp->type == OBJ_SHIP) || (objp->type == OBJ_START) )
{
// determine if this ship has a docking bay
if (ship_has_dock_bay(objp->instance))
{
head.add_data(Ships[objp->instance].ship_name);
}
}
}
head.add_data("<no anchor>");
return head.next;
}
sexp_list_item *sexp_tree::get_listing_opf_soundtrack_name()
{
int i;
sexp_list_item head;
head.add_data("<No Music>");
for (i=0; i<Num_soundtracks; i++)
{
head.add_data(Soundtracks[i].name);
}
return head.next;
}
sexp_list_item *sexp_tree::get_listing_opf_arrival_location()
{
int i;
sexp_list_item head;
for (i=0; i<MAX_ARRIVAL_NAMES; i++)
head.add_data(Arrival_location_names[i]);
return head.next;
}
sexp_list_item *sexp_tree::get_listing_opf_departure_location()
{
int i;
sexp_list_item head;
for (i=0; i<MAX_DEPARTURE_NAMES; i++)
head.add_data(Departure_location_names[i]);
return head.next;
}
sexp_list_item *sexp_tree::get_listing_opf_arrival_anchor_all()
{
int i;
object *objp;
sexp_list_item head;
for (i=0; i<MAX_SPECIAL_ARRIVAL_ANCHORS; i++)
head.add_data(Special_arrival_anchor_names[i]);
for ( objp = GET_FIRST(&obj_used_list); objp != END_OF_LIST(&obj_used_list); objp = GET_NEXT(objp) )
{
if ( (objp->type == OBJ_SHIP) || (objp->type == OBJ_START) )
{
head.add_data(Ships[objp->instance].ship_name);
}
}
return head.next;
}
sexp_list_item *sexp_tree::get_listing_opf_ai_goal(int parent_node)
{
int i, n, w, z, child;
sexp_list_item head;
Assert(parent_node >= 0);
child = nodes[parent_node].child;
Assert(child >= 0);
n = ship_name_lookup(nodes[child].text, 1);
if (n >= 0) {
// add operators if it's an ai-goal and ai-goal is allowed for that ship
for (i=0; i<Num_operators; i++) {
if ( (query_operator_return_type(i) == OPR_AI_GOAL) && query_sexp_ai_goal_valid(Operators[i].value, n) )
head.add_op(i);
}
} else {
z = wing_name_lookup(nodes[child].text);
if (z >= 0) {
for (w=0; w<Wings[z].wave_count; w++) {
n = Wings[z].ship_index[w];
// add operators if it's an ai-goal and ai-goal is allowed for that ship
for (i=0; i<Num_operators; i++) {
if ( (query_operator_return_type(i) == OPR_AI_GOAL) && query_sexp_ai_goal_valid(Operators[i].value, n) )
head.add_op(i);
}
}
} else
return NULL; // no valid ship or wing to check against, make nothing available
}
return head.next;
}
sexp_list_item *sexp_tree::get_listing_opf_docker_point(int parent_node)
{
int i, z, sh;
sexp_list_item head;
Assert(parent_node >= 0);
Assert(!stricmp(nodes[parent_node].text, "ai-dock"));
z = nodes[parent_node].parent;
Assert(z >= 0);
Assert(!stricmp(nodes[z].text, "add-ship-goal") || !stricmp(nodes[z].text, "add-wing-goal") || !stricmp(nodes[z].text, "add-goal"));
z = nodes[z].child;
Assert(z >= 0);
sh = ship_name_lookup(nodes[z].text, 1);
if (sh >= 0) {
z = get_docking_list(Ships[sh].modelnum);
for (i=0; i<z; i++)
head.add_data(Docking_bay_list[i]);
}
return head.next;
}
sexp_list_item *sexp_tree::get_listing_opf_dockee_point(int parent_node)
{
int i, z, sh;
sexp_list_item head;
Assert(parent_node >= 0);
Assert(!stricmp(nodes[parent_node].text, "ai-dock"));
z = nodes[parent_node].child;
Assert(z >= 0);
sh = ship_name_lookup(nodes[z].text, 1);
if (sh >= 0) {
z = get_docking_list(Ships[sh].modelnum);
for (i=0; i<z; i++)
head.add_data(Docking_bay_list[i]);
}
return head.next;
}
sexp_list_item *sexp_tree::get_listing_opf_message()
{
char *str;
int i;
sexp_list_item head;
if (m_mode == MODE_EVENTS) {
Assert(Event_editor_dlg);
// this for looks a litle strange, but had to do it get rid of a warning. Conditional
//uses last statement is sequence, i.e. same as for (i=0, str, i++)
for (i=0; str = Event_editor_dlg->current_message_name(i), str; i++)
head.add_data(str);
} else {
for (i=Num_builtin_messages; i<Num_messages; i++)
head.add_data(Messages[i].name);
}
return head.next;
}
sexp_list_item *sexp_tree::get_listing_opf_who_from()
{
object *ptr;
sexp_list_item head;
//head.add_data("<any allied>");
head.add_data("#Command");
head.add_data("<any wingman>");
ptr = GET_FIRST(&obj_used_list);
while (ptr != END_OF_LIST(&obj_used_list)) {
if ((ptr->type == OBJ_SHIP) || (ptr->type == OBJ_START))
if (!(Ship_info[Ships[get_ship_from_obj(ptr)].ship_info_index].flags & SIF_NOT_FLYABLE))
head.add_data(Ships[ptr->instance].ship_name);
ptr = GET_NEXT(ptr);
}
return head.next;
}
sexp_list_item *sexp_tree::get_listing_opf_priority()
{
sexp_list_item head;
head.add_data("High");
head.add_data("Normal");
head.add_data("Low");
return head.next;
}
sexp_list_item *sexp_tree::get_listing_opf_waypoint_path()
{
int i;
sexp_list_item head;
for (i=0; i<Num_waypoint_lists; i++)
head.add_data(Waypoint_lists[i].name);
return head.next;
}
sexp_list_item *sexp_tree::get_listing_opf_ship_point()
{
sexp_list_item head;
head.add_list(get_listing_opf_ship());
head.add_list(get_listing_opf_point());
return head.next;
}
sexp_list_item *sexp_tree::get_listing_opf_ship_wing_point()
{
sexp_list_item head;
head.add_data("<any friendly>");
head.add_data("<any hostile>");
head.add_data("<any neutral>");
head.add_data("<any unknown>");
head.add_list(get_listing_opf_ship());
head.add_list(get_listing_opf_wing());
head.add_list(get_listing_opf_point());
return head.next;
}
sexp_list_item *sexp_tree::get_listing_opf_mission_name()
{
int i;
sexp_list_item head;
if ((m_mode == MODE_CAMPAIGN) && (Cur_campaign_mission >= 0)) {
for (i=0; i<Campaign.num_missions; i++)
if ( (i == Cur_campaign_mission) || (Campaign.missions[i].level < Campaign.missions[Cur_campaign_mission].level) )
head.add_data(Campaign.missions[i].name);
} else
head.add_data(Mission_filename);
return head.next;
}
sexp_list_item *sexp_tree::get_listing_opf_goal_name(int parent_node)
{
int i, m;
sexp_list_item head;
if (m_mode == MODE_CAMPAIGN) {
int child;
Assert(parent_node >= 0);
child = nodes[parent_node].child;
Assert(child >= 0);
for (m=0; m<Campaign.num_missions; m++)
if (!stricmp(Campaign.missions[m].name, nodes[child].text))
break;
if (m < Campaign.num_missions) {
if (Campaign.missions[m].num_goals < 0) // haven't loaded goal names yet.
read_mission_goal_list(m);
for (i=0; i<Campaign.missions[m].num_goals; i++)
head.add_data(Campaign.missions[m].goals[i].name);
}
} else {
for (i=0; i<Num_goals; i++)
head.add_data(Mission_goals[i].name);
}
return head.next;
}
sexp_list_item *sexp_tree::get_listing_opf_ship_wing()
{
sexp_list_item head;
head.add_list(get_listing_opf_ship());
head.add_list(get_listing_opf_wing());
return head.next;
}
sexp_list_item *sexp_tree::get_listing_opf_ship_type()
{
int i;
sexp_list_item head;
for (i=0; i<=9; i++){ //MAX_SHIP_TYPE_COUNTS
head.add_data(Ship_type_names[i]);
}
head.add_data(Ship_type_names[11]);
for (i=13; i<=15; i++){ //MAX_SHIP_TYPE_COUNTS
head.add_data(Ship_type_names[i]);
}
return head.next;
}
sexp_list_item *sexp_tree::get_listing_opf_keypress()
{
int i;
sexp_list_item head;
for (i=0; i<CCFG_MAX; i++) {
if (Control_config[i].key_default > 0) {
head.add_data_dup(textify_scancode(Control_config[i].key_default));
}
}
return head.next;
}
sexp_list_item *sexp_tree::get_listing_opf_event_name(int parent_node)
{
int i, m;
sexp_list_item head;
if (m_mode == MODE_CAMPAIGN) {
int child;
Assert(parent_node >= 0);
child = nodes[parent_node].child;
Assert(child >= 0);
for (m=0; m<Campaign.num_missions; m++)
if (!stricmp(Campaign.missions[m].name, nodes[child].text))
break;
if (m < Campaign.num_missions) {
if (Campaign.missions[m].num_events < 0) // haven't loaded goal names yet.
read_mission_goal_list(m);
for (i=0; i<Campaign.missions[m].num_events; i++)
head.add_data(Campaign.missions[m].events[i].name);
}
} else {
for (i=0; i<Num_mission_events; i++)
head.add_data(Mission_events[i].name);
}
return head.next;
}
sexp_list_item *sexp_tree::get_listing_opf_ai_order()
{
int i;
sexp_list_item head;
for (i=0; i<Fred_comm_orders_max; i++)
head.add_data(Fred_comm_orders[i].menu_text);
return head.next;
}
sexp_list_item *sexp_tree::get_listing_opf_skill_level()
{
int i;
sexp_list_item head;
for (i=0; i<NUM_SKILL_LEVELS; i++)
head.add_data(Skill_level_names(i, 0));
return head.next;
}
sexp_list_item *sexp_tree::get_listing_opf_cargo()
{
sexp_list_item head;
head.add_data("Nothing");
for (int i=0; i<Num_cargo; i++)
{
if (stricmp(Cargo_names[i], "nothing"))
head.add_data(Cargo_names[i]);
}
return head.next;
}
sexp_list_item *sexp_tree::get_listing_opf_string()
{
sexp_list_item head;
head.add_data("<any string>");
return head.next;
}
sexp_list_item *sexp_tree::get_listing_opf_medal_name()
{
int i;
sexp_list_item head;
for (i=0; i<MAX_ASSIGNABLE_MEDALS; i++)
head.add_data(Medals[i].name);
// also add SOC crest (index 17) and Wings (index 13)
head.add_data(Medals[13].name);
head.add_data(Medals[17].name);
return head.next;
}
sexp_list_item *sexp_tree::get_listing_opf_weapon_name()
{
int i;
sexp_list_item head;
for (i=0; i<Num_weapon_types; i++)
head.add_data(Weapon_info[i].name);
return head.next;
}
sexp_list_item *sexp_tree::get_listing_opf_intel_name()
{
int i;
sexp_list_item head;
for (i=0; i<Intel_info_size; i++)
head.add_data(Intel_info[i].name);
return head.next;
}
sexp_list_item *sexp_tree::get_listing_opf_ship_class_name()
{
int i;
sexp_list_item head;
for (i=0; i<Num_ship_types; i++)
head.add_data(Ship_info[i].name);
return head.next;
}
sexp_list_item *sexp_tree::get_listing_opf_hud_gauge_name()
{
int i;
sexp_list_item head;
for (i=0; i<NUM_HUD_GAUGES; i++)
head.add_data(HUD_gauge_text[i]);
return head.next;
}
sexp_list_item *sexp_tree::get_listing_opf_huge_weapon()
{
int i;
sexp_list_item head;
for (i=0; i<Num_weapon_types; i++) {
if (Weapon_info[i].wi_flags & WIF_HUGE)
head.add_data(Weapon_info[i].name);
}
return head.next;
}
sexp_list_item *sexp_tree::get_listing_opf_ship_not_player()
{
object *ptr;
sexp_list_item head;
ptr = GET_FIRST(&obj_used_list);
while (ptr != END_OF_LIST(&obj_used_list)) {
if (ptr->type == OBJ_SHIP)
head.add_data(Ships[ptr->instance].ship_name);
ptr = GET_NEXT(ptr);
}
return head.next;
}
sexp_list_item *sexp_tree::get_listing_opf_jump_nodes()
{
int i;
sexp_list_item head;
for (i = 0; i < Num_jump_nodes; i++ )
head.add_data( Jump_nodes[i].name );
return head.next;
}
// creates list of Sexp_variables
sexp_list_item *sexp_tree::get_listing_opf_variable_names()
{
int i;
sexp_list_item head;
for (i=0; i<MAX_SEXP_VARIABLES; i++) {
if (Sexp_variables[i].type & SEXP_VARIABLE_SET) {
head.add_data( Sexp_variables[i].variable_name );
}
}
return head.next;
}
// Deletes sexp_variable from sexp_tree.
// resets tree to not include given variable, and resets text and type
void sexp_tree::delete_sexp_tree_variable(const char *var_name)
{
char search_str[64];
char replace_text[TOKEN_LENGTH];
sprintf(search_str, "%s(", var_name);
// store old item index
int old_item_index = item_index;
for (int idx=0; idx<MAX_SEXP_TREE_SIZE; idx++) {
if (nodes[idx].type & SEXPT_VARIABLE) {
if ( strstr(nodes[idx].text, search_str) != NULL ) {
// check type is number or string
Assert( (nodes[idx].type & SEXPT_NUMBER) || (nodes[idx].type & SEXPT_STRING) );
// reset type as not variable
int type = nodes[idx].type &= ~SEXPT_VARIABLE;
// reset text
if (nodes[idx].type & SEXPT_NUMBER) {
strcpy(replace_text, "number");
} else {
strcpy(replace_text, "string");
}
// set item_index and replace data
item_index = idx;
replace_data(replace_text, type);
}
}
}
// restore item_index
item_index = old_item_index;
}
// Modify sexp_tree for a change in sexp_variable (name, type, or default value)
void sexp_tree::modify_sexp_tree_variable(const char *old_name, int sexp_var_index)
{
char search_str[64];
int type;
Assert(Sexp_variables[sexp_var_index].type & SEXP_VARIABLE_SET);
Assert( (Sexp_variables[sexp_var_index].type & SEXP_VARIABLE_NUMBER) || (Sexp_variables[sexp_var_index].type & SEXP_VARIABLE_STRING) );
// Get type for sexp_tree node
if (Sexp_variables[sexp_var_index].type & SEXP_VARIABLE_NUMBER) {
type = (SEXPT_NUMBER | SEXPT_VALID);
} else {
type = (SEXPT_STRING | SEXPT_VALID);
}
// store item index;
int old_item_index = item_index;
// Search string in sexp_tree nodes
sprintf(search_str, "%s(", old_name);
for (int idx=0; idx<MAX_SEXP_TREE_SIZE; idx++) {
if (nodes[idx].type & SEXPT_VARIABLE) {
if ( strstr(nodes[idx].text, search_str) != NULL ) {
// temp set item_index
item_index = idx;
// replace variable data
replace_variable_data(sexp_var_index, (type | SEXPT_VARIABLE));
}
}
}
// restore item_index
item_index = old_item_index;
}
// convert from item_index to sexp_variable index, -1 if not
int sexp_tree::get_item_index_to_var_index()
{
// check valid item index and node is a variable
if ( (item_index > 0) && (nodes[item_index].type & SEXPT_VARIABLE) ) {
return get_tree_name_to_sexp_variable_index(nodes[item_index].text);
} else {
return -1;
}
}
int sexp_tree::get_tree_name_to_sexp_variable_index(const char *tree_name)
{
char var_name[TOKEN_LENGTH];
int chars_to_copy = strcspn(tree_name, "(");
Assert(chars_to_copy < TOKEN_LENGTH - 1);
// Copy up to '(' and add null termination
strncpy(var_name, tree_name, chars_to_copy);
var_name[chars_to_copy] = '\0';
// Look up index
return get_index_sexp_variable_name(var_name);
}
int sexp_tree::get_variable_count(const char *var_name)
{
int idx;
int count = 0;
char compare_name[64];
// get name to compare
strcpy(compare_name, var_name);
strcat(compare_name, "(");
// look for compare name
for (idx=0; idx<MAX_SEXP_TREE_SIZE; idx++) {
if (nodes[idx].type & SEXPT_VARIABLE) {
if ( strstr(nodes[idx].text, compare_name) ) {
count++;
}
}
}
return count;
}
| [
"[email protected]"
]
| [
[
[
1,
6946
]
]
]
|
1d577c8fe847cc79900dbf5eb806fe3bb43558a5 | 7b4c786d4258ce4421b1e7bcca9011d4eeb50083 | /C++Primer中文版(第4版)/第一次-代码集合-20090414/第九章 顺序容器/20090210_习题9.35_使用迭代器对string对象进行操作.cpp | bf14573846e1c608e9632cc3e238183db9085de7 | []
| no_license | lzq123218/guoyishi-works | dbfa42a3e2d3bd4a984a5681e4335814657551ef | 4e78c8f2e902589c3f06387374024225f52e5a92 | refs/heads/master | 2021-12-04T11:11:32.639076 | 2011-05-30T14:12:43 | 2011-05-30T14:12:43 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 471 | cpp | #include <iostream>
#include <string>
using namespace std;
int main()
{
string str;
cout << "Enter a string:" << endl;
getline(cin, str);
cout << "What you have enter is:"
<< str << endl;
cout << "Upper:" << endl;
for (string::iterator iter = str.begin(); iter != str.end(); ++iter) {
if (isupper(*iter)) {
cout << *iter << " ";
str.erase(iter);
--iter;
}
}
cout << "Changed:" << endl
<< str << endl;
return 0;
}
| [
"baicaibang@70501136-4834-11de-8855-c187e5f49513"
]
| [
[
[
1,
27
]
]
]
|
4b6cf6bd7bb5dc581762e33266b82918107476fa | 5ac13fa1746046451f1989b5b8734f40d6445322 | /minimangalore/Nebula2/code/nebula2/src/scene/ncharacter3skinanimator_cmds.cc | 8b29fd050d68259a3db5ccab29f0d7447d824912 | []
| no_license | moltenguy1/minimangalore | 9f2edf7901e7392490cc22486a7cf13c1790008d | 4d849672a6f25d8e441245d374b6bde4b59cbd48 | refs/heads/master | 2020-04-23T08:57:16.492734 | 2009-08-01T09:13:33 | 2009-08-01T09:13:33 | 35,933,330 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 946 | cc | //------------------------------------------------------------------------------
// ncharacter3skinanimator_cmds.cc
// (C) 2005 RadonLabs GmbH
//------------------------------------------------------------------------------
#include "scene/ncharacter3skinanimator.h"
#include "kernel/npersistserver.h"
//------------------------------------------------------------------------------
/**
@scriptclass
nCharacter3SkinAnimator
@cppclass
nCharacter3SkinAnimator
@superclass
nanimator
@classinfo
Provide an animated joint skeleton for nSkinShape node.
*/
void
n_initcmds(nClass* cl)
{
cl->BeginCmds();
cl->EndCmds();
}
//------------------------------------------------------------------------------
/**
*/
/*
bool
nCharacter3SkinAnimator::SaveCmds(nPersistServer* ps)
{
if (nSkinAnimator::SaveCmds(ps))
{
return true;
}
return false;
}
*/
| [
"BawooiT@d1c0eb94-fc07-11dd-a7be-4b3ef3b0700c"
]
| [
[
[
1,
41
]
]
]
|
7dfdcae497567c67c09d9752832b0a72acec673b | 95a3e8914ddc6be5098ff5bc380305f3c5bcecb2 | /src/FusionForever_lib/SmallBullet.h | aff65cd66933c9589f69b51d14916f8d35d3ab91 | []
| no_license | danishcake/FusionForever | 8fc3b1a33ac47177666e6ada9d9d19df9fc13784 | 186d1426fe6b3732a49dfc8b60eb946d62aa0e3b | refs/heads/master | 2016-09-05T16:16:02.040635 | 2010-04-24T11:05:10 | 2010-04-24T11:05:10 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 400 | h | #pragma once
#include "projectile.h"
class SmallBullet :
public Projectile
{
protected:
static bool initialised_;
static int fill_dl_;
static int fill_verts_index_;
virtual void InitialiseGraphics();
public:
SmallBullet(Vector3f _position);
virtual ~SmallBullet(void);
virtual void Hit(std::vector<Decoration_ptr>& _spawn, std::vector<Projectile_ptr>& _projectile_spawn);
};
| [
"Edward Woolhouse@e6f1df29-e57c-d74d-9e6e-27e3b006b1a7",
"EdwardDesktop@e6f1df29-e57c-d74d-9e6e-27e3b006b1a7"
]
| [
[
[
1,
14
],
[
16,
16
]
],
[
[
15,
15
]
]
]
|
61b124ce7824f56fc31ea175dfd61db8439ddc96 | 81488d2175ab16c6c942054fa3dcdc7cdce8d8df | /ofxMagnetic/example/src/testApp.h | 7d7c019a0dafec28f4bef20a047106edeaf6e8f1 | []
| no_license | devert/ofxmagnetic | fbaabd0389c9ac4c23683d353b47bfda25c6f33f | b6f1d9ccf744b6c45009ddafa9aa0af02ddddd9c | refs/heads/master | 2020-04-04T05:00:16.008427 | 2010-11-03T23:42:57 | 2010-11-03T23:42:57 | 32,811,146 | 1 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 698 | h | #ifndef _TEST_APP
#define _TEST_APP
#include "ofMain.h"
#include "ofxMagneticApp.h"
class testApp : public ofxMagneticApp
{
public:
// Routines
void setup();
void update();
void draw();
// Events
void keyPressed(int key);
void keyReleased(int key);
void mouseMoved(int x, int y);
void mouseDragged(int x, int y, int button);
void mousePressed(int x, int y, int button);
void mouseReleased(int x, int y, int button);
void windowResized(int w, int h);
void audioReceived(float * input, int bufferSize, int nChannels);
void audioRequested(float * input, int bufferSize, int nChannels);
private:
};
#endif
| [
"[email protected]@70826fe1-adc8-3e30-cfb8-25ad2d9f667f"
]
| [
[
[
1,
32
]
]
]
|
6e9b9aa5f514be67cc2412cb25cf9130d0e9ab96 | fa609a5b5a0e7de3344988a135b923a0f655f59e | /Source/TextTemplate.h | 29d986b51d9f8978a6abb13f4e228754c59f191e | [
"MIT"
]
| permissive | Sija/swift | 3edfd70e1c8d9d54556862307c02d1de7d400a7e | dddedc0612c0d434ebc2322fc5ebded10505792e | refs/heads/master | 2016-09-06T09:59:35.416041 | 2007-08-30T02:29:30 | 2007-08-30T02:29:30 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 620 | h | #pragma once
#ifndef __SWIFT_TEXT_TEMPLATE_H__
#define __SWIFT_TEXT_TEMPLATE_H__
#include <fstream>
#include "iTemplate.h"
#include "Exception.h"
namespace Swift {
class TextTemplate : public iTemplate {
public:
TextTemplate(const StringRef& data, iVariableManager* parent = NULL) :
iTemplate(parent), _data(data) { }
public:
inline void set(const StringRef& data) {
_data = data;
}
inline const String& getData() const {
return _data;
}
inline void load() { }
protected:
String _data;
};
}
#endif // __SWIFT_TEXT_TEMPLATE_H__ | [
"[email protected]"
]
| [
[
[
1,
31
]
]
]
|
f48f57add39dc4f25a5093b19ad9e0f487fbcd3c | ea02e41514b3b979c78af4ea7b5c55e99834036b | /MonoLaunch/MonoCtrl2/MonoCtrl2.h | 8ec8d8430622fd89d0f3c86648a2bc1f2ffc5db5 | [
"MIT"
]
| permissive | isabella232/wintools | 446228b88eb4296633b0c2be05c18fe291d6b5d2 | 203f7b550c0a1660306d4cc0606b1dc6289e8d9a | refs/heads/master | 2022-02-23T13:02:25.859592 | 2010-04-07T16:45:52 | 2010-04-07T16:45:52 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 623 | h | // MonoCtrl2.h : main header file for the PROJECT_NAME application
//
#pragma once
#ifndef __AFXWIN_H__
#error include 'stdafx.h' before including this file for PCH
#endif
#include "resource.h" // main symbols
#include "afxwin.h"
// CMonoCtrl2App:
// See MonoCtrl2.cpp for the implementation of this class
//
class CMonoCtrl2App : public CWinApp
{
public:
CMonoCtrl2App();
// Overrides
public:
virtual BOOL InitInstance();
// Implementation
DECLARE_MESSAGE_MAP()
// The DesktopWindow wrapper
CWnd m_DeskTopWin;
virtual int ExitInstance();
};
extern CMonoCtrl2App theApp; | [
"[email protected]"
]
| [
[
[
1,
35
]
]
]
|
7e274739fd8ed86da49c20ef5ba303ed06f439be | ad80c85f09a98b1bfc47191c0e99f3d4559b10d4 | /code/src/shadow/nshadowcontrol_cmds.cc | 1de2ed61189b7de84ac4bc2afb40d74ee31af81e | []
| no_license | DSPNerd/m-nebula | 76a4578f5504f6902e054ddd365b42672024de6d | 52a32902773c10cf1c6bc3dabefd2fd1587d83b3 | refs/heads/master | 2021-12-07T18:23:07.272880 | 2009-07-07T09:47:09 | 2009-07-07T09:47:09 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 2,558 | cc | #define N_IMPLEMENTS nShadowControl
//------------------------------------------------------------------------------
// nshadowcontrol_cmds.cc
// (C) 2001 RadonLabs GmbH
//------------------------------------------------------------------------------
#include "shadow/nshadowcontrol.h"
#include "kernel/npersistserver.h"
static void n_setcolor(void*, nCmd*);
static void n_getcolor(void*, nCmd*);
//------------------------------------------------------------------------------
/**
@scriptclass
nshadowcontrol
@superclass
nvisnode
@classinfo
Control global attributes of shadow server (like shadow color).
*/
void
n_initcmds(nClass* cl)
{
cl->BeginCmds();
cl->AddCmd("v_setcolor_ffff", 'SCOL', n_setcolor);
cl->AddCmd("ffff_getcolor_v", 'GCOL', n_getcolor);
cl->EndCmds();
}
//------------------------------------------------------------------------------
/**
@cmd
setcolor
@input
f(Red), f(Blue), f(Green), f(Alpha)
@output
v
@info
Set global shadow color (alpha defines transparency).
*/
static void n_setcolor(void* slf, nCmd* cmd)
{
nShadowControl* self = (nShadowControl*) slf;
float f0 = cmd->In()->GetF();
float f1 = cmd->In()->GetF();
float f2 = cmd->In()->GetF();
float f3 = cmd->In()->GetF();
self->SetColor(f0, f1, f2, f3);
}
//------------------------------------------------------------------------------
/**
@cmd
getcolor
@input
v
@output
f(Red), f(Blue), f(Green), f(Alpha)
@info
Get global shadow color
*/
static void n_getcolor(void* slf, nCmd* cmd)
{
nShadowControl* self = (nShadowControl*) slf;
float f0, f1, f2, f3;
self->GetColor(f0, f1, f2, f3);
cmd->Out()->SetF(f0);
cmd->Out()->SetF(f1);
cmd->Out()->SetF(f2);
cmd->Out()->SetF(f3);
}
//------------------------------------------------------------------------------
/**
*/
bool
nShadowControl::SaveCmds(nPersistServer* fs)
{
if (nVisNode::SaveCmds(fs))
{
nCmd* cmd;
float f0, f1, f2, f3;
//--- setcolor ---
cmd = fs->GetCmd(this, 'SCOL');
this->GetColor(f0, f1, f2, f3);
cmd->In()->SetF(f0);
cmd->In()->SetF(f1);
cmd->In()->SetF(f2);
cmd->In()->SetF(f3);
fs->PutCmd(cmd);
return true;
}
return false;
}
//------------------------------------------------------------------------------
| [
"plushe@411252de-2431-11de-b186-ef1da62b6547"
]
| [
[
[
1,
106
]
]
]
|
f9a67edf7b587b862887d05c46c3f72dec5ee534 | d7b345a8a6b0473c325fab661342de295c33b9c8 | /beta/src/usermapi/usermapi.cpp | edb8e3d847066c2d92ab4f8d527c6203cabee80b | []
| no_license | raould/Polaris-Open-Source | 67ccd647bf40de51a3dae903ab70e8c271f3f448 | 10d0ca7e2db9e082e1d2ed2e43fa46875f1b07b2 | refs/heads/master | 2021-01-01T19:19:39.148016 | 2010-05-10T17:39:26 | 2010-05-10T17:39:26 | 631,953 | 3 | 2 | null | null | null | null | UTF-8 | C++ | false | false | 6,864 | cpp | // Copyright 2010 Hewlett-Packard under the terms of the MIT X license
// found at http://www.opensource.org/licenses/mit-license.html
// usermapi.cpp : Defines the entry point for the DLL application.
//
#include "stdafx.h"
#include <mapidefs.h>
#include <mapi.h>
#include <tchar.h>
HINSTANCE hlibMAPI;
LPMAPILOGON m_MAPILogon;
LPMAPILOGOFF m_MAPILogoff;
LPMAPISENDMAIL m_MAPISendMail;
LPMAPISENDDOCUMENTS m_MAPISendDocuments;
LPMAPIFINDNEXT m_MAPIFindNext;
LPMAPIREADMAIL m_MAPIReadMail;
LPMAPISAVEMAIL m_MAPISaveMail;
LPMAPIDELETEMAIL m_MAPIDeleteMail;
LPMAPIFREEBUFFER m_MAPIFreeBuffer;
LPMAPIADDRESS m_MAPIAddress;
LPMAPIDETAILS m_MAPIDetails;
LPMAPIRESOLVENAME m_MAPIResolveName;
BOOL APIENTRY DllMain( HANDLE hModule,
DWORD ul_reason_for_call,
LPVOID lpReserved
)
{
if (DLL_PROCESS_ATTACH == ul_reason_for_call) {
// Determine the user's preferred MAPI client.
BYTE name[128 * sizeof(TCHAR)];
{
HKEY hkcu_mail;
LONG error = RegOpenKey(HKEY_CURRENT_USER, _T("Software\\Clients\\Mail"), &hkcu_mail);
if (ERROR_SUCCESS != error) {
return FALSE;
}
DWORD type;
DWORD size = sizeof name;
error = RegQueryValueEx(hkcu_mail, NULL, NULL, &type, name, &size);
if (ERROR_SUCCESS != error) {
return FALSE;
}
RegCloseKey(hkcu_mail);
}
// Determine the preferred MAPI client's DLLPath.
BYTE dll_path[(MAX_PATH + 1) * sizeof(TCHAR)];
{
HKEY hklm_mail;
LONG error = RegOpenKey(HKEY_LOCAL_MACHINE, _T("Software\\Clients\\Mail"), &hklm_mail);
if (ERROR_SUCCESS != error) {
return FALSE;
}
HKEY hklm_mail_prog;
error = RegOpenKey(hklm_mail, (LPCTSTR)name, &hklm_mail_prog);
if (ERROR_SUCCESS != error) {
return FALSE;
}
DWORD type;
DWORD size = sizeof dll_path;
error = RegQueryValueEx(hklm_mail_prog, _T("DLLPathEx"), NULL, &type, dll_path, &size);
if (ERROR_SUCCESS != error) {
size = sizeof dll_path;
error = RegQueryValueEx(hklm_mail_prog, _T("DLLPath"), NULL, &type, dll_path, &size);
if (ERROR_SUCCESS != error) {
return FALSE;
}
}
RegCloseKey(hklm_mail);
RegCloseKey(hklm_mail_prog);
}
// Get pointers to all the MAPI methods.
hlibMAPI = LoadLibrary((LPCTSTR)dll_path);
m_MAPILogon = (LPMAPILOGON)GetProcAddress(hlibMAPI, "MAPILogon");
m_MAPILogoff = (LPMAPILOGOFF)GetProcAddress(hlibMAPI, "MAPILogoff");
m_MAPISendMail = (LPMAPISENDMAIL)GetProcAddress(hlibMAPI, "MAPISendMail");
m_MAPISendDocuments = (LPMAPISENDDOCUMENTS)GetProcAddress(hlibMAPI, "MAPISendDocuments");
m_MAPIFindNext = (LPMAPIFINDNEXT)GetProcAddress(hlibMAPI, "MAPIFindNext");
m_MAPIReadMail = (LPMAPIREADMAIL)GetProcAddress(hlibMAPI, "MAPIReadMail");
m_MAPISaveMail = (LPMAPISAVEMAIL)GetProcAddress(hlibMAPI, "MAPISaveMail");
m_MAPIDeleteMail = (LPMAPIDELETEMAIL)GetProcAddress(hlibMAPI, "MAPIDeleteMail");
m_MAPIFreeBuffer = (LPMAPIFREEBUFFER)GetProcAddress(hlibMAPI, "MAPIFreeBuffer");
m_MAPIAddress = (LPMAPIADDRESS)GetProcAddress(hlibMAPI, "MAPIAddress");
m_MAPIDetails = (LPMAPIDETAILS)GetProcAddress(hlibMAPI, "MAPIDetails");
m_MAPIResolveName = (LPMAPIRESOLVENAME)GetProcAddress(hlibMAPI, "MAPIResolveName");
}
return TRUE;
}
ULONG FAR PASCAL
MAPILogon(ULONG_PTR ulUIParam,
LPSTR lpszProfileName,
LPSTR lpszPassword,
FLAGS flFlags,
ULONG ulReserved,
LPLHANDLE lplhSession) {
return m_MAPILogon(ulUIParam, lpszProfileName, lpszPassword, flFlags, ulReserved, lplhSession);
}
ULONG FAR PASCAL
MAPILogoff(LHANDLE lhSession,
ULONG_PTR ulUIParam,
FLAGS flFlags,
ULONG ulReserved) {
return m_MAPILogoff(lhSession, ulUIParam, flFlags, ulReserved);
}
ULONG FAR PASCAL
MAPISendMail(LHANDLE lhSession,
ULONG_PTR ulUIParam,
lpMapiMessage lpMessage,
FLAGS flFlags,
ULONG ulReserved) {
return m_MAPISendMail(lhSession, ulUIParam, lpMessage, flFlags, ulReserved);
}
ULONG FAR PASCAL
MAPISendDocuments(ULONG_PTR ulUIParam,
LPSTR lpszDelimChar,
LPSTR lpszFilePaths,
LPSTR lpszFileNames,
ULONG ulReserved) {
return m_MAPISendDocuments(ulUIParam, lpszDelimChar, lpszFilePaths, lpszFileNames, ulReserved);
}
ULONG FAR PASCAL
MAPIFindNext(LHANDLE lhSession,
ULONG_PTR ulUIParam,
LPSTR lpszMessageType,
LPSTR lpszSeedMessageID,
FLAGS flFlags,
ULONG ulReserved,
LPSTR lpszMessageID) {
return m_MAPIFindNext(lhSession, ulUIParam, lpszMessageType, lpszSeedMessageID, flFlags, ulReserved, lpszMessageID);
}
ULONG FAR PASCAL
MAPIReadMail(LHANDLE lhSession,
ULONG_PTR ulUIParam,
LPSTR lpszMessageID,
FLAGS flFlags,
ULONG ulReserved,
lpMapiMessage FAR *lppMessage) {
return m_MAPIReadMail(lhSession, ulUIParam, lpszMessageID, flFlags, ulReserved, lppMessage);
}
ULONG FAR PASCAL
MAPISaveMail(LHANDLE lhSession,
ULONG_PTR ulUIParam,
lpMapiMessage lpMessage,
FLAGS flFlags,
ULONG ulReserved,
LPSTR lpszMessageID) {
return m_MAPISaveMail(lhSession, ulUIParam, lpMessage, flFlags, ulReserved, lpszMessageID);
}
ULONG FAR PASCAL
MAPIDeleteMail(LHANDLE lhSession,
ULONG_PTR ulUIParam,
LPSTR lpszMessageID,
FLAGS flFlags,
ULONG ulReserved) {
return m_MAPIDeleteMail(lhSession, ulUIParam, lpszMessageID, flFlags, ulReserved);
}
ULONG FAR PASCAL
MAPIFreeBuffer(LPVOID pv) {
return m_MAPIFreeBuffer(pv);
}
ULONG FAR PASCAL
MAPIAddress(LHANDLE lhSession,
ULONG_PTR ulUIParam,
LPSTR lpszCaption,
ULONG nEditFields,
LPSTR lpszLabels,
ULONG nRecips,
lpMapiRecipDesc lpRecips,
FLAGS flFlags,
ULONG ulReserved,
LPULONG lpnNewRecips,
lpMapiRecipDesc FAR *lppNewRecips) {
return m_MAPIAddress(lhSession, ulUIParam, lpszCaption, nEditFields, lpszLabels, nRecips, lpRecips, flFlags, ulReserved, lpnNewRecips, lppNewRecips);
}
ULONG FAR PASCAL
MAPIDetails(LHANDLE lhSession,
ULONG_PTR ulUIParam,
lpMapiRecipDesc lpRecip,
FLAGS flFlags,
ULONG ulReserved) {
return m_MAPIDetails(lhSession, ulUIParam, lpRecip, flFlags, ulReserved);
}
ULONG FAR PASCAL
MAPIResolveName(LHANDLE lhSession,
ULONG_PTR ulUIParam,
LPSTR lpszName,
FLAGS flFlags,
ULONG ulReserved,
lpMapiRecipDesc FAR *lppRecip) {
return m_MAPIResolveName(lhSession, ulUIParam, lpszName, flFlags, ulReserved, lppRecip);
}
| [
"[email protected]"
]
| [
[
[
1,
212
]
]
]
|
aaf65c0bc999bacf5f3a1c86dd384b7703e840a1 | 854ee643a4e4d0b7a202fce237ee76b6930315ec | /arcemu_svn/src/sun/src/SpellHandlers/WarlockSpells.cpp | bebd2d2c9f57b2b2b8f73c9cbc001a3e9485e16a | []
| no_license | miklasiak/projekt | df37fa82cf2d4a91c2073f41609bec8b2f23cf66 | 064402da950555bf88609e98b7256d4dc0af248a | refs/heads/master | 2021-01-01T19:29:49.778109 | 2008-11-10T17:14:14 | 2008-11-10T17:14:14 | 34,016,391 | 2 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 900 | cpp | /****************************************************************************
*
* SpellHandler Plugin
* Copyright (c) 2007 Team Ascent
*
* This work is licensed under the Creative Commons Attribution-NonCommercial-ShareAlike 3.0
* License. To view a copy of this license, visit
* http://creativecommons.org/licenses/by-nc-sa/3.0/ or send a letter to Creative Commons,
* 543 Howard Street, 5th Floor, San Francisco, California, 94105, USA.
*
* EXCEPT TO THE EXTENT REQUIRED BY APPLICABLE LAW, IN NO EVENT WILL LICENSOR BE LIABLE TO YOU
* ON ANY LEGAL THEORY FOR ANY SPECIAL, INCIDENTAL, CONSEQUENTIAL, PUNITIVE OR EXEMPLARY DAMAGES
* ARISING OUT OF THIS LICENSE OR THE USE OF THE WORK, EVEN IF LICENSOR HAS BEEN ADVISED OF THE
* POSSIBILITY OF SUCH DAMAGES.
*
*/
#include "StdAfx.h"
#include "Setup.h"
void SetupWarlockSpells(ScriptMgr * mgr)
{
// moo?
}
| [
"[email protected]@3074cc92-8d2b-11dd-8ab4-67102e0efeef",
"[email protected]@3074cc92-8d2b-11dd-8ab4-67102e0efeef"
]
| [
[
[
1,
22
],
[
24,
25
]
],
[
[
23,
23
],
[
26,
26
]
]
]
|
83c8638a2e9cc9e0cee1129262fb1cc7efd6c057 | e9944cc3f8c362cd0314a2d7a01291ed21de19ee | / xcommon/btnexgenipl/examples/Streams/BTCOFStream.cpp | e5920af389246c08f0d771114c376cc897c5d4a2 | []
| no_license | wermanhme1990/xcommon | 49d7185a28316d46992ad9311ae9cdfe220cb586 | c9b1567da1f11e7a606c6ed638a9fde1f6ece577 | refs/heads/master | 2016-09-06T12:43:43.593776 | 2008-12-05T04:24:11 | 2008-12-05T04:24:11 | 39,864,906 | 2 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,245 | cpp | #include "stdafx.h"
#include "BTCOFStream.h"
BTCOFStream::BTCOFStream()
{
}
BTCOFStream::~BTCOFStream()
{
(void)Close();
}
bool BTCOFStream::Open(LPCTSTR lpszFileName /* = NULL */)
{
if(!lpszFileName)
return false;
// Try to open/create a file for output.
return m_File.Open( lpszFileName, CFile::modeCreate | CFile::modeWrite);
}
int BTCOFStream::Close()
{
if( IsOpen())
m_File.Close();
return 0;
}
long BTCOFStream::Write(const void* pData, long lCount)
{
if(!IsOpen())
return -1;
m_File.Write( pData, lCount);
return lCount; // Normally we will return number of written bytes, but CFile did
// not return any value, so we have to return lCount. You can catch
// CFileException to process error messages.
// Read BTCIOStream.h for more details.
}
long BTCOFStream::Seek(long lOffset, unsigned int nOrigin)
{
if(!IsOpen())
return -1;
switch( nOrigin)
{
case Begin: nOrigin = CFile::begin;
break;
case Current: nOrigin = CFile::current;
break;
case End: nOrigin = CFile::end;
break;
}
return m_File.Seek( lOffset, nOrigin);
}
bool BTCOFStream::IsOpen()
{
return m_File.m_hFile != CFile::hFileNull;
}
| [
"[email protected]"
]
| [
[
[
1,
66
]
]
]
|
f2745039c612fa5f6d6acaa2b7a916af890e4bf5 | bfdfb7c406c318c877b7cbc43bc2dfd925185e50 | /compiler/hyCOperand.h | e5979ca8b47062bcdaa88c6ee898dda55cec1a9b | [
"MIT"
]
| permissive | ysei/Hayat | 74cc1e281ae6772b2a05bbeccfcf430215cb435b | b32ed82a1c6222ef7f4bf0fc9dedfad81280c2c0 | refs/heads/master | 2020-12-11T09:07:35.606061 | 2011-08-01T12:38:39 | 2011-08-01T12:38:39 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 3,426 | h | /* -*- coding: sjis-dos; -*- */
/*
* copyright 2010 FUKUZAWA Tadashi. All rights reserved.
*/
#ifndef m_HYCOPERAND_H_
#define m_HYCOPERAND_H_
#include "hySymbolID.h"
#include "hyCBytecode.h"
namespace Hayat {
namespace Compiler {
#define DEF_OPERAND(opr,inittype) \
class OPR_##opr { \
protected: \
inittype val; \
public: \
typedef inittype BaseType_t; \
OPR_##opr(inittype v) { val = v; } \
void addCodeTo(Bytecode& b); \
static const size_t SIZE = sizeof(inittype); \
};
DEF_OPERAND(INT, hys32);
inline void OPR_INT::addCodeTo(Bytecode& b) { b.addCode<hys32>(val); }
DEF_OPERAND(INT8, hys8);
inline void OPR_INT8::addCodeTo(Bytecode& b) { b.addCode<hys8>(val); }
DEF_OPERAND(FLOAT, hyf32);
inline void OPR_FLOAT::addCodeTo(Bytecode& b) { b.addCode<hyf32>(val); }
DEF_OPERAND(UINT8, hyu8);
inline void OPR_UINT8::addCodeTo(Bytecode& b) { b.addCode<hyu8>(val); }
DEF_OPERAND(UINT16, hyu16);
inline void OPR_UINT16::addCodeTo(Bytecode& b) { b.addCode<hyu16>(val); }
DEF_OPERAND(UINT32, hyu32);
inline void OPR_UINT32::addCodeTo(Bytecode& b) { b.addCode<hyu32>(val); }
DEF_OPERAND(STRCONST, hyu32);
inline void OPR_STRCONST::addCodeTo(Bytecode& b) { b.addCode<hyu32>(val); }
DEF_OPERAND(SYMBOL, SymbolID_t);
inline void OPR_SYMBOL::addCodeTo(Bytecode& b) { b.addCode<SymbolID_t>(val); }
DEF_OPERAND(METHOD, SymbolID_t);
inline void OPR_METHOD::addCodeTo(Bytecode& b) { b.addCode<SymbolID_t>(val); }
DEF_OPERAND(CLASS, SymbolID_t);
inline void OPR_CLASS::addCodeTo(Bytecode& b) { b.addCode<SymbolID_t>(val); }
DEF_OPERAND(LOCALVAR, hys16);
inline void OPR_LOCALVAR::addCodeTo(Bytecode& b) { b.addCode<hys16>(val); }
DEF_OPERAND(MAYLOCALVAR, hys16);
inline void OPR_MAYLOCALVAR::addCodeTo(Bytecode& b) { b.addCode<hys16>(val); }
DEF_OPERAND(MEMBVAR, SymbolID_t);
inline void OPR_MEMBVAR::addCodeTo(Bytecode& b) { b.addCode<SymbolID_t>(val); }
DEF_OPERAND(CLASSVAR, SymbolID_t);
inline void OPR_CLASSVAR::addCodeTo(Bytecode& b) { b.addCode<SymbolID_t>(val); }
DEF_OPERAND(GLOBALVAR, SymbolID_t);
inline void OPR_GLOBALVAR::addCodeTo(Bytecode& b) { b.addCode<SymbolID_t>(val); }
DEF_OPERAND(CONSTVAR, SymbolID_t);
inline void OPR_CONSTVAR::addCodeTo(Bytecode& b) { b.addCode<SymbolID_t>(val); }
DEF_OPERAND(RELATIVE, hys32);
inline void OPR_RELATIVE::addCodeTo(Bytecode& b) { b.addCode<hys32>(val); }
DEF_OPERAND(JUMPSYMBOL, SymbolID_t);
inline void OPR_JUMPSYMBOL::addCodeTo(Bytecode& b) {
b.addCode<SymbolID_t>(val);
#ifdef SYMBOL_ID_IS_HYU16
b.addCode<hys16>(0);
#endif
}
DEF_OPERAND(SCOPE, TArray<SymbolID_t>*);
// OPR_SCOPE::addCodeTo() is not inline
DEF_OPERAND(SIGNATURE, hyu16);
inline void OPR_SIGNATURE::addCodeTo(Bytecode& b) { b.addCode<hyu16>(val); }
#undef DEF_OPERAND
}
}
#endif /* m_HYCOPERAND_H_ */
| [
"[email protected]"
]
| [
[
[
1,
98
]
]
]
|
6db62325d38b597a7ad5a7f2f684b79f4a2cecdb | ef23e388061a637f82b815d32f7af8cb60c5bb1f | /src/mame/includes/mystwarr.h | e4254ebbfde67e00f0d3c16065c24df3968d78c6 | []
| no_license | marcellodash/psmame | 76fd877a210d50d34f23e50d338e65a17deff066 | 09f52313bd3b06311b910ed67a0e7c70c2dd2535 | refs/heads/master | 2021-05-29T23:57:23.333706 | 2011-06-23T20:11:22 | 2011-06-23T20:11:22 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,164 | h | class mystwarr_state : public driver_device
{
public:
mystwarr_state(running_machine &machine, const driver_device_config_base &config)
: driver_device(machine, config) { }
UINT16 *m_gx_workram;
UINT8 m_mw_irq_control;
int m_cur_sound_region;
int m_layer_colorbase[6];
int m_oinprion;
int m_cbparam;
int m_sprite_colorbase;
int m_sub1_colorbase;
int m_last_psac_colorbase;
int m_gametype;
int m_roz_enable;
int m_roz_rombank;
tilemap_t *m_ult_936_tilemap;
UINT16 m_clip;
UINT16 *m_spriteram;
};
/*----------- defined in video/mystwarr.c -----------*/
VIDEO_START( gaiapols );
VIDEO_START( dadandrn );
VIDEO_START( viostorm );
VIDEO_START( metamrph );
VIDEO_START( martchmp );
VIDEO_START( mystwarr );
SCREEN_UPDATE( dadandrn );
SCREEN_UPDATE( mystwarr );
SCREEN_UPDATE( metamrph );
SCREEN_UPDATE( martchmp );
WRITE16_HANDLER( ddd_053936_enable_w );
WRITE16_HANDLER( ddd_053936_clip_w );
READ16_HANDLER( gai_053936_tilerom_0_r );
READ16_HANDLER( ddd_053936_tilerom_0_r );
READ16_HANDLER( ddd_053936_tilerom_1_r );
READ16_HANDLER( gai_053936_tilerom_2_r );
READ16_HANDLER( ddd_053936_tilerom_2_r );
| [
"Mike@localhost"
]
| [
[
[
1,
44
]
]
]
|
f2de31e5f6a90abb7870102f93314cb07dd2615c | 5f0b8d4a0817a46a9ae18a057a62c2442c0eb17e | /Include/component/MenuBar.cpp | 177c16813a6323bfbd172cbe7f389ffe18712275 | [
"BSD-3-Clause"
]
| permissive | gui-works/ui | 3327cfef7b9bbb596f2202b81f3fc9a32d5cbe2b | 023faf07ff7f11aa7d35c7849b669d18f8911cc6 | refs/heads/master | 2020-07-18T00:46:37.172575 | 2009-11-18T22:05:25 | 2009-11-18T22:05:25 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 5,153 | cpp | /*
* Copyright (c) 2003-2006, Bram Stein
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
*
* 1. Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* 2. Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
* 3. The name of the author may not be used to endorse or promote products
* derived from this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE AUTHOR "AS IS" AND ANY EXPRESS OR IMPLIED
* WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF
* MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO
* EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT,
* INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,
* BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
* DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY
* OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
* NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE,
* EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
#include "./MenuBar.h"
#include "../FocusManager.h"
#include "../event/PropertyEvent.h"
namespace ui
{
MenuBar::MenuBar(void)
: selected(false),
selectedMenu(0),
layout(Component::LEFT,0,0)
{
setThemeName("MenuBar");
setLayout(&layout);
}
void MenuBar::add(Menu* menu)
{
menu->addMouseListener(this);
menu->addFocusListener(this);
menu->addObserver(this);
addImpl(menu,-1);
}
void MenuBar::remove(Menu *menu)
{
menu->removeMouseListener(this);
menu->removeFocusListener(this);
menu->removeObserver(this);
removeImpl(menu);
}
bool MenuBar::isSelected()
{
return selected;
}
void MenuBar::selectMenu(Menu *menu)
{
event::PropertyEvent selectedEvent(menu,event::PropertyEvent::SPECIAL,Menu::SELECTED);
menu->processPropertyEvent(selectedEvent);
menu->setPopupMenuVisible(true);
}
void MenuBar::deselectMenu(Menu *menu)
{
//if(menu->isSelected())
//{
event::PropertyEvent deselectedEvent(menu,event::PropertyEvent::SPECIAL,Menu::DESELECTED);
menu->processPropertyEvent(deselectedEvent);
menu->setPopupMenuVisible(false);
//}
}
void MenuBar::mouseEntered(const event::MouseEvent &e)
{
if(isSelected())
{
if(e.getSource() != selectedMenu)
{
// find the new selectedMenu
ComponentList::const_iterator iter;
ComponentList list = getChildren();
for(iter = list.begin(); iter != list.end(); ++iter)
{
Menu* menu = static_cast<Menu*>((*iter));
if(e.getSource() == menu)
{
selectMenu(menu);
selectedMenu = menu;
selected = true;
FocusManager::getInstance().setPermanentFocusOwner(selectedMenu);
}
else
{
deselectMenu(menu);
}
}
}
}
}
void MenuBar::mousePressed(const event::MouseEvent &e)
{
ComponentList::const_iterator iter;
ComponentList list = getChildren();
for(iter = list.begin(); iter != list.end(); ++iter)
{
Menu* menu = static_cast<Menu*>((*iter));
if(e.getSource() == menu)
{
if(menu != selectedMenu)
{
selectMenu(menu);
selectedMenu = menu;
selected = true;
}
else
{
deselectMenu(menu);
selectedMenu = 0;
selected = false;
}
}
else
{
deselectMenu(menu);
}
}
}
void MenuBar::focusGained(const event::FocusEvent &e)
{
if(selectedMenu != e.getSource())
{
if(selectedMenu != 0)
{
deselectMenu(selectedMenu);
}
selectedMenu = static_cast<Menu *>(e.getSource());
selectMenu(selectedMenu);
selected = true;
}
}
void MenuBar::update(util::Observable *subject)
{
selectedMenu = 0;
selected = false;
ComponentList::iterator iter;
ComponentList list = getChildren();
for(iter = list.begin(); iter != list.end(); ++iter)
{
Menu* menu = static_cast<Menu*>((*iter));
deselectMenu(menu);
}
}
void MenuBar::focusLost(const event::FocusEvent &e)
{
bool found = false;
ComponentList::iterator iter;
ComponentList list = getChildren();
for(iter = list.begin(); iter != list.end(); ++iter)
{
Menu* menu = static_cast<Menu*>((*iter));
ComponentList::const_iterator f = std::find(menu->getPopupMenu().getChildren().begin(),menu->getPopupMenu().getChildren().end(),e.getOppositeComponent());
if(f != menu->getPopupMenu().getChildren().end())
{
found = true;
}
else
{
deselectMenu(menu);
}
}
if(!found)
{
selectedMenu = 0;
selected = false;
}
}
} | [
"bs@bram.(none)"
]
| [
[
[
1,
199
]
]
]
|
6f196ad8871c1e954d1b3129d0bf6e5a2dad4875 | c7dcd4b321428c91074d6802b8a655a40fbb283b | /ObjectDetection/ObjectDetection/stdafx.h | 7e16bdf1e21515230ad4d50c30b1c67ac7fd874e | []
| no_license | buubui/imgdetection | 7c12576ef6ddc06d788183f4261bc070e13ee2fb | feeb9b5233c2a0bd35b60bf7792bd05005cc0409 | refs/heads/master | 2016-09-05T11:45:33.588669 | 2011-04-27T16:08:34 | 2011-04-27T16:08:34 | 32,272,304 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 838 | h | // stdafx.h : include file for standard system include files,
// or project specific include files that are used frequently, but
// are changed infrequently
//
#pragma once
#define M_PI 3.141592654
#define M_e 0.01
#include "cxcore.h"
#include "cxtypes.h"
#include "cv.h"
#include "time.h"
#include "highgui.h"
#include "cvaux.h"
#include <math.h>
#include <iostream>
#include <fstream>
using namespace std;
using namespace cv;
using namespace System;
using namespace System::Collections;
#include "loadConfigs.h"
#include "multiscaleDetectRect.h"
#include "imFilter.h"
#include "HOG.h"
#include "svmData.h"
#include <boost/algorithm/string.hpp>
#include <boost/algorithm/string/replace.hpp>
#include "detection.h"
#include "meanshift.h"
#include <msclr\marshal_cppstd.h>
#include "myPCA.h"
//abc
| [
"bhlbuu@b6243d83-3e35-bad2-eac4-1d342526e9e5",
"[email protected]@b6243d83-3e35-bad2-eac4-1d342526e9e5"
]
| [
[
[
1,
32
],
[
34,
36
]
],
[
[
33,
33
]
]
]
|
36d05a28a45e7625cca5a01cc54ef50ef01a6af1 | 7d4c5390d7108be0c1987881ab0e9e27968a6f38 | /Others/Sample animator/egAnimatables.cpp | 91e6697571276cbb041723cbf4d2214722a7420d | []
| no_license | aout/SAGE | 257c5ef2e3583b554c0d3e7099bf86800918dec5 | 5117ea6234e585f0e452290e89ab6ac4161d9391 | refs/heads/master | 2016-09-06T02:53:10.794585 | 2011-01-21T17:08:23 | 2011-01-21T17:08:23 | 33,314,008 | 2 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 9,036 | cpp | // *************************************************************************************************
//
// Horde3D
// Next-Generation Graphics Engine
// --------------------------------------
// Copyright (C) 2006-2009 Nicolas Schulz
//
// This software is distributed under the terms of the Eclipse Public License v1.0.
// A copy of the license may be obtained at: http://www.eclipse.org/legal/epl-v10.html
//
// *************************************************************************************************
#include "egModel.h"
#include "egMaterial.h"
#include "egModules.h"
#include "utDebug.h"
using namespace std;
// *************************************************************************************************
// Class MeshNode
// *************************************************************************************************
MeshNode::MeshNode( const MeshNodeTpl &meshTpl ) :
SceneNode( meshTpl ), _parentModel( 0x0 ), _ignoreAnim( false ),
_materialRes( meshTpl.matRes ), _batchStart( meshTpl.batchStart ), _batchCount( meshTpl.batchCount ),
_vertRStart( meshTpl.vertRStart ), _vertREnd( meshTpl.vertREnd ), _lodLevel( meshTpl.lodLevel )
{
}
SceneNodeTpl *MeshNode::parsingFunc( map< string, string > &attribs )
{
bool result = true;
map< string, string >::iterator itr;
MeshNodeTpl *meshTpl = new MeshNodeTpl( "", 0x0, 0, 0, 0, 0 );
itr = attribs.find( "material" );
if( itr != attribs.end() )
{
uint32 res = Modules::resMan().addResource( ResourceTypes::Material, itr->second, 0, false );
if( res != 0 )
meshTpl->matRes = (MaterialResource *)Modules::resMan().resolveResHandle( res );
}
else result = false;
itr = attribs.find( "batchStart" );
if( itr != attribs.end() ) meshTpl->batchStart = atoi( itr->second.c_str() );
else result = false;
itr = attribs.find( "batchCount" );
if( itr != attribs.end() ) meshTpl->batchCount = atoi( itr->second.c_str() );
else result = false;
itr = attribs.find( "vertRStart" );
if( itr != attribs.end() ) meshTpl->vertRStart = atoi( itr->second.c_str() );
else result = false;
itr = attribs.find( "vertREnd" );
if( itr != attribs.end() ) meshTpl->vertREnd = atoi( itr->second.c_str() );
else result = false;
itr = attribs.find( "lodLevel" );
if( itr != attribs.end() ) meshTpl->lodLevel = atoi( itr->second.c_str() );
if( !result )
{
delete meshTpl; meshTpl = 0x0;
}
return meshTpl;
}
SceneNode *MeshNode::factoryFunc( const SceneNodeTpl &nodeTpl )
{
if( nodeTpl.type != SceneNodeTypes::Mesh ) return 0x0;
return new MeshNode( *(MeshNodeTpl *)&nodeTpl );
}
IAnimatableNode *MeshNode::getANParent()
{
switch( _parent->getType() )
{
case SceneNodeTypes::Joint:
return (IAnimatableNode *)((JointNode *)_parent);
case SceneNodeTypes::Mesh:
return (IAnimatableNode *)((MeshNode *)_parent);
default:
return 0x0;
}
}
bool MeshNode::canAttach( SceneNode &parent )
{
// Important: Meshes may not live outside of models
return (parent.getType() == SceneNodeTypes::Model) ||
(parent.getType() == SceneNodeTypes::Mesh) ||
(parent.getType() == SceneNodeTypes::Joint);
}
int MeshNode::getParamI( int param )
{
switch( param )
{
case MeshNodeParams::MatResI:
if( _materialRes != 0x0 ) return _materialRes->getHandle();
else return 0;
case MeshNodeParams::BatchStartI:
return _batchStart;
case MeshNodeParams::BatchCountI:
return _batchCount;
case MeshNodeParams::VertRStartI:
return _vertRStart;
case MeshNodeParams::VertREndI:
return _vertREnd;
case MeshNodeParams::LodLevelI:
return _lodLevel;
}
return SceneNode::getParamI( param );
}
void MeshNode::setParamI( int param, int value )
{
Resource *res;
switch( param )
{
case MeshNodeParams::MatResI:
res = Modules::resMan().resolveResHandle( value );
if( res != 0x0 && res->getType() == ResourceTypes::Material )
_materialRes = (MaterialResource *)res;
else
Modules::setError( "Invalid handle in h3dSetNodeParamI for H3DMesh::MatResI" );
return;
case MeshNodeParams::LodLevelI:
_lodLevel = value;
return;
}
SceneNode::setParamI( param, value );
}
bool MeshNode::checkIntersection( const Vec3f &rayOrig, const Vec3f &rayDir, Vec3f &intsPos ) const
{
// Collision check is only done for base LOD
if( _lodLevel != 0 ) return false;
if( !rayAABBIntersection( rayOrig, rayDir, _bBox.min, _bBox.max ) ) return false;
GeometryResource *geoRes = _parentModel->getGeometryResource();
if( geoRes == 0x0 || geoRes->getIndexData() == 0x0 || geoRes->getVertPosData() == 0x0 ) return false;
// Transform ray to local space
Matrix4f m = _absTrans.inverted();
Vec3f orig = m * rayOrig;
Vec3f dir = m * (rayOrig + rayDir) - orig;
Vec3f nearestIntsPos = Vec3f( Math::MaxFloat, Math::MaxFloat, Math::MaxFloat );
bool intersection = false;
// Check triangles
for( uint32 i = _batchStart; i < _batchStart + _batchCount; i += 3 )
{
Vec3f *vert0, *vert1, *vert2;
if( geoRes->_16BitIndices )
{
vert0 = &geoRes->getVertPosData()[((uint16 *)geoRes->_indexData)[i + 0]];
vert1 = &geoRes->getVertPosData()[((uint16 *)geoRes->_indexData)[i + 1]];
vert2 = &geoRes->getVertPosData()[((uint16 *)geoRes->_indexData)[i + 2]];
}
else
{
vert0 = &geoRes->getVertPosData()[((uint32 *)geoRes->_indexData)[i + 0]];
vert1 = &geoRes->getVertPosData()[((uint32 *)geoRes->_indexData)[i + 1]];
vert2 = &geoRes->getVertPosData()[((uint32 *)geoRes->_indexData)[i + 2]];
}
if( rayTriangleIntersection( orig, dir, *vert0, *vert1, *vert2, intsPos ) )
{
intersection = true;
if( (intsPos - orig).length() < (nearestIntsPos - orig).length() )
nearestIntsPos = intsPos;
}
}
intsPos = _absTrans * nearestIntsPos;
return intersection;
}
void MeshNode::onAttach( SceneNode &parentNode )
{
// Find parent model node
SceneNode *node = &parentNode;
while( node->getType() != SceneNodeTypes::Model ) node = node->getParent();
_parentModel = (ModelNode *)node;
_parentModel->markNodeListDirty();
}
void MeshNode::onDetach( SceneNode &/*parentNode*/ )
{
if( _parentModel != 0x0 ) _parentModel->markNodeListDirty();
}
void MeshNode::onPostUpdate()
{
_bBox = _localBBox;
_bBox.transform( _absTrans );
}
// *************************************************************************************************
// Class JointNode
// *************************************************************************************************
JointNode::JointNode( const JointNodeTpl &jointTpl ) :
SceneNode( jointTpl ), _jointIndex( jointTpl.jointIndex ), _parentModel( 0x0 ), _ignoreAnim( false )
{
}
SceneNodeTpl *JointNode::parsingFunc( map< string, string > &attribs )
{
bool result = true;
map< string, string >::iterator itr;
JointNodeTpl *jointTpl = new JointNodeTpl( "", 0 );
itr = attribs.find( "jointIndex" );
if( itr != attribs.end() ) jointTpl->jointIndex = atoi( itr->second.c_str() );
else result = false;
if( !result )
{
delete jointTpl; jointTpl = 0x0;
}
return jointTpl;
}
SceneNode *JointNode::factoryFunc( const SceneNodeTpl &nodeTpl )
{
if( nodeTpl.type != SceneNodeTypes::Joint ) return 0x0;
return new JointNode( *(JointNodeTpl *)&nodeTpl );
}
IAnimatableNode *JointNode::getANParent()
{
switch( _parent->getType() )
{
case SceneNodeTypes::Joint:
return (IAnimatableNode *)((JointNode *)_parent);
case SceneNodeTypes::Mesh:
return (IAnimatableNode *)((MeshNode *)_parent);
default:
return 0x0;
}
}
bool JointNode::canAttach( SceneNode &parent )
{
// Important: Joints may not live outside of models
return (parent.getType() == SceneNodeTypes::Model) ||
(parent.getType() == SceneNodeTypes::Joint);
}
int JointNode::getParamI( int param )
{
switch( param )
{
case JointNodeParams::JointIndexI:
return (int)_jointIndex;
}
return SceneNode::getParamI( param );
}
void JointNode::onPostUpdate()
{
if( _parentModel->getGeometryResource() == 0x0 ) return;
if( _parent->getType() != SceneNodeTypes::Joint )
_relModelMat = _relTrans;
else
Matrix4f::fastMult43( _relModelMat, ((JointNode *)_parent)->_relModelMat, _relTrans );
if( _parentModel->jointExists( _jointIndex ) )
{
Matrix4f mat( Math::NO_INIT );
Matrix4f::fastMult43( mat, _relModelMat, _parentModel->getGeometryResource()->getInvBindMat( _jointIndex ) );
_parentModel->setSkinningMat( _jointIndex, mat );
}
}
void JointNode::onAttach( SceneNode &parentNode )
{
// Find parent model node
SceneNode *node = &parentNode;
while( node->getType() != SceneNodeTypes::Model ) node = node->getParent();
_parentModel = (ModelNode *)node;
_parentModel->markNodeListDirty();
}
void JointNode::onDetach( SceneNode &/*parentNode*/ )
{
if( _parentModel != 0x0 ) _parentModel->markNodeListDirty();
}
| [
"[email protected]@3dace960-eeb1-8b87-8c5b-9022fc2c5b97"
]
| [
[
[
1,
327
]
]
]
|
7e505dc94d6d7f68e9a35751198966bea467be18 | 4f913cc1a50e8e649fd40313631a161234e3c59d | /NokomoSystem/NokomoSystem.h | f9985e9b7ccceb75e9ebeefbfe23b6175c1a7e2a | []
| no_license | autch/kpiadx.kpi | abb1f084163478796e202196a7411a049a76116c | f482c3871d948e71a3b3839e9066f845ecdb5915 | refs/heads/master | 2021-12-16T01:22:32.824315 | 2010-12-15T06:34:48 | 2010-12-15T06:34:48 | 1,170,398 | 1 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,224 | h |
#pragma once
/************************************************************************
* NokomoSystem.h -- NokomoSystem basic services / system services
*
* Copyright(c) 2004, Autch.net. All rights reserved.
*
************************************************************************/
// vital Win32 SDK
#include <windows.h>
// Standard C++ libraries
// STL
#include <set>
#include <string>
#include <stack>
#include <vector>
#include <algorithm>
#include <functional>
// C++ libs.
#include <iostream>
namespace Nokomo
{
// NokomoSystem global declarations
using namespace std;
typedef unsigned __int64 QWORD, *PQWORD;
};
//// NokomoSystem basic / system services ////////////////////////////////
// exceptions
#include "Exceptions.h"
// basic arithmetic functions / classes
#include "BasicArithmetics.h"
// synchronization objects
#include "SyncObjects.h"
// unit conversion objects
#include "UnitConversions.h"
// add-on for Standard Template Libraries
#include "StlExtensions.h"
// streamer interface
#include "Stream.h"
// file drivers
#include "FileDrivers.h"
//////////////////////////////////////////////////////////////////////////
| [
"autch@f88602a7-bc0e-0410-bfba-c07ee007e53c"
]
| [
[
[
1,
55
]
]
]
|
7b108b4e5910382cf2ebc756363aea13fd9069d9 | f177993b13e97f9fecfc0e751602153824dfef7e | /ImProSln/OSCSender/OSCSender.h | fa3fe1ff421b6b2b5c819da1000a085f2d963b25 | []
| no_license | svn2github/imtophooksln | 7bd7412947d6368ce394810f479ebab1557ef356 | bacd7f29002135806d0f5047ae47cbad4c03f90e | refs/heads/master | 2020-05-20T04:00:56.564124 | 2010-09-24T09:10:51 | 2010-09-24T09:10:51 | 11,787,598 | 1 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,522 | h | // The following ifdef block is the standard way of creating macros which make exporting
// from a DLL simpler. All files within this DLL are compiled with the OSCSENDER_EXPORTS
// symbol defined on the command line. this symbol should not be defined on any project
// that uses this DLL. This way any other project whose source files include this file see
// OSCSENDER_API functions as being imported from a DLL, whereas this DLL sees symbols
// defined with this macro as being exported.
#ifdef OSCSENDER_EXPORTS
#define OSCSENDER_API __declspec(dllexport)
#else
#define OSCSENDER_API __declspec(dllimport)
#endif
#pragma once
#include "ITouchListener.h"
#include "osc/OscOutboundPacketStream.h"
#include "ip/UdpSocket.h"
#include <string>
#include <map>
using namespace touchlib;
using namespace std;
class OSCSENDER_API OSCSender : public ITouchListener
{
public:
static int m_ref;
static OSCSender* GetOSCSender();
HRESULT AddRef();
HRESULT Release();
void connectSocket(char* ip_address, int port);
void disConnectSocket();
bool isConnected();
void fingerDown(TouchData data);
void fingerUpdate(TouchData data);
void fingerUp(TouchData data);
void frame();
void clearFingers();
void sendHighResBoundingBox(int id, float rect[4], float orgPt[4][2]);
public:
char m_ipAddress[MAX_PATH];
int m_port;
protected:
OSCSender(void);
virtual ~OSCSender(void);
UdpTransmitSocket* m_transmitSocket;
map<int, TouchData> m_fingerList;
int m_frameSeq;
};
| [
"ndhumuscle@fa729b96-8d43-11de-b54f-137c5e29c83a"
]
| [
[
[
1,
49
]
]
]
|
80ce24a6b67b4a449f657dab869de29404be170f | c436a5d7cdbebc04e5d202c6bb3c83448a5db529 | /EngineTest/source/Globals.cpp | 69a48cd46c7d3569ac3c98b39105b126188fc23e | [
"Zlib"
]
| permissive | pvdk/QtOgreFramework | 89132be5c0ea4f11a43abf4632577ebb21a0b10a | e32bafae2b0c1a8af9700efea61ff351866bb1d5 | refs/heads/master | 2021-01-23T08:15:38.575879 | 2010-11-15T21:39:06 | 2010-11-15T21:39:06 | 1,680,419 | 0 | 1 | null | null | null | null | UTF-8 | C++ | false | false | 502 | cpp | #include "Globals.h"
Globals::Globals(QObject* parent)
:QObject(parent)
{
}
quint32 Globals::getCurrentFrameTime(void) const
{
return m_uCurrentFrameTime;
}
void Globals::setCurrentFrameTime(const quint32 uCurrentFrameTime)
{
m_uCurrentFrameTime = uCurrentFrameTime;
}
quint32 Globals::getPreviousFrameTime(void) const
{
return m_uPreviousFrameTime;
}
void Globals::setPreviousFrameTime(const quint32 uPreviousFrameTime)
{
m_uPreviousFrameTime = uPreviousFrameTime;
} | [
"esuvs@2eb06014-c84b-0410-ad17-af83cdd4cbf1"
]
| [
[
[
1,
26
]
]
]
|
5d35ec1699acc030d0f332b82030493cd77eb49e | 2e5fd1fc05c0d3b28f64abc99f358145c3ddd658 | /deps/quickfix/src/C++/FieldTypes.cpp | 18e1db4c24e90ab07896306dae9497a5b9ffd080 | [
"BSD-2-Clause"
]
| permissive | indraj/fixfeed | 9365c51e2b622eaff4ce5fac5b86bea86415c1e4 | 5ea71aab502c459da61862eaea2b78859b0c3ab3 | refs/heads/master | 2020-12-25T10:41:39.427032 | 2011-02-15T13:38:34 | 2011-02-15T20:50:08 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,716 | cpp | /****************************************************************************
** Copyright (c) quickfixengine.org All rights reserved.
**
** This file is part of the QuickFIX FIX Engine
**
** This file may be distributed under the terms of the quickfixengine.org
** license as defined by quickfixengine.org and appearing in the file
** LICENSE included in the packaging of this file.
**
** This file is provided AS IS with NO WARRANTY OF ANY KIND, INCLUDING THE
** WARRANTY OF DESIGN, MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE.
**
** See http://www.quickfixengine.org/LICENSE for licensing information.
**
** Contact [email protected] if any conditions of this licensing are
** not clear to you.
**
****************************************************************************/
#ifdef _MSC_VER
#include "stdafx.h"
#else
#include "config.h"
#endif
#include "CallStack.h"
#include "FieldTypes.h"
#ifdef HAVE_FTIME
# include <sys/timeb.h>
#endif
namespace FIX {
DateTime DateTime::nowUtc()
{
#if defined( HAVE_FTIME )
timeb tb;
ftime (&tb);
return fromUtcTimeT (tb.time, tb.millitm);
#elif defined( _POSIX_SOURCE )
struct timeval tv;
gettimeofday (&tv, 0);
return fromUtcTimeT( tv.tv_sec, tv.tv_usec / 1000 );
#else
return fromUtcTimeT( ::time (0), 0 );
#endif
}
DateTime DateTime::nowLocal()
{
#if defined( HAVE_FTIME )
timeb tb;
ftime (&tb);
return fromLocalTimeT( tb.time, tb.millitm );
#elif defined( _POSIX_SOURCE )
struct timeval tv;
gettimeofday (&tv, 0);
return fromLocalTimeT( tv.tv_sec, tv.tv_usec / 1000 );
#else
return fromLocalTimeT( ::time (0), 0 );
#endif
}
}
| [
"[email protected]"
]
| [
[
[
1,
65
]
]
]
|
5bc7a4d79b262c183f26f20dca797c58da1fb9d2 | 7575692fd3800ec48e7c941cdd40210d02ca96d0 | /advanced-cpp-pa6/advanced-cpp-pa6/SonyVCRPlayer.h | 79d6e3b4528830a01da9d44c152d12c2030e863d | []
| no_license | husamMaruf/advanced-programming-2011 | bf577a8cc51d53599ed032c22ae31fc15db217fb | db285ae560495bd051400f0e372a2eec2434afe1 | refs/heads/master | 2021-01-10T10:12:46.760433 | 2011-05-21T17:00:12 | 2011-05-21T17:00:12 | 36,380,809 | 2 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 353 | h | #pragma once
#include "VCRPlayer.h"
class SonyVCRPlayer : public VCRPlayer {
public:
friend class SonyPlayerFactory;
virtual void start();
virtual void stop();
virtual void forward();
virtual void rewind();
private:
SonyVCRPlayer() {}
SonyVCRPlayer(const SonyVCRPlayer&);
SonyVCRPlayer& operator=(const SonyVCRPlayer&);
}; | [
"dankilman@a7c0e201-94a5-d3f3-62b2-47f0ba67a830",
"[email protected]"
]
| [
[
[
1,
6
],
[
9,
12
],
[
18,
18
]
],
[
[
7,
8
],
[
13,
17
]
]
]
|
d5c5208c5f871de167ef6f0c934e5c5481aab7a9 | 485c5413e1a4769516c549ed7f5cd4e835751187 | /Source/Engine/Spline/Spline.cpp | 0a990dba4ea3c171ff1a3466cd7d0861383a8a94 | []
| no_license | FranckLetellier/rvstereogram | 44d0a78c47288ec0d9fc88efac5c34088af88d41 | c494b87ee8ebb00cf806214bc547ecbec9ad0ca0 | refs/heads/master | 2021-05-29T12:00:15.042441 | 2010-03-25T13:06:10 | 2010-03-25T13:06:10 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 7,361 | cpp | //---------------------------------------------------------------------
//
// PROJECT ....
// Copyright (C)
//
// All rights reserved
//
//---------------------------------------------------------------------
/// Spline
///\author Helena DUCHAUSSOY, Fabien KAPALA, Franck LETELLIER, Baptiste MALAGA
#include "Spline.hpp"
#include <GL/glew.h>
#include <GL/glut.h>
#include <GL/glu.h>
Spline::Spline(const char * filename)
{
controlPoints = loadXMLFile(filename);
int size = controlPoints.size();
boost::numeric::ublas::matrix<float> leftM = fillLeftMatrix(size);
boost::numeric::ublas::vector<float> vectorDx = initDeltaVector(size);
boost::numeric::ublas::vector<float> vectorDy = initDeltaVector(size);
boost::numeric::ublas::vector<float> vectorDz = initDeltaVector(size);
boost::numeric::ublas::vector<float> vectorBx = fillRightVector(controlPoints,0);
boost::numeric::ublas::vector<float> vectorBy = fillRightVector(controlPoints,1);
boost::numeric::ublas::vector<float> vectorBz = fillRightVector(controlPoints,2);
boost::numeric::ublas::matrix<float> inverseLeftM = gaussJordan(leftM);
vectorDx = prod(inverseLeftM,vectorBx);
vectorDy = prod(inverseLeftM,vectorBy);
vectorDz = prod(inverseLeftM,vectorBz);
for(unsigned int i=0 ; i<vectorDx.size() ; i++){
if(abs(vectorDx[i])<0.001) vectorDx[i]=0;
if(abs(vectorDy[i])<0.001) vectorDy[i]=0;
if(abs(vectorDz[i])<0.001) vectorDz[i]=0;
}
float sLength = splineLength(0.1, vectorDx, vectorDy, vectorDz);
float precision = sLength/500;
createSpline(0.001, precision, vectorDx, vectorDy, vectorDz);
}
Spline::Spline(const char * filename, float precision)
{
controlPoints = loadXMLFile(filename);
int size = controlPoints.size();
boost::numeric::ublas::matrix<float> leftM = fillLeftMatrix(size);
boost::numeric::ublas::vector<float> vectorDx = initDeltaVector(size);
boost::numeric::ublas::vector<float> vectorDy = initDeltaVector(size);
boost::numeric::ublas::vector<float> vectorDz = initDeltaVector(size);
boost::numeric::ublas::vector<float> vectorBx = fillRightVector(controlPoints,0);
boost::numeric::ublas::vector<float> vectorBy = fillRightVector(controlPoints,1);
boost::numeric::ublas::vector<float> vectorBz = fillRightVector(controlPoints,2);
boost::numeric::ublas::matrix<float> inverseLeftM = gaussJordan(leftM);
vectorDx = prod(inverseLeftM,vectorBx);
vectorDy = prod(inverseLeftM,vectorBy);
vectorDz = prod(inverseLeftM,vectorBz);
for(unsigned int i=0 ; i<vectorDx.size() ; i++){
if(abs(vectorDx[i])<0.001) vectorDx[i]=0;
if(abs(vectorDy[i])<0.001) vectorDy[i]=0;
if(abs(vectorDz[i])<0.001) vectorDz[i]=0;
}
createSpline(0.001, precision, vectorDx, vectorDy, vectorDz);
}
Spline::~Spline()
{
}
boost::numeric::ublas::matrix<float> Spline::fillLeftMatrix(int size)
{
boost::numeric::ublas::matrix<float> leftMatrix(size,size);
int i,j;
for(i=0 ; i<size ; i++){
for(j=0 ; j<size ; j++){
if(i==j){
leftMatrix.insert_element(i,j,4);
}
else if(i==size-1 && j==0){
leftMatrix.insert_element(i,j,1);
}
else if(i==0 && j==size-1){
leftMatrix.insert_element(i,j,1);
}
else if(j==i+1 || j==i-1){
leftMatrix.insert_element(i,j,1);
}
else{
leftMatrix.insert_element(i,j,0);
}
}
}
return leftMatrix;
}
boost::numeric::ublas::vector<float> Spline::initDeltaVector(int rows)
{
return boost::numeric::ublas::zero_vector<float>(rows);
}
boost::numeric::ublas::vector<float> Spline::fillRightVector(const std::vector<osg::Vec3f> v, int composant)
{
int size = v.size();
boost::numeric::ublas::vector<float> result(size);
for(int i=0 ; i<size ; i++){
if(i!=0 && i!= size-1){
result.insert_element(i , 3*(v.at(i+1)[composant]-v.at(i-1)[composant]));
}
if(i==0){
result.insert_element(i , 3*(v.at(i+1)[composant]-v.at(size-1)[composant]));
}
if(i==size-1){
result.insert_element(i , 3*(v.at(0)[composant]-v.at(i-1)[composant]));
}
}
return result;
}
float Spline::getPointCoordinate (float t, boost::numeric::ublas::vector<float> vecD, unsigned int index, unsigned int composant)
{
float a = controlPoints.at(index)[composant];
float b = vecD(index);
float c;
float d;
if(index != controlPoints.size()-1){
c = 3*(controlPoints.at(index+1)[composant] - controlPoints.at(index)[composant]) - 2*vecD(index) - vecD(index+1);
d = 2*(controlPoints.at(index)[composant] - controlPoints.at(index+1)[composant]) + vecD(index) + vecD(index+1);
}
else if(index == controlPoints.size()-1){
c = 3*(controlPoints.at(0)[composant] - controlPoints.at(index)[composant]) - 2*vecD(index) - vecD(0);
d = 2*(controlPoints.at(index)[composant] - controlPoints.at(0)[composant]) + vecD(index) + vecD(0);
}
return (a+(b*t)+(c*t*t)+(d*pow(t,3)));
}
float Spline::splineLength(float step, boost::numeric::ublas::vector<float> vecDx, boost::numeric::ublas::vector<float> vecDy, boost::numeric::ublas::vector<float> vecDz)
{
float t=0;
unsigned int size = controlPoints.size();
unsigned int l=0;
float splineLength = 0;
osg::Vec3f newPoint, exPoint;
while(l < size){
while(t < 1){
newPoint[0] = getPointCoordinate(t, vecDx, l, 0);
newPoint[1] = getPointCoordinate(t, vecDy, l, 1);
newPoint[2] = getPointCoordinate(t, vecDz, l, 2);
//tmpVector.push_back(newPoint);
if(t != 0 || l != 0){
// Not the very first point of the Spline so we can calculate the distance
// between the previous point and the current one
float tmp = pow(newPoint.x()-exPoint.x(),2)+pow(newPoint.y()-exPoint.y(),2)+pow(newPoint.z()-exPoint.z(),2);
splineLength += pow (tmp,static_cast<float>(0.5));
}
exPoint = newPoint;
t+=step;
}
t=0;
l++;
}
return splineLength;
}
void Spline::createSpline(float precision, float step, boost::numeric::ublas::vector<float> vecDx, boost::numeric::ublas::vector<float> vecDy, boost::numeric::ublas::vector<float> vecDz)
{
float t=0;
float dist = 0;
unsigned int size = controlPoints.size();
unsigned int l=0;
osg::Vec3f newPoint, exPoint;
while(l<size){
exPoint[0] = controlPoints[l][0];
exPoint[1] = controlPoints[l][1];
exPoint[2] = controlPoints[l][2];
while(t<1){
t+=precision;
newPoint[0] = getPointCoordinate(t, vecDx, l, 0);
newPoint[1] = getPointCoordinate(t, vecDy, l, 1);
newPoint[2] = getPointCoordinate(t, vecDz, l, 2);
dist = pow( pow(newPoint.x()-exPoint.x(),2) + pow(newPoint.y()-exPoint.y(),2) + pow(newPoint.z()-exPoint.z(),2),static_cast<float>(0.5));
if(dist>step){
splinePoints.push_back(newPoint);
exPoint = newPoint;
}
}
t=0;
l++;
}
}
void Spline::draw()
{
osg::Vec3f point;
glBegin(GL_LINES);
point = getSplinePointAt(0);
glVertex3f(point.x(),point.y(),point.z());
for(unsigned int i=1 ; i<getSplineSize() ; ++i)
{
point = getSplinePointAt(i);
glVertex3f(point.x(),point.y(),point.z());
glVertex3f(point.x(),point.y(),point.z());
}
point = getSplinePointAt(0);
glVertex3f(point.x(),point.y(),point.z());
glEnd();
for(unsigned int i=0 ; i<getControlSize() ; ++i)
{
point = getControlPointAt(i);
glPushMatrix();
glTranslatef(point.x(),point.y(),point.z());
glutSolidSphere(0.1f,8.0,8.0);
glPopMatrix();
}
}
| [
"[email protected]"
]
| [
[
[
1,
255
]
]
]
|
dea94e8bf1e4c8ab837d52c57e98f965d5c9445e | 6d340a0cdbabbcbdd10460852ed24770c2ec78e4 | /source_codes/geometry/two_farest_points/two_farest_points.cpp | b9036f375f7319e1e93e93525a65982c4b133bb0 | []
| no_license | vsbus/vsb-reference | 5bdb5eb8c212f1e8592a1b47044f5d531d741df4 | 2f4434e896bd03d33c14683b3702f09d51b5992e | refs/heads/master | 2021-01-10T18:38:57.392158 | 2011-05-10T13:08:11 | 2011-05-10T13:08:11 | 32,411,348 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 492 | cpp | double maxConvPolyDist(Poly p) {
int n = p.size();
double res = 0;
if (n == 2) {
return sqrt((p[0] - p[1]).length2());
}
if (n > 2) {
for (int j = n - 1, i = 0, cur = 1, next = (cur + 1) % n; i < n; j = i++) {
Point v = p[i] - p[j];
while(v % (p[cur] - p[j]) <= v % (p[next] - p[j])) {
cur = next;
if (++next == n) {
next = 0;
}
}
res = max(res, max((p[i] - p[cur]).length2(), (p[j] - p[cur]).length2()));
}
}
return sqrt(res);
}
| [
"victorbarinov@ad8ebaea-3bba-49b6-65e2-71ef8dee33c5"
]
| [
[
[
1,
20
]
]
]
|
e18546619fa24946636a644f5130a57c0732059a | 7f6fe18cf018aafec8fa737dfe363d5d5a283805 | /samples/toyozpaint/aboutwindow.h | cb5c905ff158e7ac9423fc81c3065b290c54c3b7 | []
| no_license | snori/ntk | 4db91d8a8fc836ca9a0dc2bc41b1ce767010d5ba | 86d1a32c4ad831e791ca29f5e7f9e055334e8fe7 | refs/heads/master | 2020-05-18T05:28:49.149912 | 2009-08-04T16:47:12 | 2009-08-04T16:47:12 | 268,861 | 2 | 0 | null | null | null | null | SHIFT_JIS | C++ | false | false | 2,626 | h | #ifndef __ABOUTWINDOW_H__
#define __ABOUTWINDOW_H__
#include <ntk/interface/window.h>
#include <ntk/interface/screen.h>
#include <ntk/interface/stringview.h>
#include "toyozpaint.h"
class about_window_t : public ntk_window {
public:
//
// constants
//
enum {
OK_J_MESSAGE = 'OK_J'
};// messages
//
// methods
//
about_window_t()
: ntk_window(ntk_rect(0, 0, 400, 300), "バージョン情報", TITLED_WINDOW, NOT_RESIZABLE)
{
move_to_center_();
setup_controls_();
}
void message_received(const ntk_message& message)
{
switch(message.what)
{
case OK_J_MESSAGE:
quit();
break;
default:
ntk_window::message_received(message);
}
}
private:
//
// functions
//
void move_to_center_()
{
move_to(
(ntk_screen::frame().width() - frame().width()) /2,
(ntk_screen::frame().height() - frame().height()) /2);
}
void setup_controls_()
{
enum {BUTTON_HEIGHT = 30};
ntk_rect rect = bounds();
rect.inset_by(10, 10);
rect.bottom -= BUTTON_HEIGHT;
ntk_string_view* ver_info = new ntk_string_view(
rect, "VerInfo", ver_info_string(), ntk_view::FOLLOW_ALL_SIDES,
ntk_string_view::DEFAULT_FLAGS | ntk_view::FULL_UPDATE_ON_RESIZE,
panel()->view_color() + 20);
ver_info->set_alignment(ntk_string_view::ALIGN_CENTER | ntk_string_view::ALIGN_VCENTER);
ver_info->set_ex_style(ver_info->ex_style() | WS_EX_STATICEDGE);
ver_info->resize_by(1, 0);ver_info->resize_by(-1, 0);// style 更新の為(^^;
add_child(ver_info);
rect = bounds();
rect.top = rect.bottom - 30;
rect.inset_by(-1, 0);
rect.bottom += 1;
{
ntk_rect left = rect;
left.right = left.left + left.width() /2;
add_child(new ntk_button(left, "CloseButton", "OK", new ntk_message(ntk::QUIT_REQUESTED), ntk_view::FOLLOW_LEFT_RIGHT | ntk_view::FOLLOW_BOTTOM, ntk_button::DEFAULT_FLAGS | ntk_view::FULL_UPDATE_ON_RESIZE));
ntk_rect right = rect;
right.left = right.right - right.width() /2;
add_child(new ntk_button(right, "CloseButton", "おーけー", new ntk_message(OK_J_MESSAGE), ntk_view::FOLLOW_LEFT_RIGHT | ntk_view::FOLLOW_BOTTOM, ntk_button::DEFAULT_FLAGS | ntk_view::FULL_UPDATE_ON_RESIZE));
}
}
ntk_string ver_info_string()
{
const ntk_version& ver = app()->version();
return
app()->name() + "\n" +
"\n" +
"v" + ver.as_string() + "\n" +
"[" + ver.name() + "]\n" +
"\n" +
"COPYRIGHT (C) 1998-2002 Snori, ALL RIGHTS RESERVED.\n"
"\n"
"mailto:[email protected]\nhttp://ntk.yi.org/";
}
};// class about_window_t
#endif//EOH | [
"[email protected]"
]
| [
[
[
1,
101
]
]
]
|
bc0cc64ccffa5a27e3f34b66e54e8446939b2368 | d115cf7a1b374d857f6b094d4b4ccd8e9b1ac189 | /pyplusplus_dev/unittests/data/already_exposed_2to_be_exported.hpp | 3601d4e0d5c8c481ae28dc17e97eb69e7a97a95a | [
"BSL-1.0"
]
| permissive | gatoatigrado/pyplusplusclone | 30af9065fb6ac3dcce527c79ed5151aade6a742f | a64dc9aeeb718b2f30bd6a5ff8dcd8bfb1cd2ede | refs/heads/master | 2016-09-05T23:32:08.595261 | 2010-05-16T10:53:45 | 2010-05-16T10:53:45 | 700,369 | 4 | 2 | null | null | null | null | UTF-8 | C++ | false | false | 627 | hpp | // Copyright 2004-2008 Roman Yakovenko.
// Distributed under the Boost Software License, Version 1.0. (See
// accompanying file LICENSE_1_0.txt or copy at
// http://www.boost.org/LICENSE_1_0.txt)
#ifndef __already_exposed_2to_be_exported_hpp__
#define __already_exposed_2to_be_exported_hpp__
#include "already_exposed_to_be_exported.hpp"
#include <vector>
#include <string>
namespace to_be_exposed{
struct ae_derived : public already_exposed::ae_base
{};
inline std::vector< std::string > do_nothing(){
return std::vector< std::string >();
}
}
#endif//__already_exposed_2to_be_exported_hpp__
| [
"roman_yakovenko@dc5859f9-2512-0410-ae5c-dd123cda1f76"
]
| [
[
[
1,
24
]
]
]
|
dd41038a4365c1315cdebca0c76b9b5829142b1a | 7fd11eb839c1b9a4ffaaecf8c5f8500452f58ab5 | /DipstickDlg.h | 47c3e016bd26485dfa274677d33d651526461f4f | [
"MIT"
]
| permissive | wyrover/dipstick | 05f23a9c06960182d803e1fd62bb3a641051656e | 9c276c74d74ade95556d44b218aca06edb63a02b | refs/heads/master | 2021-01-18T20:03:00.993256 | 2005-08-06T21:38:18 | 2005-08-06T21:38:18 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 6,156 | h | // DipstickDlg.h : header file
//
class CDipstickDlg;
struct CPingyHost {
CPingyHost(CDipstickDlg* daddy) : m_IP(0), m_MinRTT(0), m_AvgRTT(0), m_MaxRTT(0), m_Pinged(FALSE), m_Pinging(FALSE), m_Packetloss(-1), m_bToPing(TRUE), m_Daddy(daddy) {}
CPingyHost(CDipstickDlg* daddy,LPTSTR hostname) : m_HostName(hostname), m_IP(0), m_MinRTT(0), m_AvgRTT(0), m_MaxRTT(0), m_Pinged(FALSE), m_Pinging(FALSE), m_Packetloss(-1), m_bToPing(TRUE), m_Daddy(daddy) {}
CPingyHost(CDipstickDlg* daddy,LPTSTR hostname,DWORD ip) : m_HostName(hostname), m_IP(ip), m_MinRTT(0), m_AvgRTT(0), m_MaxRTT(0), m_Pinged(FALSE), m_Pinging(FALSE), m_Packetloss(-1), m_bToPing(TRUE), m_Daddy(daddy) {}
CPingyHost(CDipstickDlg* daddy,DWORD ip) : m_IP(ip), m_MinRTT(0), m_AvgRTT(0), m_MaxRTT(0), m_Pinged(FALSE), m_Pinging(FALSE), m_Packetloss(-1), m_bToPing(TRUE), m_Daddy(daddy) {}
public:
static UINT SuicideProc(LPVOID pParam);
void Suicide();
void Ping();
UINT DoPing();
static UINT PingProc(LPVOID);
CDipstickDlg* m_Daddy;
CMutex m_mutex;
CString m_Descr;
CString m_URL;
BOOL m_bToPing;
BOOL m_Pinging;
CString m_HostName;
CString m_Status;
DWORD m_IP;
ULONG m_MinRTT;
ULONG m_AvgRTT;
ULONG m_MaxRTT;
BOOL m_Pinged;
int m_Packetloss;
};
typedef CList<CPingyHost*,CPingyHost*> CHostList;
/////////////////////////////////////////////////////////////////////////////
// CDipstickDlg dialog
class CDragPad;
class CDipstickDlg : public CDialog
{
// Construction
struct _xferHTML {
CString html;
CCrackURL src;
};
public:
LRESULT OnURLSPing(WPARAM wP,LPARAM lP);
CRegEx m_reURL;
BOOL ExportLocations(LPCTSTR file);
CString m_impexPath;
BOOL ImportLocations(LPCTSTR file);
BOOL m_bIgnorelative;
CEvent m_eveStartup;
UINT volatile m_ActiveThreads;
BOOL m_bAdjustInnermost;
BOOL m_bSmartAdjust;
BOOL CollectURLs(COleDataObject* pDO,BOOL bTestOnly=FALSE);
BOOL IsPasteableClipboard();
void UpdateDragpadTitle();
BOOL m_bAutoBest;
void RecalcLayout(int cx,int cy);
CSize m_MinSize;
UINT m_GapY;
UINT m_OverY;
UINT m_OverX;
BOOL m_bMSWorkAround;
CRegEx m_reCrackHost;
CRegEx m_reNestedURL;
CRegEx m_reHTMLURL; // 1 - URL
CRegEx m_reCrackURL; // 3 - schema, 4 - host, 5 - path, 7 - query string
BITMAP m_bitmapBack;
CBitmap m_bmpBack;
int m_iUnreachable;
int m_iCompleted;
int m_iPinging;
int m_iPending;
CImageList m_Images;
void UpdateControlButtons();
BOOL m_bExiting;
int CheckForPendingRequests();
UINT m_MaxThreads;
BOOL m_bShown;
enum {
sortHost, sortIP, sortMin, sortAvg, sortMax, sortLoss
};
int m_SortCriteria;
static int CALLBACK CompareItems(LPARAM lp1, LPARAM lp2, LPARAM lp);
DWORD m_Interval;
BOOL RemovePingyHost(CPingyHost *host,int index=-1);
BOOL UpdatePingyHost(CPingyHost *host,int index=-1);
BOOL AddPingyHost(CPingyHost *host);
CHostList m_Hosts;
enum {
subitemHost = 0, subitemIP, subitemMin,subitemAvg,subitemMax, subitemPacketloss
};
DWORD m_TimeOut;
UINT m_PingSize;
UINT m_PingsPerHost;
CDragPad * m_DragPad;
~CDipstickDlg();
CDipstickDlg(CWnd* pParent = NULL); // standard constructor
// Dialog Data
//{{AFX_DATA(CDipstickDlg)
enum { IDD = IDD_DIPSTICK_DIALOG };
CButton m_AdvancedCtl;
CButton m_HelpCtl;
CButton m_ExitCtl;
CButton m_OptionsCtl;
CButton m_ManualPingCtl;
CButton m_RemoveCtl;
CButton m_RepingAllCtl;
CButton m_RepingCtl;
CButton m_ClearListCtl;
CListCtrl m_HostList;
//}}AFX_DATA
// ClassWizard generated virtual function overrides
//{{AFX_VIRTUAL(CDipstickDlg)
protected:
virtual void DoDataExchange(CDataExchange* pDX); // DDX/DDV support
virtual BOOL PreCreateWindow(CREATESTRUCT& cs);
//}}AFX_VIRTUAL
// Implementation
protected:
HICON m_hIcon;
// Generated message map functions
//{{AFX_MSG(CDipstickDlg)
virtual BOOL OnInitDialog();
afx_msg void OnSysCommand(UINT nID, LPARAM lParam);
afx_msg void OnPaint();
afx_msg HCURSOR OnQueryDragIcon();
afx_msg void OnDestroy();
afx_msg void OnOptions();
afx_msg LRESULT OnUrlPing(WPARAM,LPARAM);
afx_msg LRESULT OnActivityCount(WPARAM,LPARAM);
afx_msg LRESULT OnUpdateHostData(WPARAM,LPARAM);
afx_msg LRESULT OnHTMLTransfer(WPARAM,LPARAM);
afx_msg void OnColumnclickHostlist(NMHDR* pNMHDR, LRESULT* pResult);
afx_msg void OnWindowPosChanging(WINDOWPOS FAR* lpwndpos);
afx_msg void OnDragpadOptions();
afx_msg void OnDragpadShowmainwindow();
afx_msg void OnDragpadHelp();
afx_msg void OnDragpadAbout();
afx_msg void OnDragpadExit();
virtual void OnOK();
virtual void OnCancel();
afx_msg void OnManualping();
afx_msg void OnDragpadManualping();
afx_msg void OnDragpadRepingAll();
afx_msg void OnDragpadRemoveAll();
afx_msg void OnReping();
afx_msg void OnRepingall();
afx_msg void OnClear();
afx_msg void OnInsertitemHostlist(NMHDR* pNMHDR, LRESULT* pResult);
afx_msg void OnDeleteitemHostlist(NMHDR* pNMHDR, LRESULT* pResult);
afx_msg void OnDeleteallitemsHostlist(NMHDR* pNMHDR, LRESULT* pResult);
afx_msg void OnExit();
afx_msg void OnItemchangedHostlist(NMHDR* pNMHDR, LRESULT* pResult);
afx_msg void OnRemove();
afx_msg void OnRclickHostlist(NMHDR* pNMHDR, LRESULT* pResult);
afx_msg void OnHostListReping();
afx_msg void OnHostListRemove();
afx_msg void OnHostListRepingAll();
afx_msg void OnHostListRemoveAll();
afx_msg void OnHostListOpenURL();
afx_msg void OnHostListProperties();
afx_msg void OnDblclkHostlist(NMHDR* pNMHDR, LRESULT* pResult);
afx_msg void OnClose();
afx_msg void OnGetMinMaxInfo(MINMAXINFO FAR* lpMMI);
afx_msg void OnSize(UINT nType, int cx, int cy);
afx_msg void OnHelp();
afx_msg void OnBegindragHostlist(NMHDR* pNMHDR, LRESULT* pResult);
afx_msg void OnPasteurl();
afx_msg void OnHostlistCopyurl();
afx_msg BOOL OnHelpInfo(HELPINFO* pHelpInfo);
afx_msg void OnDropFiles(HDROP hDropInfo);
afx_msg void OnAdvanced();
afx_msg void OnAdvancedExportlist();
afx_msg void OnAdvancedImportlist();
afx_msg void OnDragpadAdvancedExportlist();
afx_msg void OnDragpadAdvancedImportlist();
//}}AFX_MSG
DECLARE_MESSAGE_MAP()
};
| [
"[email protected]"
]
| [
[
[
1,
186
]
]
]
|
7bdb27e08a0b4773985e61551f9689bf06b84d0b | 6581dacb25182f7f5d7afb39975dc622914defc7 | /easyMule/easyMule/src/UILayer/SearchButton.cpp | 3fe5df90fc505337f34924ec61e06204b6bb9254 | []
| no_license | dice2019/alexlabonline | caeccad28bf803afb9f30b9e3cc663bb2909cc4f | 4c433839965ed0cff99dad82f0ba1757366be671 | refs/heads/master | 2021-01-16T19:37:24.002905 | 2011-09-21T15:20:16 | 2011-09-21T15:20:16 | null | 0 | 0 | null | null | null | null | GB18030 | C++ | false | false | 7,714 | cpp | /*
* $Id: SearchButton.cpp 14238 2009-07-08 10:04:38Z dgkang $
*
* this file is part of easyMule
* Copyright (C)2002-2008 VeryCD Dev Team ( strEmail.Format("%s@%s", "emuledev", "verycd.com") / http: * www.easymule.org )
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU General Public License
* as published by the Free Software Foundation; either
* version 2 of the License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.
*/
// SearchButton.cpp : 实现文件
//
#include "stdafx.h"
#include "emule.h"
#include "emuleDlg.h"
#include "SearchButton.h"
#include "Util.h"
#include "SearchBarCtrl.h"
#include "CmdFuncs.h"
#include "FaceManager.h"
#include "DlgMainTabSidePanel.h"
#include "StringConversion.h"
#include "CmdFuncs.h"
#include ".\searchbutton.h"
#include "StatForServer.h"
#include "DlgMainTabSearch.h"
// CSearchButton
CSearchButton::CSearchButton()
{
m_hIcon = theApp.LoadIcon(_T("FIND"), 16, 16, LR_DEFAULTSIZE);
m_bHover = FALSE;
m_bIsPressed = FALSE;
}
CSearchButton::~CSearchButton()
{
}
BEGIN_MESSAGE_MAP(CSearchButton, CButton)
ON_WM_MEASUREITEM()
ON_WM_MOUSEMOVE()
ON_MESSAGE(WM_MOUSELEAVE, OnMouseLeave)
ON_CONTROL_REFLECT(BN_CLICKED, OnBnClicked)
ON_WM_ERASEBKGND()
//ON_WM_PAINT()
END_MESSAGE_MAP()
// CSearchButton 消息处理程序
BOOL CSearchButton::Create(CWnd* pParentWnd, CRect rect, LPCTSTR lpszCaption, DWORD dwStyle, UINT nID)
{
return CButton::Create(lpszCaption, dwStyle | BS_OWNERDRAW, rect, pParentWnd, nID);
}
void CSearchButton::GetDesireSize(CSize &size)
{
CFaceManager::GetInstance()->GetImageSize(II_SEARCHBTN_N, size);
}
void CSearchButton::OnMeasureItem(int nIDCtl, LPMEASUREITEMSTRUCT lpMeasureItemStruct)
{
CButton::OnMeasureItem(nIDCtl, lpMeasureItemStruct);
}
void CSearchButton::PreSubclassWindow()
{
//ModifyStyle(BS_TYPEMASK, BS_OWNERDRAW, SWP_FRAMECHANGED);
// ModifyStyle(BS_TYPEMASK, 0, SWP_FRAMECHANGED);
CButton::PreSubclassWindow();
}
void CSearchButton::DrawInactive(CDC* pDC, const CRect& rect)
{
CRect rtFrm;
CRect rtFace;
rtFrm = rect;
rtFace = rect;
{
//CPenDC penOutSide(pDC->GetSafeHdc(), RGB(171, 164, 150));
Draw2GradLayerRect(pDC->GetSafeHdc(), rtFace, RGB(224, 240, 248), RGB(224, 240, 248), RGB(200, 216, 232), RGB(200, 216, 232), 62);
}
{
CPenDC penInSide(pDC->GetSafeHdc(), RGB(255, 255, 255), 1);
rtFrm.left += 2;
rtFrm.top += 2;
rtFrm.right -= 1;
rtFrm.bottom -= 2;
//DrawRound(pDC->GetSafeHdc(), rtFrm, 4);
}
}
void CSearchButton::DrawHover(CDC* pDC, const CRect& rect)
{
CRect rtFrm;
CRect rtFace;
rtFrm = rect;
rtFace = rect;
{
//CPenDC penOutSide(pDC->GetSafeHdc(), RGB(110, 150, 199));
//rtFace.top += 3;
Draw2GradLayerRect(pDC->GetSafeHdc(), rtFace, RGB(208, 248, 200), RGB(208, 248, 200), RGB(160, 232, 144), RGB(160, 232, 144), 62);
//DrawRound(pDC->GetSafeHdc(), rtFrm, 3);
}
{
CPenDC penInSide(pDC->GetSafeHdc(), RGB(255, 255, 255), 2);
rtFrm.left += 2;
rtFrm.top += 2;
rtFrm.right -= 1;
rtFrm.bottom -= 2;
//DrawRound(pDC->GetSafeHdc(), rtFrm, 3);
}
}
void CSearchButton::DrawPressed(CDC* pDC, const CRect& rect)
{
CRect rtFrm;
CRect rtFace;
rtFrm = rect;
rtFace = rect;
{
Draw2GradLayerRect(pDC->GetSafeHdc(), rtFace, RGB(170, 206, 227), RGB(170, 206, 227), RGB(107, 171, 207), RGB(113, 174, 209), 62);
}
{
CPenDC penInSide(pDC->GetSafeHdc(), RGB(255, 255, 255), 2);
rtFrm.left += 2;
rtFrm.top += 2;
rtFrm.right -= 1;
rtFrm.bottom -= 2;
}
}
void CSearchButton::DrawItem(LPDRAWITEMSTRUCT lpDrawItemStruct)
{
CClientRect rtClient(this);
CBufferDC bufDC(lpDrawItemStruct->hDC, rtClient);
DrawParentBk(GetSafeHwnd(), bufDC.GetSafeHdc());
m_bIsPressed = lpDrawItemStruct->itemState & ODS_SELECTED;
if (m_bHover)
{
if (m_bIsPressed)
CFaceManager::GetInstance()->DrawImage(II_SEARCHBTN_P, bufDC.GetSafeHdc(), rtClient);
else
CFaceManager::GetInstance()->DrawImage(II_SEARCHBTN_H, bufDC.GetSafeHdc(), rtClient);
}
else
CFaceManager::GetInstance()->DrawImage(II_SEARCHBTN_N, bufDC.GetSafeHdc(), rtClient);
}
void CSearchButton::OnMouseMove(UINT nFlags, CPoint point)
{
TRACKMOUSEEVENT csTME;
CButton::OnMouseMove(nFlags, point);
if (!m_bHover)
{
m_bHover = TRUE;
Invalidate();
ZeroMemory(&csTME, sizeof(csTME));
csTME.cbSize = sizeof(csTME);
csTME.dwFlags = TME_LEAVE;
csTME.hwndTrack = m_hWnd;
::_TrackMouseEvent(&csTME);
}
}
LRESULT CSearchButton::OnMouseLeave(WPARAM /*wParam*/, LPARAM /*lParam*/)
{
if (m_bHover)
{
m_bHover = FALSE;
Invalidate();
}
return 0;
}
void CSearchButton::OnBnClicked()
{
CString str;
CString query;
CSearchBarCtrl* SearchBarCtrl = (CSearchBarCtrl*)(&((CDlgMainTabSidePanel*)GetParent())->m_SearchBarCtrl);
CSearchEdit* SearchEditor = SearchBarCtrl->GetEditor();
SearchEditor->GetWindowText(str);
if(!str.Compare(GetResString(IDS_SEARCH_INPUT)))
{
return;
}
switch(SearchBarCtrl->GetSearchType())
{
case SearchTypeEd2kGlobal:
if(SearchEditor->m_bTipinfo || str.IsEmpty())
{
return;
}
else
{
if (str.Left(13).CompareNoCase(_T("ed2k://|file|")) == 0)
{
CmdFuncs::AddEd2kLinksToDownload(str, 0);
}
// VC-SearchDream[2007-04-06]: For HTTP and FTP Direct DownLoad
else if ((str.Left(7).CompareNoCase(_T("http://")) == 0) || (str.Left(6).CompareNoCase(_T("ftp://")) == 0)) // Direct HTTP and FTP DownLoad
{
CmdFuncs::AddUrlToDownload(str);
}
else
{
//VC-dgkang 将定位到新Search标签去.
theApp.emuledlg->m_mainTabWnd.m_dlgSearch.OpenNewSearchResult(str);
//theApp.emuledlg->m_mainTabWnd.m_dlgResource.OpenNewSearchResult(str);
}
}
break;
case SearchTypeVeryCD:
if (str.Left(13).CompareNoCase(_T("ed2k://|file|")) == 0)
{
CmdFuncs::AddEd2kLinksToDownload(str, 0);
}
else
{
if ((str.Left(7).CompareNoCase(_T("http://")) == 0) || (str.Left(6).CompareNoCase(_T("ftp://")) == 0)) // Direct HTTP and FTP DownLoad
{
CmdFuncs::AddUrlToDownload(str);
}
else
{
if(thePrefs.m_bShowBroswer /*&& IsWindow(theApp.emuledlg->webbrowser->m_hWnd)*/ )
{
//VC-dgkang 2008年7月8日
#ifdef _FOREIGN_VERSION
query = thePrefs.m_strSearchPage;
#else
query = "http://www.verycd.com/search/folders/";
#endif
query += EncodeUrlUtf8(str);
//VC-dgkang 2008年7月10日
//VC 搜索也可以不加的,所以去掉 /
//query += "/";
theApp.emuledlg->m_mainTabWnd.m_dlgResource.OpenNewUrl(query, str);
}
else
{
ShellOpenFile(query);
}
}
}
break;
default:
ASSERT(0);
}
}
BOOL CSearchButton::OnEraseBkgnd(CDC* /*pDC*/)
{
return TRUE;
}
BOOL CSearchButton::PreTranslateMessage(MSG* pMsg)
{
// TODO: 在此添加专用代码和/或调用基类
if (WM_LBUTTONDBLCLK == pMsg->message)
pMsg->message = WM_LBUTTONDOWN;
return CButton::PreTranslateMessage(pMsg);
}
| [
"damoguyan8844@3a4e9f68-f5c2-36dc-e45a-441593085838"
]
| [
[
[
1,
311
]
]
]
|
cf3ed268f6c225534d48d700f5f95f627e04e81f | d99be43382029eac49f8b922b1dda681a477eeff | /src/figures/Figure.h | 779defa19a3fab82db3215168d2be8e4126d2e38 | [
"MIT"
]
| permissive | jinkoandres/ofxTableGestures | 9535ce8046b84050cc3f4c567e665d38c5af8bfd | d4ca6ac7af6841373d42c0e2b86a9298e4baeed8 | refs/heads/master | 2021-05-13T17:47:19.156720 | 2011-06-30T15:17:40 | 2011-06-30T15:17:40 | 116,836,902 | 0 | 0 | null | 2018-01-09T15:53:33 | 2018-01-09T15:53:33 | null | UTF-8 | C++ | false | false | 2,211 | h | /*
ofxTableGestures (formerly OF-TangibleFramework)
Developed for Taller de Sistemes Interactius I
Universitat Pompeu Fabra
Copyright (c) 2011 Daniel Gallardo Grassot <[email protected]>
Permission is hereby granted, free of charge, to any person
obtaining a copy of this software and associated documentation
files (the "Software"), to deal in the Software without
restriction, including without limitation the rights to use,
copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the
Software is furnished to do so, subject to the following
conditions:
The above copyright notice and this permission notice shall be
included in all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES
OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT
HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,
WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR
OTHER DEALINGS IN THE SOFTWARE.
*/
#ifndef DFIGURE_H
#define DFIGURE_H
#include "BoundingBox.h"
#include <string>
#include "ofMain.h"
#include "Matrix.h"
namespace Figures
{
class Figure
{
public:
Figure();
virtual ~Figure();
void SetTexture(const std::string & path);
void SetTexture(ofImage& image);
void Draw();
void DrawStroke();
bool Collide(ofPoint const & point);
virtual void GetCentre(float & x, float & y);
ofPoint GetCentre();
protected:
BoundingBox bbox;
bool has_texture;
ofImage texture;
Matrix matrix;
virtual void RebuildGeometry()=0;
virtual void Design()=0;
virtual void DesignStroke()=0;
virtual bool CheckCollision(ofPoint const & point)=0;
};
}
#endif // DFIGURE_H
| [
"daniel@dphdstdnt.(none)"
]
| [
[
[
1,
66
]
]
]
|
054095db0960007f6f574607a3ee4857e1262b9a | 5bd189ea897b10ece778fbf9c7a0891bf76ef371 | /BasicEngine/BasicEngine/Physics/PhysicsManager.h | e077e52ad308c616fc0392fb379c4459dcf27a05 | []
| no_license | boriel/masterullgrupo | c323bdf91f5e1e62c4c44a739daaedf095029710 | 81b3d81e831eb4d55ede181f875f57c715aa18e3 | refs/heads/master | 2021-01-02T08:19:54.413488 | 2011-12-14T22:42:23 | 2011-12-14T22:42:23 | 32,330,054 | 0 | 0 | null | null | null | null | ISO-8859-1 | C++ | false | false | 2,828 | h | /*
class cPhysichsManager
haciendo pruebas con la física, para hacer un manager y usarlo.
*/
#ifndef PHYSICS_MANAGER_H
#define PHYSICS_MANAGER_H
#include "..\Utility\ResourceManager.h"
#include "..\Utility\Singleton.h"
#include "btBulletDynamicsCommon.h"
#include "Objects\PhysicsCube.h"
#include "PhysicObjectType.h"
#include "..\MathLib\MathLib.h"
//#include "GlutStuff.h"
#include "GL_ShapeDrawer.h"
#include "GLDebugDrawer.h"
class cPhysicsManager : public cResourceManager, public cSingleton<cPhysicsManager>
{
friend class cSingleton<cPhysicsManager>;
public:
bool Init();
bool Deinit();
void Update(float lfTimestep); // Function to update the world
void Render(); //para renderizar los collision shape
//void RenderObjectDebug(const btTransform& worldTransform, const btCollisionShape* shape, const btVector3& color);
btDiscreteDynamicsWorld* GetDynamicsWorld(void) { return mpbtDynamicsWorld;}
//btDynamicsWorld* GetDynamicsWorld(void) { return mpbtDynamicsWorld;}
//void LoadObjectsXmlCollision();
//inline void SetDebugMode (bool lbDebugMode) { mbDebugMode = lbDebugMode; }
//inline bool GetDebugMode () { return mbDebugMode; }
//void AddCollisionShape (btCollisionShape* lbtCollShape) { mabtCollisionShapes.push_back(lbtCollShape); }
//void InitAllPhysics();
//cPhysicsObject* GetPhysicsObjectPtr (const string lsType, const string lsModelName);
void Disable(void);
inline int GetDebugMode() { return miDebugMode; }
inline void SetDebugMode (int liDebugMode) { miDebugMode = liDebugMode; }
void CambiarDebugMode();
//bool GetIdle() const { return mbIdle; }
//void SetIdle(bool lbIdle) { mbIdle = lbIdle; }
private:
btDiscreteDynamicsWorld* mpbtDynamicsWorld;
//btDynamicsWorld* mpbtDynamicsWorld;
btBroadphaseInterface* mpBroadphase;
btDefaultCollisionConfiguration* mpCollisionConfiguration;
btCollisionDispatcher* mpDispatcher;
btSequentialImpulseConstraintSolver* mpSolver;
int miDebugMode;
//bool mbDebugMode;
GL_ShapeDrawer* mpShapeDrawer;
bool mEnableshadows;
GLDebugDrawer* mpbtDebugDrawer;
//bool mbIdle;
//btAlignedObjectArray<btCollisionShape*> mabtCollisionShapes;
//typedef std::vector<cPhysicsObject *> cPhysicsObjectList;
//cPhysicsObjectList mPhysicsObject; //Objetos en general que no se donde clasificarlos por ahora ....
//cPhysicsObjectList mPhysicsPlayer;
//cPhysicsObjectList mPhysicsPista;
//cPhysicsObjectList mPhysicsVehicle;
//std::string msFilename; // Resources or Properties file
void RenderWorldDebug();
void MyInit();
void RenderMe();
void RenderScene(int liPass);
//Sería interesante poner una lista de fisica asi como tenemos estrucurada la lista de objectos??
};
#endif
| [
"yormanh@f2da8aa9-0175-0678-5dcd-d323193514b7",
"[email protected]@f2da8aa9-0175-0678-5dcd-d323193514b7",
"davidvargas.tenerife@f2da8aa9-0175-0678-5dcd-d323193514b7",
"[email protected]@f2da8aa9-0175-0678-5dcd-d323193514b7"
]
| [
[
[
1,
8
],
[
10,
11
],
[
16,
21
],
[
24,
28
],
[
30,
31
],
[
33,
35
],
[
37,
43
],
[
45,
48
],
[
54,
56
],
[
62,
66
],
[
68,
77
],
[
79,
79
],
[
81,
83
],
[
89,
91
]
],
[
[
9,
9
],
[
14,
15
],
[
22,
23
],
[
32,
32
],
[
36,
36
],
[
49,
53
],
[
61,
61
],
[
67,
67
],
[
78,
78
],
[
80,
80
],
[
84,
88
]
],
[
[
12,
13
],
[
29,
29
],
[
57,
60
]
],
[
[
44,
44
]
]
]
|
b07568864883ced7526a4e571b3bb19b8bdf142a | 38926bfe477f933a307f51376dd3c356e7893ffc | /Source/GameDLL/ItemEvents.cpp | 60a7f8478b7996464af21fd57263f724b0a221a7 | []
| no_license | richmondx/dead6 | b0e9dd94a0ebb297c0c6e9c4f24c6482ef4d5161 | 955f76f35d94ed5f991871407f3d3ad83f06a530 | refs/heads/master | 2021-12-05T14:32:01.782047 | 2008-01-01T13:13:39 | 2008-01-01T13:13:39 | null | 0 | 0 | null | null | null | null | WINDOWS-1250 | C++ | false | false | 6,950 | cpp | /*************************************************************************
Crytek Source File.
Copyright (C), Crytek Studios, 2001-2004.
-------------------------------------------------------------------------
$Id$
$DateTime$
-------------------------------------------------------------------------
History:
- 5:9:2005 14:55 : Created by Márcio Martins
*************************************************************************/
#include "StdAfx.h"
#include "Item.h"
#include "IActorSystem.h"
#include "Actor.h"
#include "Game.h"
#include "OffHand.h"
//------------------------------------------------------------------------
void CItem::OnStartUsing()
{
}
//------------------------------------------------------------------------
void CItem::OnStopUsing()
{
}
//------------------------------------------------------------------------
void CItem::OnSelect(bool select)
{
}
//------------------------------------------------------------------------
void CItem::OnSelected(bool selected)
{
}
//------------------------------------------------------------------------
void CItem::OnEnterFirstPerson()
{
EnableUpdate(true, eIUS_General);
EnableHiddenSkinning(true);
SetViewMode(eIVM_FirstPerson);
AttachToHand(false);
AttachArms(true, true);
RestoreLayers();
/*
if(m_stats.mounted)
{
ICharacterInstance* pChar = GetOwnerActor()?GetOwnerActor()->GetEntity()->GetCharacter(0):NULL;
if(pChar)
pChar->HideMaster(1);
}*/
}
//------------------------------------------------------------------------
void CItem::OnEnterThirdPerson()
{
EnableHiddenSkinning(false);
AttachToHand(true);
AttachArms(false, false);
SetViewMode(eIVM_ThirdPerson);
/*
if(m_stats.mounted)
{
ICharacterInstance* pChar = GetOwnerActor()?GetOwnerActor()->GetEntity()->GetCharacter(0):NULL;
if(pChar)
pChar->HideMaster(0);
}*/
}
//------------------------------------------------------------------------
void CItem::OnReset()
{
//Hidden entities must have physics disabled
if(!GetEntity()->IsHidden())
GetEntity()->EnablePhysics(true);
DestroyedGeometry(false);
m_stats.health = m_properties.hitpoints;
UpdateDamageLevel();
if(m_params.scopeAttachment)
DrawSlot(CItem::eIGS_Aux1,false); //Hide secondary FP scope
if (m_properties.mounted && m_params.mountable)
{
MountAt(GetEntity()->GetWorldPos());
SEntityPhysicalizeParams params;
params.mass = 0;
params.nSlot = -1; // todo: -1 doesn't work for characters
params.type = PE_STATIC;
GetEntity()->Physicalize(params);
}
else
{
SetViewMode(eIVM_ThirdPerson);
if (m_properties.pickable)
{
Physicalize(true, m_properties.physics);
Pickalize(true, false);
}
else
Physicalize(m_properties.physics, true);
}
GetEntity()->InvalidateTM();
}
//------------------------------------------------------------------------
void CItem::OnHit(float damage, const char* damageType)
{
if(!m_properties.hitpoints)
return;
if(damageType && !stricmp(damageType, "repair"))
{
if (m_stats.health < m_properties.hitpoints) //repair only to maximum
{
bool destroyed = m_stats.health<=0.f;
m_stats.health = min(float(m_properties.hitpoints),m_stats.health+damage);
UpdateDamageLevel();
if(destroyed && m_stats.health>0.f)
OnRepaired();
}
}
else
{
if (m_stats.health > 0.0f)
{
m_stats.health -= damage;
UpdateDamageLevel();
if (m_stats.health <= 0.0f)
{
m_stats.health = 0.0f;
OnDestroyed();
int n=(int)m_damageLevels.size();
for (int i=0;i<n; ++i)
{
SDamageLevel &level=m_damageLevels[i];
if (level.min_health==0 && level.max_health==0)
{
int slot=(m_stats.viewmode&eIVM_FirstPerson)?eIGS_FirstPerson:eIGS_ThirdPerson;
SpawnEffect(slot, level.effect, level.helper, Vec3Constants<float>::fVec3_Zero,
Vec3Constants<float>::fVec3_OneZ, level.scale);
}
}
}
}
}
}
//------------------------------------------------------------------------
void CItem::UpdateDamageLevel()
{
if (m_properties.hitpoints<=0 || m_damageLevels.empty())
return;
int slot=(m_stats.viewmode&eIVM_FirstPerson)?eIGS_FirstPerson:eIGS_ThirdPerson;
int n=(int)m_damageLevels.size();
int health=(int)((100.0f*MAX(0.0f, m_stats.health))/m_properties.hitpoints);
for (int i=0;i<n; ++i)
{
SDamageLevel &level=m_damageLevels[i];
if (level.min_health==0 && level.max_health==0)
continue;
if (level.min_health<=health && health<level.max_health)
{
if (level.effectId==-1)
level.effectId=AttachEffect(slot, 0, true, level.effect.c_str(), level.helper.c_str(),
Vec3Constants<float>::fVec3_Zero, Vec3Constants<float>::fVec3_OneZ, level.scale, true);
}
else if (level.effectId!=-1)
{
AttachEffect(0, level.effectId, false);
level.effectId=-1;
}
}
}
//------------------------------------------------------------------------
void CItem::OnDestroyed()
{
/* MR, 2007-02-09: shouldn't be needed
for (int i=0; i<eIGS_Last; i++)
{
ICharacterInstance *pCharacter = GetEntity()->GetCharacter(i);
if (pCharacter)
pCharacter->SetAnimationSpeed(0);
}*/
DestroyedGeometry(true);
if(!gEnv->pSystem->IsSerializingFile()) //don't replay destroy animations/effects
PlayAction(g_pItemStrings->destroy);
EnableUpdate(false);
}
//------------------------------------------------------------------------
void CItem::OnRepaired()
{
for (int i=0; i<eIGS_Last; i++)
{
ICharacterInstance *pCharacter = GetEntity()->GetCharacter(i);
if (pCharacter)
pCharacter->SetAnimationSpeed(1.0f);
}
DestroyedGeometry(false);
EnableUpdate(true);
}
//------------------------------------------------------------------------
void CItem::OnDropped(EntityId actorId)
{
m_pItemSystem->RegisterForCollection(GetEntityId());
}
//------------------------------------------------------------------------
void CItem::OnPickedUp(EntityId actorId, bool destroyed)
{
if(GetISystem()->IsSerializingFile() == 1)
return;
CActor *pActor=GetActor(actorId);
if (!pActor)
return;
if(gEnv->bMultiplayer && pActor->IsClient() && IsSelected())
{
COffHand* pOffHand = static_cast<COffHand*>(pActor->GetWeaponByClass(CItem::sOffHandClass));
if(pOffHand && pOffHand->GetOffHandState()==eOHS_HOLDING_GRENADE)
pOffHand->FinishAction(eOHA_RESET);
}
if (!IsServer())
return;
//if (destroyed && m_params.unique)
{
if (!m_bonusAccessoryAmmo.empty())
{
for (TAccessoryAmmoMap::iterator it=m_bonusAccessoryAmmo.begin(); it!=m_bonusAccessoryAmmo.end(); ++it)
{
int count=it->second;
AddAccessoryAmmoToInventory(it->first,count,pActor);
}
m_bonusAccessoryAmmo.clear();
}
}
m_pItemSystem->UnregisterForCollection(GetEntityId());
}
| [
"[email protected]",
"kkirst@c5e09591-5635-0410-80e3-0b71df3ecc31"
]
| [
[
[
1,
17
],
[
19,
49
],
[
53,
53
],
[
59,
67
],
[
75,
79
],
[
83,
88
],
[
92,
209
],
[
212,
233
],
[
235,
246
],
[
258,
264
],
[
266,
270
],
[
274,
274
]
],
[
[
18,
18
],
[
50,
52
],
[
54,
58
],
[
68,
74
],
[
80,
82
],
[
89,
91
],
[
210,
211
],
[
234,
234
],
[
247,
257
],
[
265,
265
],
[
271,
273
]
]
]
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.