G4-ExampleB1/src/PrimaryGeneratorAction.cc

68 lines
2.5 KiB
C++

#include "PrimaryGeneratorAction.hh"
#include "G4Box.hh"
#include "G4LogicalVolume.hh"
#include "G4LogicalVolumeStore.hh"
#include "G4ParticleDefinition.hh"
#include "G4ParticleGun.hh"
#include "G4ParticleTable.hh"
#include "G4RunManager.hh"
#include "G4SystemOfUnits.hh"
#include "Randomize.hh"
namespace B1 {
PrimaryGeneratorAction::PrimaryGeneratorAction() {
// 初始化粒子枪,每个 event 有 n_particle 个粒子
G4int n_particle = 1;
fParticleGun = new G4ParticleGun(n_particle);
// default particle kinematic
// 粒子列表的查找器
G4ParticleTable* particleTable = G4ParticleTable::GetParticleTable();
// 设置为 6 MeV 沿 z 轴正方向的 gamma 源
G4ParticleDefinition* particle = particleTable->FindParticle("gamma");
fParticleGun->SetParticleDefinition(particle);
fParticleGun->SetParticleMomentumDirection(G4ThreeVector(0., 0., 1.));
fParticleGun->SetParticleEnergy(6. * MeV);
}
PrimaryGeneratorAction::~PrimaryGeneratorAction() { delete fParticleGun; }
// 每次 event 调用一次 this function is called at the begining of ecah event
// 可以设置粒子能谱分布、角度分布、源的位置分布
void PrimaryGeneratorAction::GeneratePrimaries(G4Event* anEvent) {
G4double envSizeXY = 0;
G4double envSizeZ = 0;
// 避免引入 DetectorConstruction 类
// 从 G4LogicalVolumeStore 获取 Envelope volume
if (!fEnvelopeBox) {
G4LogicalVolume* envLV = G4LogicalVolumeStore::GetInstance()->GetVolume("Envelope");
if (envLV) fEnvelopeBox = dynamic_cast<G4Box*>(envLV->GetSolid());
}
// 获取几何参数
if (fEnvelopeBox) {
envSizeXY = fEnvelopeBox->GetXHalfLength() * 2.;
envSizeZ = fEnvelopeBox->GetZHalfLength() * 2.;
} else {
G4ExceptionDescription msg;
msg << "Envelope volume of box shape not found.\n";
msg << "Perhaps you have changed geometry.\n";
msg << "The gun will be place at the center.";
G4Exception("PrimaryGeneratorAction::GeneratePrimaries()", "MyCode0002", JustWarning, msg);
}
// 几何参数用于调整源的空间分布
G4double size = 0.8;
G4double x0 = size * envSizeXY * (G4UniformRand() - 0.5);
G4double y0 = size * envSizeXY * (G4UniformRand() - 0.5);
G4double z0 = -0.5 * envSizeZ;
fParticleGun->SetParticlePosition(G4ThreeVector(x0, y0, z0)); // 设置此次发射的位置
fParticleGun->GeneratePrimaryVertex(anEvent); // 发射粒子
}
} // namespace B1